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