exec.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. package daemon
  2. import (
  3. "fmt"
  4. "io"
  5. "strings"
  6. "time"
  7. "golang.org/x/net/context"
  8. "github.com/Sirupsen/logrus"
  9. "github.com/docker/docker/api/errors"
  10. "github.com/docker/docker/api/types"
  11. "github.com/docker/docker/api/types/strslice"
  12. "github.com/docker/docker/container"
  13. "github.com/docker/docker/daemon/exec"
  14. "github.com/docker/docker/libcontainerd"
  15. "github.com/docker/docker/pkg/pools"
  16. "github.com/docker/docker/pkg/signal"
  17. "github.com/docker/docker/pkg/term"
  18. "github.com/docker/docker/utils"
  19. )
  20. // Seconds to wait after sending TERM before trying KILL
  21. const termProcessTimeout = 10
  22. func (d *Daemon) registerExecCommand(container *container.Container, config *exec.Config) {
  23. // Storing execs in container in order to kill them gracefully whenever the container is stopped or removed.
  24. container.ExecCommands.Add(config.ID, config)
  25. // Storing execs in daemon for easy access via Engine API.
  26. d.execCommands.Add(config.ID, config)
  27. }
  28. // ExecExists looks up the exec instance and returns a bool if it exists or not.
  29. // It will also return the error produced by `getConfig`
  30. func (d *Daemon) ExecExists(name string) (bool, error) {
  31. if _, err := d.getExecConfig(name); err != nil {
  32. return false, err
  33. }
  34. return true, nil
  35. }
  36. // getExecConfig looks up the exec instance by name. If the container associated
  37. // with the exec instance is stopped or paused, it will return an error.
  38. func (d *Daemon) getExecConfig(name string) (*exec.Config, error) {
  39. ec := d.execCommands.Get(name)
  40. // If the exec is found but its container is not in the daemon's list of
  41. // containers then it must have been deleted, in which case instead of
  42. // saying the container isn't running, we should return a 404 so that
  43. // the user sees the same error now that they will after the
  44. // 5 minute clean-up loop is run which erases old/dead execs.
  45. if ec != nil {
  46. if container := d.containers.Get(ec.ContainerID); container != nil {
  47. if !container.IsRunning() {
  48. return nil, fmt.Errorf("Container %s is not running: %s", container.ID, container.State.String())
  49. }
  50. if container.IsPaused() {
  51. return nil, errExecPaused(container.ID)
  52. }
  53. if container.IsRestarting() {
  54. return nil, errContainerIsRestarting(container.ID)
  55. }
  56. return ec, nil
  57. }
  58. }
  59. return nil, errExecNotFound(name)
  60. }
  61. func (d *Daemon) unregisterExecCommand(container *container.Container, execConfig *exec.Config) {
  62. container.ExecCommands.Delete(execConfig.ID)
  63. d.execCommands.Delete(execConfig.ID)
  64. }
  65. func (d *Daemon) getActiveContainer(name string) (*container.Container, error) {
  66. container, err := d.GetContainer(name)
  67. if err != nil {
  68. return nil, err
  69. }
  70. if !container.IsRunning() {
  71. return nil, errNotRunning{container.ID}
  72. }
  73. if container.IsPaused() {
  74. return nil, errExecPaused(name)
  75. }
  76. if container.IsRestarting() {
  77. return nil, errContainerIsRestarting(container.ID)
  78. }
  79. return container, nil
  80. }
  81. // ContainerExecCreate sets up an exec in a running container.
  82. func (d *Daemon) ContainerExecCreate(name string, config *types.ExecConfig) (string, error) {
  83. container, err := d.getActiveContainer(name)
  84. if err != nil {
  85. return "", err
  86. }
  87. cmd := strslice.StrSlice(config.Cmd)
  88. entrypoint, args := d.getEntrypointAndArgs(strslice.StrSlice{}, cmd)
  89. keys := []byte{}
  90. if config.DetachKeys != "" {
  91. keys, err = term.ToBytes(config.DetachKeys)
  92. if err != nil {
  93. err = fmt.Errorf("Invalid escape keys (%s) provided", config.DetachKeys)
  94. return "", err
  95. }
  96. }
  97. execConfig := exec.NewConfig()
  98. execConfig.OpenStdin = config.AttachStdin
  99. execConfig.OpenStdout = config.AttachStdout
  100. execConfig.OpenStderr = config.AttachStderr
  101. execConfig.ContainerID = container.ID
  102. execConfig.DetachKeys = keys
  103. execConfig.Entrypoint = entrypoint
  104. execConfig.Args = args
  105. execConfig.Tty = config.Tty
  106. execConfig.Privileged = config.Privileged
  107. execConfig.User = config.User
  108. linkedEnv, err := d.setupLinkedContainers(container)
  109. if err != nil {
  110. return "", err
  111. }
  112. execConfig.Env = utils.ReplaceOrAppendEnvValues(container.CreateDaemonEnvironment(config.Tty, linkedEnv), config.Env)
  113. if len(execConfig.User) == 0 {
  114. execConfig.User = container.Config.User
  115. }
  116. d.registerExecCommand(container, execConfig)
  117. d.LogContainerEvent(container, "exec_create: "+execConfig.Entrypoint+" "+strings.Join(execConfig.Args, " "))
  118. return execConfig.ID, nil
  119. }
  120. // ContainerExecStart starts a previously set up exec instance. The
  121. // std streams are set up.
  122. // If ctx is cancelled, the process is terminated.
  123. func (d *Daemon) ContainerExecStart(ctx context.Context, name string, stdin io.ReadCloser, stdout io.Writer, stderr io.Writer) (err error) {
  124. var (
  125. cStdin io.ReadCloser
  126. cStdout, cStderr io.Writer
  127. )
  128. ec, err := d.getExecConfig(name)
  129. if err != nil {
  130. return errExecNotFound(name)
  131. }
  132. ec.Lock()
  133. if ec.ExitCode != nil {
  134. ec.Unlock()
  135. err := fmt.Errorf("Error: Exec command %s has already run", ec.ID)
  136. return errors.NewRequestConflictError(err)
  137. }
  138. if ec.Running {
  139. ec.Unlock()
  140. return fmt.Errorf("Error: Exec command %s is already running", ec.ID)
  141. }
  142. ec.Running = true
  143. defer func() {
  144. if err != nil {
  145. ec.Running = false
  146. exitCode := 126
  147. ec.ExitCode = &exitCode
  148. }
  149. }()
  150. ec.Unlock()
  151. c := d.containers.Get(ec.ContainerID)
  152. logrus.Debugf("starting exec command %s in container %s", ec.ID, c.ID)
  153. d.LogContainerEvent(c, "exec_start: "+ec.Entrypoint+" "+strings.Join(ec.Args, " "))
  154. if ec.OpenStdin && stdin != nil {
  155. r, w := io.Pipe()
  156. go func() {
  157. defer w.Close()
  158. defer logrus.Debug("Closing buffered stdin pipe")
  159. pools.Copy(w, stdin)
  160. }()
  161. cStdin = r
  162. }
  163. if ec.OpenStdout {
  164. cStdout = stdout
  165. }
  166. if ec.OpenStderr {
  167. cStderr = stderr
  168. }
  169. if ec.OpenStdin {
  170. ec.StreamConfig.NewInputPipes()
  171. } else {
  172. ec.StreamConfig.NewNopInputPipe()
  173. }
  174. p := libcontainerd.Process{
  175. Args: append([]string{ec.Entrypoint}, ec.Args...),
  176. Env: ec.Env,
  177. Terminal: ec.Tty,
  178. }
  179. if err := execSetPlatformOpt(c, ec, &p); err != nil {
  180. return err
  181. }
  182. attachErr := container.AttachStreams(ctx, ec.StreamConfig, ec.OpenStdin, true, ec.Tty, cStdin, cStdout, cStderr, ec.DetachKeys)
  183. systemPid, err := d.containerd.AddProcess(ctx, c.ID, name, p, ec.InitializeStdio)
  184. if err != nil {
  185. return err
  186. }
  187. ec.Lock()
  188. ec.Pid = systemPid
  189. ec.Unlock()
  190. select {
  191. case <-ctx.Done():
  192. logrus.Debugf("Sending TERM signal to process %v in container %v", name, c.ID)
  193. d.containerd.SignalProcess(c.ID, name, int(signal.SignalMap["TERM"]))
  194. select {
  195. case <-time.After(termProcessTimeout * time.Second):
  196. logrus.Infof("Container %v, process %v failed to exit within %d seconds of signal TERM - using the force", c.ID, name, termProcessTimeout)
  197. d.containerd.SignalProcess(c.ID, name, int(signal.SignalMap["KILL"]))
  198. case <-attachErr:
  199. // TERM signal worked
  200. }
  201. return fmt.Errorf("context cancelled")
  202. case err := <-attachErr:
  203. if err != nil {
  204. if _, ok := err.(container.DetachError); !ok {
  205. return fmt.Errorf("exec attach failed with error: %v", err)
  206. }
  207. d.LogContainerEvent(c, "exec_detach")
  208. }
  209. }
  210. return nil
  211. }
  212. // execCommandGC runs a ticker to clean up the daemon references
  213. // of exec configs that are no longer part of the container.
  214. func (d *Daemon) execCommandGC() {
  215. for range time.Tick(5 * time.Minute) {
  216. var (
  217. cleaned int
  218. liveExecCommands = d.containerExecIds()
  219. )
  220. for id, config := range d.execCommands.Commands() {
  221. if config.CanRemove {
  222. cleaned++
  223. d.execCommands.Delete(id)
  224. } else {
  225. if _, exists := liveExecCommands[id]; !exists {
  226. config.CanRemove = true
  227. }
  228. }
  229. }
  230. if cleaned > 0 {
  231. logrus.Debugf("clean %d unused exec commands", cleaned)
  232. }
  233. }
  234. }
  235. // containerExecIds returns a list of all the current exec ids that are in use
  236. // and running inside a container.
  237. func (d *Daemon) containerExecIds() map[string]struct{} {
  238. ids := map[string]struct{}{}
  239. for _, c := range d.containers.List() {
  240. for _, id := range c.ExecCommands.List() {
  241. ids[id] = struct{}{}
  242. }
  243. }
  244. return ids
  245. }