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