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