github.com/zhuohuang-hust/src-cbuild@v0.0.0-20230105071821-c7aab3e7c840/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 Engine 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  
    98      fmt.Println("daemon/exec.go  ContainerExecCreate()")
    99  
   100      container, err := d.getActiveContainer(name)
   101  	if err != nil {
   102  		return "", err
   103  	}
   104  
   105  	cmd := strslice.StrSlice(config.Cmd)
   106  	entrypoint, args := d.getEntrypointAndArgs(strslice.StrSlice{}, cmd)
   107  
   108  	keys := []byte{}
   109  	if config.DetachKeys != "" {
   110  		keys, err = term.ToBytes(config.DetachKeys)
   111  		if err != nil {
   112  			err = fmt.Errorf("Invalid escape keys (%s) provided", config.DetachKeys)
   113  			return "", err
   114  		}
   115  	}
   116  
   117  	execConfig := exec.NewConfig()
   118  	execConfig.OpenStdin = config.AttachStdin
   119  	execConfig.OpenStdout = config.AttachStdout
   120  	execConfig.OpenStderr = config.AttachStderr
   121  	execConfig.ContainerID = container.ID
   122  	execConfig.DetachKeys = keys
   123  	execConfig.Entrypoint = entrypoint
   124  	execConfig.Args = args
   125  	execConfig.Tty = config.Tty
   126  	execConfig.Privileged = config.Privileged
   127  	execConfig.User = config.User
   128  
   129  	linkedEnv, err := d.setupLinkedContainers(container)
   130  	if err != nil {
   131  		return "", err
   132  	}
   133  	execConfig.Env = utils.ReplaceOrAppendEnvValues(container.CreateDaemonEnvironment(config.Tty, linkedEnv), config.Env)
   134  	if len(execConfig.User) == 0 {
   135  		execConfig.User = container.Config.User
   136  	}
   137  
   138  	d.registerExecCommand(container, execConfig)
   139  
   140  	d.LogContainerEvent(container, "exec_create: "+execConfig.Entrypoint+" "+strings.Join(execConfig.Args, " "))
   141  
   142  	return execConfig.ID, nil
   143  }
   144  
   145  // ContainerExecStart starts a previously set up exec instance. The
   146  // std streams are set up.
   147  // If ctx is cancelled, the process is terminated.
   148  func (d *Daemon) ContainerExecStart(ctx context.Context, name string, stdin io.ReadCloser, stdout io.Writer, stderr io.Writer) (err error) {
   149  
   150      fmt.Println("daemon/exec.go/ContainerExecStart() exec")
   151  
   152  	var (
   153  		cStdin           io.ReadCloser
   154  		cStdout, cStderr io.Writer
   155  	)
   156  
   157  	ec, err := d.getExecConfig(name)
   158  	if err != nil {
   159  		return errExecNotFound(name)
   160  	}
   161  
   162  	ec.Lock()
   163  	if ec.ExitCode != nil {
   164  		ec.Unlock()
   165  		err := fmt.Errorf("Error: Exec command %s has already run", ec.ID)
   166  		return errors.NewRequestConflictError(err)
   167  	}
   168  
   169  	if ec.Running {
   170  		ec.Unlock()
   171  		return fmt.Errorf("Error: Exec command %s is already running", ec.ID)
   172  	}
   173  	ec.Running = true
   174  	defer func() {
   175  		if err != nil {
   176  			ec.Running = false
   177  			exitCode := 126
   178  			ec.ExitCode = &exitCode
   179  		}
   180  	}()
   181  	ec.Unlock()
   182  
   183  	c := d.containers.Get(ec.ContainerID)
   184  	logrus.Debugf("starting exec command %s in container %s", ec.ID, c.ID)
   185  	d.LogContainerEvent(c, "exec_start: "+ec.Entrypoint+" "+strings.Join(ec.Args, " "))
   186  
   187  	if ec.OpenStdin && stdin != nil {
   188  		r, w := io.Pipe()
   189  		go func() {
   190  			defer w.Close()
   191  			defer logrus.Debug("Closing buffered stdin pipe")
   192  			pools.Copy(w, stdin)
   193  		}()
   194  		cStdin = r
   195  	}
   196  	if ec.OpenStdout {
   197  		cStdout = stdout
   198  	}
   199  	if ec.OpenStderr {
   200  		cStderr = stderr
   201  	}
   202  
   203  	if ec.OpenStdin {
   204  		ec.StreamConfig.NewInputPipes()
   205  	} else {
   206  		ec.StreamConfig.NewNopInputPipe()
   207  	}
   208  
   209  	p := libcontainerd.Process{
   210  		Args:     append([]string{ec.Entrypoint}, ec.Args...),
   211  		Env:      ec.Env,
   212  		Terminal: ec.Tty,
   213  	}
   214  
   215  	if err := execSetPlatformOpt(c, ec, &p); err != nil {
   216  		return err
   217  	}
   218  
   219  	attachErr := container.AttachStreams(ctx, ec.StreamConfig, ec.OpenStdin, true, ec.Tty, cStdin, cStdout, cStderr, ec.DetachKeys)
   220  
   221      fmt.Println("daemon/exec.go  AddProcess")
   222      fmt.Println("daemon/exec.go  AddProcess  container : ", c.ID)
   223  	systemPid, err := d.containerd.AddProcess(ctx, c.ID, name, p, ec.InitializeStdio)
   224  	if err != nil {
   225  		return err
   226  	}
   227  	ec.Lock()
   228  	ec.Pid = systemPid
   229  	ec.Unlock()
   230  
   231  	select {
   232  	case <-ctx.Done():
   233  		logrus.Debugf("Sending TERM signal to process %v in container %v", name, c.ID)
   234  		fmt.Println("daemon/exec.go ContainerExecStart() sending TERM signal")
   235          d.containerd.SignalProcess(c.ID, name, int(signal.SignalMap["TERM"]))
   236  		select {
   237  		case <-time.After(termProcessTimeout * time.Second):
   238  			logrus.Infof("Container %v, process %v failed to exit within %d seconds of signal TERM - using the force", c.ID, name, termProcessTimeout)
   239  			d.containerd.SignalProcess(c.ID, name, int(signal.SignalMap["KILL"]))
   240              fmt.Println("daemon/exec.go ContainerExecStart()  failed to exit ", termProcessTimeout)
   241  		case <-attachErr:
   242  			// TERM signal worked
   243              fmt.Println("daemon/exec.go  ContainerExecStart() TERM signal worked")
   244  		}
   245  		return fmt.Errorf("context cancelled")
   246  	case err := <-attachErr:
   247          fmt.Println("daemon/exec.go ContainerExecStart() attachErr")
   248  		if err != nil {
   249  			if _, ok := err.(container.DetachError); !ok {
   250  				return fmt.Errorf("exec attach failed with error: %v", err)
   251  			}
   252  			d.LogContainerEvent(c, "exec_detach")
   253  		}
   254  	}
   255  	return nil
   256  }
   257  
   258  // execCommandGC runs a ticker to clean up the daemon references
   259  // of exec configs that are no longer part of the container.
   260  func (d *Daemon) execCommandGC() {
   261  	for range time.Tick(5 * time.Minute) {
   262  		var (
   263  			cleaned          int
   264  			liveExecCommands = d.containerExecIds()
   265  		)
   266  		for id, config := range d.execCommands.Commands() {
   267  			if config.CanRemove {
   268  				cleaned++
   269  				d.execCommands.Delete(id)
   270  			} else {
   271  				if _, exists := liveExecCommands[id]; !exists {
   272  					config.CanRemove = true
   273  				}
   274  			}
   275  		}
   276  		if cleaned > 0 {
   277  			logrus.Debugf("clean %d unused exec commands", cleaned)
   278  		}
   279  	}
   280  }
   281  
   282  // containerExecIds returns a list of all the current exec ids that are in use
   283  // and running inside a container.
   284  func (d *Daemon) containerExecIds() map[string]struct{} {
   285  	ids := map[string]struct{}{}
   286  	for _, c := range d.containers.List() {
   287  		for _, id := range c.ExecCommands.List() {
   288  			ids[id] = struct{}{}
   289  		}
   290  	}
   291  	return ids
   292  }