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