github.com/docker/docker@v299999999.0.0-20200612211812-aaf470eca7b5+incompatible/daemon/exec.go (about)

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