github.com/kim0/docker@v0.6.2-0.20161130212042-4addda3f07e7/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/Sirupsen/logrus"
    12  	"github.com/docker/docker/api/errors"
    13  	"github.com/docker/docker/api/types"
    14  	"github.com/docker/docker/api/types/strslice"
    15  	"github.com/docker/docker/container"
    16  	"github.com/docker/docker/daemon/exec"
    17  	"github.com/docker/docker/libcontainerd"
    18  	"github.com/docker/docker/pkg/pools"
    19  	"github.com/docker/docker/pkg/signal"
    20  	"github.com/docker/docker/pkg/term"
    21  	"github.com/docker/docker/utils"
    22  )
    23  
    24  // Seconds to wait after sending TERM before trying KILL
    25  const termProcessTimeout = 10
    26  
    27  func (d *Daemon) registerExecCommand(container *container.Container, config *exec.Config) {
    28  	// Storing execs in container in order to kill them gracefully whenever the container is stopped or removed.
    29  	container.ExecCommands.Add(config.ID, config)
    30  	// Storing execs in daemon for easy access via remote API.
    31  	d.execCommands.Add(config.ID, config)
    32  }
    33  
    34  // ExecExists looks up the exec instance and returns a bool if it exists or not.
    35  // It will also return the error produced by `getConfig`
    36  func (d *Daemon) ExecExists(name string) (bool, error) {
    37  	if _, err := d.getExecConfig(name); err != nil {
    38  		return false, err
    39  	}
    40  	return true, nil
    41  }
    42  
    43  // getExecConfig looks up the exec instance by name. If the container associated
    44  // with the exec instance is stopped or paused, it will return an error.
    45  func (d *Daemon) getExecConfig(name string) (*exec.Config, error) {
    46  	ec := d.execCommands.Get(name)
    47  
    48  	// If the exec is found but its container is not in the daemon's list of
    49  	// containers then it must have been deleted, in which case instead of
    50  	// saying the container isn't running, we should return a 404 so that
    51  	// the user sees the same error now that they will after the
    52  	// 5 minute clean-up loop is run which erases old/dead execs.
    53  
    54  	if ec != nil {
    55  		if container := d.containers.Get(ec.ContainerID); container != nil {
    56  			if !container.IsRunning() {
    57  				return nil, fmt.Errorf("Container %s is not running: %s", container.ID, container.State.String())
    58  			}
    59  			if container.IsPaused() {
    60  				return nil, errExecPaused(container.ID)
    61  			}
    62  			if container.IsRestarting() {
    63  				return nil, errContainerIsRestarting(container.ID)
    64  			}
    65  			return ec, nil
    66  		}
    67  	}
    68  
    69  	return nil, errExecNotFound(name)
    70  }
    71  
    72  func (d *Daemon) unregisterExecCommand(container *container.Container, execConfig *exec.Config) {
    73  	container.ExecCommands.Delete(execConfig.ID)
    74  	d.execCommands.Delete(execConfig.ID)
    75  }
    76  
    77  func (d *Daemon) getActiveContainer(name string) (*container.Container, error) {
    78  	container, err := d.GetContainer(name)
    79  	if err != nil {
    80  		return nil, err
    81  	}
    82  
    83  	if !container.IsRunning() {
    84  		return nil, errNotRunning{container.ID}
    85  	}
    86  	if container.IsPaused() {
    87  		return nil, errExecPaused(name)
    88  	}
    89  	if container.IsRestarting() {
    90  		return nil, errContainerIsRestarting(container.ID)
    91  	}
    92  	return container, nil
    93  }
    94  
    95  // ContainerExecCreate sets up an exec in a running container.
    96  func (d *Daemon) ContainerExecCreate(name string, config *types.ExecConfig) (string, error) {
    97  	container, err := d.getActiveContainer(name)
    98  	if err != nil {
    99  		return "", err
   100  	}
   101  
   102  	cmd := strslice.StrSlice(config.Cmd)
   103  	entrypoint, args := d.getEntrypointAndArgs(strslice.StrSlice{}, cmd)
   104  
   105  	keys := []byte{}
   106  	if config.DetachKeys != "" {
   107  		keys, err = term.ToBytes(config.DetachKeys)
   108  		if err != nil {
   109  			err = fmt.Errorf("Invalid escape keys (%s) provided", config.DetachKeys)
   110  			return "", err
   111  		}
   112  	}
   113  
   114  	execConfig := exec.NewConfig()
   115  	execConfig.OpenStdin = config.AttachStdin
   116  	execConfig.OpenStdout = config.AttachStdout
   117  	execConfig.OpenStderr = config.AttachStderr
   118  	execConfig.ContainerID = container.ID
   119  	execConfig.DetachKeys = keys
   120  	execConfig.Entrypoint = entrypoint
   121  	execConfig.Args = args
   122  	execConfig.Tty = config.Tty
   123  	execConfig.Privileged = config.Privileged
   124  	execConfig.User = config.User
   125  
   126  	linkedEnv, err := d.setupLinkedContainers(container)
   127  	if err != nil {
   128  		return "", err
   129  	}
   130  	execConfig.Env = utils.ReplaceOrAppendEnvValues(container.CreateDaemonEnvironment(config.Tty, linkedEnv), config.Env)
   131  	if len(execConfig.User) == 0 {
   132  		execConfig.User = container.Config.User
   133  	}
   134  
   135  	d.registerExecCommand(container, execConfig)
   136  
   137  	d.LogContainerEvent(container, "exec_create: "+execConfig.Entrypoint+" "+strings.Join(execConfig.Args, " "))
   138  
   139  	return execConfig.ID, nil
   140  }
   141  
   142  // ContainerExecStart starts a previously set up exec instance. The
   143  // std streams are set up.
   144  // If ctx is cancelled, the process is terminated.
   145  func (d *Daemon) ContainerExecStart(ctx context.Context, name string, stdin io.ReadCloser, stdout io.Writer, stderr io.Writer) (err error) {
   146  	var (
   147  		cStdin           io.ReadCloser
   148  		cStdout, cStderr io.Writer
   149  	)
   150  
   151  	ec, err := d.getExecConfig(name)
   152  	if err != nil {
   153  		return errExecNotFound(name)
   154  	}
   155  
   156  	ec.Lock()
   157  	if ec.ExitCode != nil {
   158  		ec.Unlock()
   159  		err := fmt.Errorf("Error: Exec command %s has already run", ec.ID)
   160  		return errors.NewRequestConflictError(err)
   161  	}
   162  
   163  	if ec.Running {
   164  		ec.Unlock()
   165  		return fmt.Errorf("Error: Exec command %s is already running", ec.ID)
   166  	}
   167  	ec.Running = true
   168  	defer func() {
   169  		if err != nil {
   170  			ec.Running = false
   171  			exitCode := 126
   172  			ec.ExitCode = &exitCode
   173  		}
   174  	}()
   175  	ec.Unlock()
   176  
   177  	c := d.containers.Get(ec.ContainerID)
   178  	logrus.Debugf("starting exec command %s in container %s", ec.ID, c.ID)
   179  	d.LogContainerEvent(c, "exec_start: "+ec.Entrypoint+" "+strings.Join(ec.Args, " "))
   180  
   181  	if ec.OpenStdin && stdin != nil {
   182  		r, w := io.Pipe()
   183  		go func() {
   184  			defer w.Close()
   185  			defer logrus.Debug("Closing buffered stdin pipe")
   186  			pools.Copy(w, stdin)
   187  		}()
   188  		cStdin = r
   189  	}
   190  	if ec.OpenStdout {
   191  		cStdout = stdout
   192  	}
   193  	if ec.OpenStderr {
   194  		cStderr = stderr
   195  	}
   196  
   197  	if ec.OpenStdin {
   198  		ec.NewInputPipes()
   199  	} else {
   200  		ec.NewNopInputPipe()
   201  	}
   202  
   203  	p := libcontainerd.Process{
   204  		Args:     append([]string{ec.Entrypoint}, ec.Args...),
   205  		Env:      ec.Env,
   206  		Terminal: ec.Tty,
   207  	}
   208  
   209  	if err := execSetPlatformOpt(c, ec, &p); err != nil {
   210  		return err
   211  	}
   212  
   213  	attachErr := container.AttachStreams(ctx, ec.StreamConfig, ec.OpenStdin, true, ec.Tty, cStdin, cStdout, cStderr, ec.DetachKeys)
   214  
   215  	systemPid, err := d.containerd.AddProcess(ctx, c.ID, name, p, ec.InitializeStdio)
   216  	if err != nil {
   217  		return err
   218  	}
   219  	ec.Lock()
   220  	ec.Pid = systemPid
   221  	ec.Unlock()
   222  
   223  	select {
   224  	case <-ctx.Done():
   225  		logrus.Debugf("Sending TERM signal to process %v in container %v", name, c.ID)
   226  		d.containerd.SignalProcess(c.ID, name, int(signal.SignalMap["TERM"]))
   227  		select {
   228  		case <-time.After(termProcessTimeout * time.Second):
   229  			logrus.Infof("Container %v, process %v failed to exit within %d seconds of signal TERM - using the force", c.ID, name, termProcessTimeout)
   230  			d.containerd.SignalProcess(c.ID, name, int(signal.SignalMap["KILL"]))
   231  		case <-attachErr:
   232  			// TERM signal worked
   233  		}
   234  		return fmt.Errorf("context cancelled")
   235  	case err := <-attachErr:
   236  		if err != nil {
   237  			if _, ok := err.(container.DetachError); !ok {
   238  				return fmt.Errorf("exec attach failed with error: %v", err)
   239  			}
   240  			d.LogContainerEvent(c, "exec_detach")
   241  		}
   242  	}
   243  	return nil
   244  }
   245  
   246  // execCommandGC runs a ticker to clean up the daemon references
   247  // of exec configs that are no longer part of the container.
   248  func (d *Daemon) execCommandGC() {
   249  	for range time.Tick(5 * time.Minute) {
   250  		var (
   251  			cleaned          int
   252  			liveExecCommands = d.containerExecIds()
   253  		)
   254  		for id, config := range d.execCommands.Commands() {
   255  			if config.CanRemove {
   256  				cleaned++
   257  				d.execCommands.Delete(id)
   258  			} else {
   259  				if _, exists := liveExecCommands[id]; !exists {
   260  					config.CanRemove = true
   261  				}
   262  			}
   263  		}
   264  		if cleaned > 0 {
   265  			logrus.Debugf("clean %d unused exec commands", cleaned)
   266  		}
   267  	}
   268  }
   269  
   270  // containerExecIds returns a list of all the current exec ids that are in use
   271  // and running inside a container.
   272  func (d *Daemon) containerExecIds() map[string]struct{} {
   273  	ids := map[string]struct{}{}
   274  	for _, c := range d.containers.List() {
   275  		for _, id := range c.ExecCommands.List() {
   276  			ids[id] = struct{}{}
   277  		}
   278  	}
   279  	return ids
   280  }