github.com/docker/docker@v299999999.0.0-20200612211812-aaf470eca7b5+incompatible/daemon/kill.go (about)

     1  package daemon // import "github.com/docker/docker/daemon"
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"runtime"
     7  	"syscall"
     8  	"time"
     9  
    10  	containerpkg "github.com/docker/docker/container"
    11  	"github.com/docker/docker/errdefs"
    12  	libcontainerdtypes "github.com/docker/docker/libcontainerd/types"
    13  	"github.com/docker/docker/pkg/signal"
    14  	"github.com/pkg/errors"
    15  	"github.com/sirupsen/logrus"
    16  )
    17  
    18  type errNoSuchProcess struct {
    19  	pid    int
    20  	signal int
    21  }
    22  
    23  func (e errNoSuchProcess) Error() string {
    24  	return fmt.Sprintf("Cannot kill process (pid=%d) with signal %d: no such process.", e.pid, e.signal)
    25  }
    26  
    27  func (errNoSuchProcess) NotFound() {}
    28  
    29  // isErrNoSuchProcess returns true if the error
    30  // is an instance of errNoSuchProcess.
    31  func isErrNoSuchProcess(err error) bool {
    32  	_, ok := err.(errNoSuchProcess)
    33  	return ok
    34  }
    35  
    36  // ContainerKill sends signal to the container
    37  // If no signal is given (sig 0), then Kill with SIGKILL and wait
    38  // for the container to exit.
    39  // If a signal is given, then just send it to the container and return.
    40  func (daemon *Daemon) ContainerKill(name string, sig uint64) error {
    41  	container, err := daemon.GetContainer(name)
    42  	if err != nil {
    43  		return err
    44  	}
    45  
    46  	if sig != 0 && !signal.ValidSignalForPlatform(syscall.Signal(sig)) {
    47  		return fmt.Errorf("The %s daemon does not support signal %d", runtime.GOOS, sig)
    48  	}
    49  
    50  	// If no signal is passed, or SIGKILL, perform regular Kill (SIGKILL + wait())
    51  	if sig == 0 || syscall.Signal(sig) == syscall.SIGKILL {
    52  		return daemon.Kill(container)
    53  	}
    54  	return daemon.killWithSignal(container, int(sig))
    55  }
    56  
    57  // killWithSignal sends the container the given signal. This wrapper for the
    58  // host specific kill command prepares the container before attempting
    59  // to send the signal. An error is returned if the container is paused
    60  // or not running, or if there is a problem returned from the
    61  // underlying kill command.
    62  func (daemon *Daemon) killWithSignal(container *containerpkg.Container, sig int) error {
    63  	logrus.Debugf("Sending kill signal %d to container %s", sig, container.ID)
    64  	container.Lock()
    65  	defer container.Unlock()
    66  
    67  	if !container.Running {
    68  		return errNotRunning(container.ID)
    69  	}
    70  
    71  	var unpause bool
    72  	if container.Config.StopSignal != "" && syscall.Signal(sig) != syscall.SIGKILL {
    73  		containerStopSignal, err := signal.ParseSignal(container.Config.StopSignal)
    74  		if err != nil {
    75  			return err
    76  		}
    77  		if containerStopSignal == syscall.Signal(sig) {
    78  			container.ExitOnNext()
    79  			unpause = container.Paused
    80  		}
    81  	} else {
    82  		container.ExitOnNext()
    83  		unpause = container.Paused
    84  	}
    85  
    86  	if !daemon.IsShuttingDown() {
    87  		container.HasBeenManuallyStopped = true
    88  		container.CheckpointTo(daemon.containersReplica)
    89  	}
    90  
    91  	// if the container is currently restarting we do not need to send the signal
    92  	// to the process. Telling the monitor that it should exit on its next event
    93  	// loop is enough
    94  	if container.Restarting {
    95  		return nil
    96  	}
    97  
    98  	if err := daemon.kill(container, sig); err != nil {
    99  		if errdefs.IsNotFound(err) {
   100  			unpause = false
   101  			logrus.WithError(err).WithField("container", container.ID).WithField("action", "kill").Debug("container kill failed because of 'container not found' or 'no such process'")
   102  		} else {
   103  			return errors.Wrapf(err, "Cannot kill container %s", container.ID)
   104  		}
   105  	}
   106  
   107  	if unpause {
   108  		// above kill signal will be sent once resume is finished
   109  		if err := daemon.containerd.Resume(context.Background(), container.ID); err != nil {
   110  			logrus.Warnf("Cannot unpause container %s: %s", container.ID, err)
   111  		}
   112  	}
   113  
   114  	attributes := map[string]string{
   115  		"signal": fmt.Sprintf("%d", sig),
   116  	}
   117  	daemon.LogContainerEventWithAttributes(container, "kill", attributes)
   118  	return nil
   119  }
   120  
   121  // Kill forcefully terminates a container.
   122  func (daemon *Daemon) Kill(container *containerpkg.Container) error {
   123  	if !container.IsRunning() {
   124  		return errNotRunning(container.ID)
   125  	}
   126  
   127  	// 1. Send SIGKILL
   128  	if err := daemon.killPossiblyDeadProcess(container, int(syscall.SIGKILL)); err != nil {
   129  		// While normally we might "return err" here we're not going to
   130  		// because if we can't stop the container by this point then
   131  		// it's probably because it's already stopped. Meaning, between
   132  		// the time of the IsRunning() call above and now it stopped.
   133  		// Also, since the err return will be environment specific we can't
   134  		// look for any particular (common) error that would indicate
   135  		// that the process is already dead vs something else going wrong.
   136  		// So, instead we'll give it up to 2 more seconds to complete and if
   137  		// by that time the container is still running, then the error
   138  		// we got is probably valid and so we return it to the caller.
   139  		if isErrNoSuchProcess(err) {
   140  			return nil
   141  		}
   142  
   143  		ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
   144  		defer cancel()
   145  
   146  		if status := <-container.Wait(ctx, containerpkg.WaitConditionNotRunning); status.Err() != nil {
   147  			return err
   148  		}
   149  	}
   150  
   151  	// 2. Wait for the process to die, in last resort, try to kill the process directly
   152  	if err := killProcessDirectly(container); err != nil {
   153  		if isErrNoSuchProcess(err) {
   154  			return nil
   155  		}
   156  		return err
   157  	}
   158  
   159  	// Wait for exit with no timeout.
   160  	// Ignore returned status.
   161  	<-container.Wait(context.Background(), containerpkg.WaitConditionNotRunning)
   162  
   163  	return nil
   164  }
   165  
   166  // killPossibleDeadProcess is a wrapper around killSig() suppressing "no such process" error.
   167  func (daemon *Daemon) killPossiblyDeadProcess(container *containerpkg.Container, sig int) error {
   168  	err := daemon.killWithSignal(container, sig)
   169  	if errdefs.IsNotFound(err) {
   170  		e := errNoSuchProcess{container.GetPID(), sig}
   171  		logrus.Debug(e)
   172  		return e
   173  	}
   174  	return err
   175  }
   176  
   177  func (daemon *Daemon) kill(c *containerpkg.Container, sig int) error {
   178  	return daemon.containerd.SignalProcess(context.Background(), c.ID, libcontainerdtypes.InitProcessName, sig)
   179  }