github.com/rhatdan/docker@v0.7.7-0.20180119204836-47a0dcbcd20a/daemon/exec.go (about)

     1  package daemon
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  	"strings"
     7  	"time"
     8  
     9  	"golang.org/x/net/context"
    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  	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
    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  
    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  
    55  	if ec != nil {
    56  		if container := d.containers.Get(ec.ContainerID); container != nil {
    57  			if !container.IsRunning() {
    58  				return nil, fmt.Errorf("Container %s is not running: %s", container.ID, container.State.String())
    59  			}
    60  			if container.IsPaused() {
    61  				return nil, errExecPaused(container.ID)
    62  			}
    63  			if container.IsRestarting() {
    64  				return nil, errContainerIsRestarting(container.ID)
    65  			}
    66  			return ec, nil
    67  		}
    68  	}
    69  
    70  	return nil, errExecNotFound(name)
    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  	d.LogContainerEvent(cntr, "exec_create: "+execConfig.Entrypoint+" "+strings.Join(execConfig.Args, " "))
   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 (d *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 := d.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 := d.containers.Get(ec.ContainerID)
   176  	logrus.Debugf("starting exec command %s in container %s", ec.ID, c.ID)
   177  	d.LogContainerEvent(c, "exec_start: "+ec.Entrypoint+" "+strings.Join(ec.Args, " "))
   178  
   179  	defer func() {
   180  		if err != nil {
   181  			ec.Lock()
   182  			ec.Running = false
   183  			exitCode := 126
   184  			ec.ExitCode = &exitCode
   185  			if err := ec.CloseStreams(); err != nil {
   186  				logrus.Errorf("failed to cleanup exec %s streams: %s", c.ID, err)
   187  			}
   188  			ec.Unlock()
   189  			c.ExecCommands.Delete(ec.ID, ec.Pid)
   190  		}
   191  	}()
   192  
   193  	if ec.OpenStdin && stdin != nil {
   194  		r, w := io.Pipe()
   195  		go func() {
   196  			defer w.Close()
   197  			defer logrus.Debug("Closing buffered stdin pipe")
   198  			pools.Copy(w, stdin)
   199  		}()
   200  		cStdin = r
   201  	}
   202  	if ec.OpenStdout {
   203  		cStdout = stdout
   204  	}
   205  	if ec.OpenStderr {
   206  		cStderr = stderr
   207  	}
   208  
   209  	if ec.OpenStdin {
   210  		ec.StreamConfig.NewInputPipes()
   211  	} else {
   212  		ec.StreamConfig.NewNopInputPipe()
   213  	}
   214  
   215  	p := &specs.Process{
   216  		Args:     append([]string{ec.Entrypoint}, ec.Args...),
   217  		Env:      ec.Env,
   218  		Terminal: ec.Tty,
   219  		Cwd:      ec.WorkingDir,
   220  	}
   221  	if p.Cwd == "" {
   222  		p.Cwd = "/"
   223  	}
   224  
   225  	if err := d.execSetPlatformOpt(c, ec, p); err != nil {
   226  		return err
   227  	}
   228  
   229  	attachConfig := stream.AttachConfig{
   230  		TTY:        ec.Tty,
   231  		UseStdin:   cStdin != nil,
   232  		UseStdout:  cStdout != nil,
   233  		UseStderr:  cStderr != nil,
   234  		Stdin:      cStdin,
   235  		Stdout:     cStdout,
   236  		Stderr:     cStderr,
   237  		DetachKeys: ec.DetachKeys,
   238  		CloseStdin: true,
   239  	}
   240  	ec.StreamConfig.AttachStreams(&attachConfig)
   241  	attachErr := ec.StreamConfig.CopyStreams(ctx, &attachConfig)
   242  
   243  	// Synchronize with libcontainerd event loop
   244  	ec.Lock()
   245  	c.ExecCommands.Lock()
   246  	systemPid, err := d.containerd.Exec(ctx, c.ID, ec.ID, p, cStdin != nil, ec.InitializeStdio)
   247  	if err != nil {
   248  		c.ExecCommands.Unlock()
   249  		ec.Unlock()
   250  		return translateContainerdStartErr(ec.Entrypoint, ec.SetExitCode, err)
   251  	}
   252  	ec.Pid = systemPid
   253  	c.ExecCommands.Unlock()
   254  	ec.Unlock()
   255  
   256  	select {
   257  	case <-ctx.Done():
   258  		logrus.Debugf("Sending TERM signal to process %v in container %v", name, c.ID)
   259  		d.containerd.SignalProcess(ctx, c.ID, name, int(signal.SignalMap["TERM"]))
   260  		select {
   261  		case <-time.After(termProcessTimeout * time.Second):
   262  			logrus.Infof("Container %v, process %v failed to exit within %d seconds of signal TERM - using the force", c.ID, name, termProcessTimeout)
   263  			d.containerd.SignalProcess(ctx, c.ID, name, int(signal.SignalMap["KILL"]))
   264  		case <-attachErr:
   265  			// TERM signal worked
   266  		}
   267  		return fmt.Errorf("context cancelled")
   268  	case err := <-attachErr:
   269  		if err != nil {
   270  			if _, ok := err.(term.EscapeError); !ok {
   271  				return errdefs.System(errors.Wrap(err, "exec attach failed"))
   272  			}
   273  			d.LogContainerEvent(c, "exec_detach")
   274  		}
   275  	}
   276  	return nil
   277  }
   278  
   279  // execCommandGC runs a ticker to clean up the daemon references
   280  // of exec configs that are no longer part of the container.
   281  func (d *Daemon) execCommandGC() {
   282  	for range time.Tick(5 * time.Minute) {
   283  		var (
   284  			cleaned          int
   285  			liveExecCommands = d.containerExecIds()
   286  		)
   287  		for id, config := range d.execCommands.Commands() {
   288  			if config.CanRemove {
   289  				cleaned++
   290  				d.execCommands.Delete(id, config.Pid)
   291  			} else {
   292  				if _, exists := liveExecCommands[id]; !exists {
   293  					config.CanRemove = true
   294  				}
   295  			}
   296  		}
   297  		if cleaned > 0 {
   298  			logrus.Debugf("clean %d unused exec commands", cleaned)
   299  		}
   300  	}
   301  }
   302  
   303  // containerExecIds returns a list of all the current exec ids that are in use
   304  // and running inside a container.
   305  func (d *Daemon) containerExecIds() map[string]struct{} {
   306  	ids := map[string]struct{}{}
   307  	for _, c := range d.containers.List() {
   308  		for _, id := range c.ExecCommands.List() {
   309  			ids[id] = struct{}{}
   310  		}
   311  	}
   312  	return ids
   313  }