attach.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 remotecommand
  14. import (
  15. "fmt"
  16. "io"
  17. "net/http"
  18. "time"
  19. apierrors "k8s.io/kubernetes/pkg/api/errors"
  20. "k8s.io/kubernetes/pkg/api/unversioned"
  21. "k8s.io/kubernetes/pkg/types"
  22. "k8s.io/kubernetes/pkg/util/runtime"
  23. "k8s.io/kubernetes/pkg/util/term"
  24. )
  25. // Attacher knows how to attach to a running container in a pod.
  26. type Attacher interface {
  27. // AttachContainer attaches to the running container in the pod, copying data between in/out/err
  28. // and the container's stdin/stdout/stderr.
  29. AttachContainer(name string, uid types.UID, container string, in io.Reader, out, err io.WriteCloser, tty bool, resize <-chan term.Size) error
  30. }
  31. // ServeAttach handles requests to attach to a container. After creating/receiving the required
  32. // streams, it delegates the actual attaching to attacher.
  33. func ServeAttach(w http.ResponseWriter, req *http.Request, attacher Attacher, podName string, uid types.UID, container string, idleTimeout, streamCreationTimeout time.Duration, supportedProtocols []string) {
  34. ctx, ok := createStreams(req, w, supportedProtocols, idleTimeout, streamCreationTimeout)
  35. if !ok {
  36. // error is handled by createStreams
  37. return
  38. }
  39. defer ctx.conn.Close()
  40. err := attacher.AttachContainer(podName, uid, container, ctx.stdinStream, ctx.stdoutStream, ctx.stderrStream, ctx.tty, ctx.resizeChan)
  41. if err != nil {
  42. err = fmt.Errorf("error attaching to container: %v", err)
  43. runtime.HandleError(err)
  44. ctx.writeStatus(apierrors.NewInternalError(err))
  45. } else {
  46. ctx.writeStatus(&apierrors.StatusError{ErrStatus: unversioned.Status{
  47. Status: unversioned.StatusSuccess,
  48. }})
  49. }
  50. }