exec.go 8.7 KB

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