github.com/docker/engine@v22.0.0-20211208180946-d456264580cf+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/moby/sys/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, errNotRunning(ctr.ID)
    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 err
   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  	if c == nil {
   180  		return containerNotFound(ec.ContainerID)
   181  	}
   182  	logrus.Debugf("starting exec command %s in container %s", ec.ID, c.ID)
   183  	attributes := map[string]string{
   184  		"execID": ec.ID,
   185  	}
   186  	daemon.LogContainerEventWithAttributes(c, "exec_start: "+ec.Entrypoint+" "+strings.Join(ec.Args, " "), attributes)
   187  
   188  	defer func() {
   189  		if err != nil {
   190  			ec.Lock()
   191  			ec.Running = false
   192  			exitCode := 126
   193  			ec.ExitCode = &exitCode
   194  			if err := ec.CloseStreams(); err != nil {
   195  				logrus.Errorf("failed to cleanup exec %s streams: %s", c.ID, err)
   196  			}
   197  			ec.Unlock()
   198  			c.ExecCommands.Delete(ec.ID, ec.Pid)
   199  		}
   200  	}()
   201  
   202  	if ec.OpenStdin && stdin != nil {
   203  		r, w := io.Pipe()
   204  		go func() {
   205  			defer w.Close()
   206  			defer logrus.Debug("Closing buffered stdin pipe")
   207  			pools.Copy(w, stdin)
   208  		}()
   209  		cStdin = r
   210  	}
   211  	if ec.OpenStdout {
   212  		cStdout = stdout
   213  	}
   214  	if ec.OpenStderr {
   215  		cStderr = stderr
   216  	}
   217  
   218  	if ec.OpenStdin {
   219  		ec.StreamConfig.NewInputPipes()
   220  	} else {
   221  		ec.StreamConfig.NewNopInputPipe()
   222  	}
   223  
   224  	p := &specs.Process{}
   225  	if runtime.GOOS != "windows" {
   226  		ctr, err := daemon.containerdCli.LoadContainer(ctx, ec.ContainerID)
   227  		if err != nil {
   228  			return err
   229  		}
   230  		spec, err := ctr.Spec(ctx)
   231  		if err != nil {
   232  			return err
   233  		}
   234  		p = spec.Process
   235  	}
   236  	p.Args = append([]string{ec.Entrypoint}, ec.Args...)
   237  	p.Env = ec.Env
   238  	p.Cwd = ec.WorkingDir
   239  	p.Terminal = ec.Tty
   240  
   241  	if p.Cwd == "" {
   242  		p.Cwd = "/"
   243  	}
   244  
   245  	if err := daemon.execSetPlatformOpt(c, ec, p); err != nil {
   246  		return err
   247  	}
   248  
   249  	attachConfig := stream.AttachConfig{
   250  		TTY:        ec.Tty,
   251  		UseStdin:   cStdin != nil,
   252  		UseStdout:  cStdout != nil,
   253  		UseStderr:  cStderr != nil,
   254  		Stdin:      cStdin,
   255  		Stdout:     cStdout,
   256  		Stderr:     cStderr,
   257  		DetachKeys: ec.DetachKeys,
   258  		CloseStdin: true,
   259  	}
   260  	ec.StreamConfig.AttachStreams(&attachConfig)
   261  	attachErr := ec.StreamConfig.CopyStreams(ctx, &attachConfig)
   262  
   263  	// Synchronize with libcontainerd event loop
   264  	ec.Lock()
   265  	c.ExecCommands.Lock()
   266  	systemPid, err := daemon.containerd.Exec(ctx, c.ID, ec.ID, p, cStdin != nil, ec.InitializeStdio)
   267  	// the exec context should be ready, or error happened.
   268  	// close the chan to notify readiness
   269  	close(ec.Started)
   270  	if err != nil {
   271  		c.ExecCommands.Unlock()
   272  		ec.Unlock()
   273  		return translateContainerdStartErr(ec.Entrypoint, ec.SetExitCode, err)
   274  	}
   275  	ec.Pid = systemPid
   276  	c.ExecCommands.Unlock()
   277  	ec.Unlock()
   278  
   279  	select {
   280  	case <-ctx.Done():
   281  		logrus.Debugf("Sending TERM signal to process %v in container %v", name, c.ID)
   282  		daemon.containerd.SignalProcess(ctx, c.ID, name, int(signal.SignalMap["TERM"]))
   283  
   284  		timeout := time.NewTimer(termProcessTimeout)
   285  		defer timeout.Stop()
   286  
   287  		select {
   288  		case <-timeout.C:
   289  			logrus.Infof("Container %v, process %v failed to exit within %v of signal TERM - using the force", c.ID, name, termProcessTimeout)
   290  			daemon.containerd.SignalProcess(ctx, c.ID, name, int(signal.SignalMap["KILL"]))
   291  		case <-attachErr:
   292  			// TERM signal worked
   293  		}
   294  		return ctx.Err()
   295  	case err := <-attachErr:
   296  		if err != nil {
   297  			if _, ok := err.(term.EscapeError); !ok {
   298  				return errdefs.System(errors.Wrap(err, "exec attach failed"))
   299  			}
   300  			attributes := map[string]string{
   301  				"execID": ec.ID,
   302  			}
   303  			daemon.LogContainerEventWithAttributes(c, "exec_detach", attributes)
   304  		}
   305  	}
   306  	return nil
   307  }
   308  
   309  // execCommandGC runs a ticker to clean up the daemon references
   310  // of exec configs that are no longer part of the container.
   311  func (daemon *Daemon) execCommandGC() {
   312  	for range time.Tick(5 * time.Minute) {
   313  		var (
   314  			cleaned          int
   315  			liveExecCommands = daemon.containerExecIds()
   316  		)
   317  		for id, config := range daemon.execCommands.Commands() {
   318  			if config.CanRemove {
   319  				cleaned++
   320  				daemon.execCommands.Delete(id, config.Pid)
   321  			} else {
   322  				if _, exists := liveExecCommands[id]; !exists {
   323  					config.CanRemove = true
   324  				}
   325  			}
   326  		}
   327  		if cleaned > 0 {
   328  			logrus.Debugf("clean %d unused exec commands", cleaned)
   329  		}
   330  	}
   331  }
   332  
   333  // containerExecIds returns a list of all the current exec ids that are in use
   334  // and running inside a container.
   335  func (daemon *Daemon) containerExecIds() map[string]struct{} {
   336  	ids := map[string]struct{}{}
   337  	for _, c := range daemon.containers.List() {
   338  		for _, id := range c.ExecCommands.List() {
   339  			ids[id] = struct{}{}
   340  		}
   341  	}
   342  	return ids
   343  }