exec.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. /*
  2. Copyright 2015 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 dockershim
  14. import (
  15. "fmt"
  16. "io"
  17. "time"
  18. dockertypes "github.com/docker/docker/api/types"
  19. "k8s.io/klog"
  20. "k8s.io/client-go/tools/remotecommand"
  21. kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
  22. "k8s.io/kubernetes/pkg/kubelet/dockershim/libdocker"
  23. )
  24. // ExecHandler knows how to execute a command in a running Docker container.
  25. type ExecHandler interface {
  26. ExecInContainer(client libdocker.Interface, container *dockertypes.ContainerJSON, cmd []string, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool, resize <-chan remotecommand.TerminalSize, timeout time.Duration) error
  27. }
  28. type dockerExitError struct {
  29. Inspect *dockertypes.ContainerExecInspect
  30. }
  31. func (d *dockerExitError) String() string {
  32. return d.Error()
  33. }
  34. func (d *dockerExitError) Error() string {
  35. return fmt.Sprintf("Error executing in Docker Container: %d", d.Inspect.ExitCode)
  36. }
  37. func (d *dockerExitError) Exited() bool {
  38. return !d.Inspect.Running
  39. }
  40. func (d *dockerExitError) ExitStatus() int {
  41. return d.Inspect.ExitCode
  42. }
  43. // NativeExecHandler executes commands in Docker containers using Docker's exec API.
  44. type NativeExecHandler struct{}
  45. func (*NativeExecHandler) ExecInContainer(client libdocker.Interface, container *dockertypes.ContainerJSON, cmd []string, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool, resize <-chan remotecommand.TerminalSize, timeout time.Duration) error {
  46. done := make(chan struct{})
  47. defer close(done)
  48. createOpts := dockertypes.ExecConfig{
  49. Cmd: cmd,
  50. AttachStdin: stdin != nil,
  51. AttachStdout: stdout != nil,
  52. AttachStderr: stderr != nil,
  53. Tty: tty,
  54. }
  55. execObj, err := client.CreateExec(container.ID, createOpts)
  56. if err != nil {
  57. return fmt.Errorf("failed to exec in container - Exec setup failed - %v", err)
  58. }
  59. // Have to start this before the call to client.StartExec because client.StartExec is a blocking
  60. // call :-( Otherwise, resize events don't get processed and the terminal never resizes.
  61. //
  62. // We also have to delay attempting to send a terminal resize request to docker until after the
  63. // exec has started; otherwise, the initial resize request will fail.
  64. execStarted := make(chan struct{})
  65. go func() {
  66. select {
  67. case <-execStarted:
  68. // client.StartExec has started the exec, so we can start resizing
  69. case <-done:
  70. // ExecInContainer has returned, so short-circuit
  71. return
  72. }
  73. kubecontainer.HandleResizing(resize, func(size remotecommand.TerminalSize) {
  74. client.ResizeExecTTY(execObj.ID, uint(size.Height), uint(size.Width))
  75. })
  76. }()
  77. startOpts := dockertypes.ExecStartCheck{Detach: false, Tty: tty}
  78. streamOpts := libdocker.StreamOptions{
  79. InputStream: stdin,
  80. OutputStream: stdout,
  81. ErrorStream: stderr,
  82. RawTerminal: tty,
  83. ExecStarted: execStarted,
  84. }
  85. err = client.StartExec(execObj.ID, startOpts, streamOpts)
  86. if err != nil {
  87. return err
  88. }
  89. ticker := time.NewTicker(2 * time.Second)
  90. defer ticker.Stop()
  91. count := 0
  92. for {
  93. inspect, err2 := client.InspectExec(execObj.ID)
  94. if err2 != nil {
  95. return err2
  96. }
  97. if !inspect.Running {
  98. if inspect.ExitCode != 0 {
  99. err = &dockerExitError{inspect}
  100. }
  101. break
  102. }
  103. count++
  104. if count == 5 {
  105. klog.Errorf("Exec session %s in container %s terminated but process still running!", execObj.ID, container.ID)
  106. break
  107. }
  108. <-ticker.C
  109. }
  110. return err
  111. }