exec.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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/container/stream"
  14. "github.com/docker/docker/daemon/exec"
  15. "github.com/docker/docker/libcontainerd"
  16. "github.com/docker/docker/pkg/pools"
  17. "github.com/docker/docker/pkg/signal"
  18. "github.com/docker/docker/pkg/term"
  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. cntr, 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 = cntr.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(cntr)
  109. if err != nil {
  110. return "", err
  111. }
  112. execConfig.Env = container.ReplaceOrAppendEnvValues(cntr.CreateDaemonEnvironment(config.Tty, linkedEnv), config.Env)
  113. if len(execConfig.User) == 0 {
  114. execConfig.User = cntr.Config.User
  115. }
  116. d.registerExecCommand(cntr, execConfig)
  117. d.LogContainerEvent(cntr, "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. ec.Unlock()
  144. c := d.containers.Get(ec.ContainerID)
  145. logrus.Debugf("starting exec command %s in container %s", ec.ID, c.ID)
  146. d.LogContainerEvent(c, "exec_start: "+ec.Entrypoint+" "+strings.Join(ec.Args, " "))
  147. defer func() {
  148. if err != nil {
  149. ec.Lock()
  150. ec.Running = false
  151. exitCode := 126
  152. ec.ExitCode = &exitCode
  153. if err := ec.CloseStreams(); err != nil {
  154. logrus.Errorf("failed to cleanup exec %s streams: %s", c.ID, err)
  155. }
  156. ec.Unlock()
  157. c.ExecCommands.Delete(ec.ID)
  158. }
  159. }()
  160. if ec.OpenStdin && stdin != nil {
  161. r, w := io.Pipe()
  162. go func() {
  163. defer w.Close()
  164. defer logrus.Debug("Closing buffered stdin pipe")
  165. pools.Copy(w, stdin)
  166. }()
  167. cStdin = r
  168. }
  169. if ec.OpenStdout {
  170. cStdout = stdout
  171. }
  172. if ec.OpenStderr {
  173. cStderr = stderr
  174. }
  175. if ec.OpenStdin {
  176. ec.StreamConfig.NewInputPipes()
  177. } else {
  178. ec.StreamConfig.NewNopInputPipe()
  179. }
  180. p := libcontainerd.Process{
  181. Args: append([]string{ec.Entrypoint}, ec.Args...),
  182. Env: ec.Env,
  183. Terminal: ec.Tty,
  184. }
  185. if err := execSetPlatformOpt(c, ec, &p); err != nil {
  186. return err
  187. }
  188. attachConfig := stream.AttachConfig{
  189. TTY: ec.Tty,
  190. UseStdin: cStdin != nil,
  191. UseStdout: cStdout != nil,
  192. UseStderr: cStderr != nil,
  193. Stdin: cStdin,
  194. Stdout: cStdout,
  195. Stderr: cStderr,
  196. DetachKeys: ec.DetachKeys,
  197. CloseStdin: true,
  198. }
  199. ec.StreamConfig.AttachStreams(&attachConfig)
  200. attachErr := ec.StreamConfig.CopyStreams(ctx, &attachConfig)
  201. systemPid, err := d.containerd.AddProcess(ctx, c.ID, name, p, ec.InitializeStdio)
  202. if err != nil {
  203. return err
  204. }
  205. ec.Lock()
  206. ec.Pid = systemPid
  207. ec.Unlock()
  208. select {
  209. case <-ctx.Done():
  210. logrus.Debugf("Sending TERM signal to process %v in container %v", name, c.ID)
  211. d.containerd.SignalProcess(c.ID, name, int(signal.SignalMap["TERM"]))
  212. select {
  213. case <-time.After(termProcessTimeout * time.Second):
  214. logrus.Infof("Container %v, process %v failed to exit within %d seconds of signal TERM - using the force", c.ID, name, termProcessTimeout)
  215. d.containerd.SignalProcess(c.ID, name, int(signal.SignalMap["KILL"]))
  216. case <-attachErr:
  217. // TERM signal worked
  218. }
  219. return fmt.Errorf("context cancelled")
  220. case err := <-attachErr:
  221. if err != nil {
  222. if _, ok := err.(term.EscapeError); !ok {
  223. return fmt.Errorf("exec attach failed with error: %v", err)
  224. }
  225. d.LogContainerEvent(c, "exec_detach")
  226. }
  227. }
  228. return nil
  229. }
  230. // execCommandGC runs a ticker to clean up the daemon references
  231. // of exec configs that are no longer part of the container.
  232. func (d *Daemon) execCommandGC() {
  233. for range time.Tick(5 * time.Minute) {
  234. var (
  235. cleaned int
  236. liveExecCommands = d.containerExecIds()
  237. )
  238. for id, config := range d.execCommands.Commands() {
  239. if config.CanRemove {
  240. cleaned++
  241. d.execCommands.Delete(id)
  242. } else {
  243. if _, exists := liveExecCommands[id]; !exists {
  244. config.CanRemove = true
  245. }
  246. }
  247. }
  248. if cleaned > 0 {
  249. logrus.Debugf("clean %d unused exec commands", cleaned)
  250. }
  251. }
  252. }
  253. // containerExecIds returns a list of all the current exec ids that are in use
  254. // and running inside a container.
  255. func (d *Daemon) containerExecIds() map[string]struct{} {
  256. ids := map[string]struct{}{}
  257. for _, c := range d.containers.List() {
  258. for _, id := range c.ExecCommands.List() {
  259. ids[id] = struct{}{}
  260. }
  261. }
  262. return ids
  263. }