github.com/devdivbcp/moby@v17.12.0-ce-rc1.0.20200726071732-2d4bfdc789ad+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/docker/docker/pkg/term"
    20  	"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
    27  
    28  func (d *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  	d.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 (d *Daemon) ExecExists(name string) (bool, error) {
    38  	if _, err := d.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 (d *Daemon) getExecConfig(name string) (*exec.Config, error) {
    47  	ec := d.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  	container := d.containers.Get(ec.ContainerID)
    58  	if container == nil {
    59  		return nil, containerNotFound(name)
    60  	}
    61  	if !container.IsRunning() {
    62  		return nil, fmt.Errorf("Container %s is not running: %s", container.ID, container.State.String())
    63  	}
    64  	if container.IsPaused() {
    65  		return nil, errExecPaused(container.ID)
    66  	}
    67  	if container.IsRestarting() {
    68  		return nil, errContainerIsRestarting(container.ID)
    69  	}
    70  	return ec, nil
    71  }
    72  
    73  func (d *Daemon) unregisterExecCommand(container *container.Container, execConfig *exec.Config) {
    74  	container.ExecCommands.Delete(execConfig.ID, execConfig.Pid)
    75  	d.execCommands.Delete(execConfig.ID, execConfig.Pid)
    76  }
    77  
    78  func (d *Daemon) getActiveContainer(name string) (*container.Container, error) {
    79  	container, err := d.GetContainer(name)
    80  	if err != nil {
    81  		return nil, err
    82  	}
    83  
    84  	if !container.IsRunning() {
    85  		return nil, errNotRunning(container.ID)
    86  	}
    87  	if container.IsPaused() {
    88  		return nil, errExecPaused(name)
    89  	}
    90  	if container.IsRestarting() {
    91  		return nil, errContainerIsRestarting(container.ID)
    92  	}
    93  	return container, nil
    94  }
    95  
    96  // ContainerExecCreate sets up an exec in a running container.
    97  func (d *Daemon) ContainerExecCreate(name string, config *types.ExecConfig) (string, error) {
    98  	cntr, err := d.getActiveContainer(name)
    99  	if err != nil {
   100  		return "", err
   101  	}
   102  
   103  	cmd := strslice.StrSlice(config.Cmd)
   104  	entrypoint, args := d.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 := d.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  	d.registerExecCommand(cntr, execConfig)
   141  
   142  	attributes := map[string]string{
   143  		"execID": execConfig.ID,
   144  	}
   145  	d.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 (d *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 := d.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 := d.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  	d.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  		container, err := d.containerdCli.LoadContainer(ctx, ec.ContainerID)
   224  		if err != nil {
   225  			return err
   226  		}
   227  		spec, err := container.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 := d.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 := d.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  		d.containerd.SignalProcess(ctx, c.ID, name, int(signal.SignalMap["TERM"]))
   280  		select {
   281  		case <-time.After(termProcessTimeout * time.Second):
   282  			logrus.Infof("Container %v, process %v failed to exit within %d seconds of signal TERM - using the force", c.ID, name, termProcessTimeout)
   283  			d.containerd.SignalProcess(ctx, c.ID, name, int(signal.SignalMap["KILL"]))
   284  		case <-attachErr:
   285  			// TERM signal worked
   286  		}
   287  		return ctx.Err()
   288  	case err := <-attachErr:
   289  		if err != nil {
   290  			if _, ok := err.(term.EscapeError); !ok {
   291  				return errdefs.System(errors.Wrap(err, "exec attach failed"))
   292  			}
   293  			attributes := map[string]string{
   294  				"execID": ec.ID,
   295  			}
   296  			d.LogContainerEventWithAttributes(c, "exec_detach", attributes)
   297  		}
   298  	}
   299  	return nil
   300  }
   301  
   302  // execCommandGC runs a ticker to clean up the daemon references
   303  // of exec configs that are no longer part of the container.
   304  func (d *Daemon) execCommandGC() {
   305  	for range time.Tick(5 * time.Minute) {
   306  		var (
   307  			cleaned          int
   308  			liveExecCommands = d.containerExecIds()
   309  		)
   310  		for id, config := range d.execCommands.Commands() {
   311  			if config.CanRemove {
   312  				cleaned++
   313  				d.execCommands.Delete(id, config.Pid)
   314  			} else {
   315  				if _, exists := liveExecCommands[id]; !exists {
   316  					config.CanRemove = true
   317  				}
   318  			}
   319  		}
   320  		if cleaned > 0 {
   321  			logrus.Debugf("clean %d unused exec commands", cleaned)
   322  		}
   323  	}
   324  }
   325  
   326  // containerExecIds returns a list of all the current exec ids that are in use
   327  // and running inside a container.
   328  func (d *Daemon) containerExecIds() map[string]struct{} {
   329  	ids := map[string]struct{}{}
   330  	for _, c := range d.containers.List() {
   331  		for _, id := range c.ExecCommands.List() {
   332  			ids[id] = struct{}{}
   333  		}
   334  	}
   335  	return ids
   336  }