portforward.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /*
  2. Copyright 2016 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package portforward
  14. import (
  15. "io"
  16. "net/http"
  17. "time"
  18. "k8s.io/apimachinery/pkg/types"
  19. "k8s.io/apimachinery/pkg/util/runtime"
  20. "k8s.io/apiserver/pkg/util/wsstream"
  21. )
  22. // PortForwarder knows how to forward content from a data stream to/from a port
  23. // in a pod.
  24. type PortForwarder interface {
  25. // PortForwarder copies data between a data stream and a port in a pod.
  26. PortForward(name string, uid types.UID, port int32, stream io.ReadWriteCloser) error
  27. }
  28. // ServePortForward handles a port forwarding request. A single request is
  29. // kept alive as long as the client is still alive and the connection has not
  30. // been timed out due to idleness. This function handles multiple forwarded
  31. // connections; i.e., multiple `curl http://localhost:8888/` requests will be
  32. // handled by a single invocation of ServePortForward.
  33. func ServePortForward(w http.ResponseWriter, req *http.Request, portForwarder PortForwarder, podName string, uid types.UID, portForwardOptions *V4Options, idleTimeout time.Duration, streamCreationTimeout time.Duration, supportedProtocols []string) {
  34. var err error
  35. if wsstream.IsWebSocketRequest(req) {
  36. err = handleWebSocketStreams(req, w, portForwarder, podName, uid, portForwardOptions, supportedProtocols, idleTimeout, streamCreationTimeout)
  37. } else {
  38. err = handleHTTPStreams(req, w, portForwarder, podName, uid, supportedProtocols, idleTimeout, streamCreationTimeout)
  39. }
  40. if err != nil {
  41. runtime.HandleError(err)
  42. return
  43. }
  44. }