kill.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. package daemon // import "github.com/docker/docker/daemon"
  2. import (
  3. "context"
  4. "fmt"
  5. "runtime"
  6. "syscall"
  7. "time"
  8. containerpkg "github.com/docker/docker/container"
  9. "github.com/docker/docker/errdefs"
  10. libcontainerdtypes "github.com/docker/docker/libcontainerd/types"
  11. "github.com/moby/sys/signal"
  12. "github.com/pkg/errors"
  13. "github.com/sirupsen/logrus"
  14. )
  15. type errNoSuchProcess struct {
  16. pid int
  17. signal int
  18. }
  19. func (e errNoSuchProcess) Error() string {
  20. return fmt.Sprintf("Cannot kill process (pid=%d) with signal %d: no such process.", e.pid, e.signal)
  21. }
  22. func (errNoSuchProcess) NotFound() {}
  23. // isErrNoSuchProcess returns true if the error
  24. // is an instance of errNoSuchProcess.
  25. func isErrNoSuchProcess(err error) bool {
  26. _, ok := err.(errNoSuchProcess)
  27. return ok
  28. }
  29. // ContainerKill sends signal to the container
  30. // If no signal is given (sig 0), then Kill with SIGKILL and wait
  31. // for the container to exit.
  32. // If a signal is given, then just send it to the container and return.
  33. func (daemon *Daemon) ContainerKill(name string, sig uint64) error {
  34. container, err := daemon.GetContainer(name)
  35. if err != nil {
  36. return err
  37. }
  38. if sig != 0 && !signal.ValidSignalForPlatform(syscall.Signal(sig)) {
  39. return fmt.Errorf("The %s daemon does not support signal %d", runtime.GOOS, sig)
  40. }
  41. // If no signal is passed, or SIGKILL, perform regular Kill (SIGKILL + wait())
  42. if sig == 0 || syscall.Signal(sig) == syscall.SIGKILL {
  43. return daemon.Kill(container)
  44. }
  45. return daemon.killWithSignal(container, int(sig))
  46. }
  47. // killWithSignal sends the container the given signal. This wrapper for the
  48. // host specific kill command prepares the container before attempting
  49. // to send the signal. An error is returned if the container is paused
  50. // or not running, or if there is a problem returned from the
  51. // underlying kill command.
  52. func (daemon *Daemon) killWithSignal(container *containerpkg.Container, sig int) error {
  53. var stopSignal = syscall.Signal(sig)
  54. logrus.Debugf("Sending kill signal %d to container %s", stopSignal, container.ID)
  55. container.Lock()
  56. defer container.Unlock()
  57. if !container.Running {
  58. return errNotRunning(container.ID)
  59. }
  60. var unpause bool
  61. if container.Config.StopSignal != "" && stopSignal != syscall.SIGKILL {
  62. containerStopSignal, err := signal.ParseSignal(container.Config.StopSignal)
  63. if err != nil {
  64. return err
  65. }
  66. if containerStopSignal == stopSignal {
  67. container.ExitOnNext()
  68. unpause = container.Paused
  69. }
  70. } else {
  71. container.ExitOnNext()
  72. unpause = container.Paused
  73. }
  74. if !daemon.IsShuttingDown() {
  75. container.HasBeenManuallyStopped = true
  76. container.CheckpointTo(daemon.containersReplica)
  77. }
  78. // if the container is currently restarting we do not need to send the signal
  79. // to the process. Telling the monitor that it should exit on its next event
  80. // loop is enough
  81. if container.Restarting {
  82. return nil
  83. }
  84. err := daemon.containerd.SignalProcess(context.Background(), container.ID, libcontainerdtypes.InitProcessName, stopSignal)
  85. if err != nil {
  86. if errdefs.IsNotFound(err) {
  87. unpause = false
  88. logrus.WithError(err).WithField("container", container.ID).WithField("action", "kill").Debug("container kill failed because of 'container not found' or 'no such process'")
  89. go func() {
  90. // We need to clean up this container but it is possible there is a case where we hit here before the exit event is processed
  91. // but after it was fired off.
  92. // So let's wait the container's stop timeout amount of time to see if the event is eventually processed.
  93. // Doing this has the side effect that if no event was ever going to come we are waiting a a longer period of time uneccessarily.
  94. // But this prevents race conditions in processing the container.
  95. ctx, cancel := context.WithTimeout(context.TODO(), time.Duration(container.StopTimeout())*time.Second)
  96. defer cancel()
  97. s := <-container.Wait(ctx, containerpkg.WaitConditionNotRunning)
  98. if s.Err() != nil {
  99. daemon.handleContainerExit(container, nil)
  100. }
  101. }()
  102. } else {
  103. return errors.Wrapf(err, "Cannot kill container %s", container.ID)
  104. }
  105. }
  106. if unpause {
  107. // above kill signal will be sent once resume is finished
  108. if err := daemon.containerd.Resume(context.Background(), container.ID); err != nil {
  109. logrus.Warnf("Cannot unpause container %s: %s", container.ID, err)
  110. }
  111. }
  112. attributes := map[string]string{
  113. "signal": fmt.Sprintf("%d", stopSignal),
  114. }
  115. daemon.LogContainerEventWithAttributes(container, "kill", attributes)
  116. return nil
  117. }
  118. // Kill forcefully terminates a container.
  119. func (daemon *Daemon) Kill(container *containerpkg.Container) error {
  120. if !container.IsRunning() {
  121. return errNotRunning(container.ID)
  122. }
  123. // 1. Send SIGKILL
  124. if err := daemon.killPossiblyDeadProcess(container, int(syscall.SIGKILL)); err != nil {
  125. // kill failed, check if process is no longer running.
  126. if isErrNoSuchProcess(err) {
  127. return nil
  128. }
  129. }
  130. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  131. defer cancel()
  132. status := <-container.Wait(ctx, containerpkg.WaitConditionNotRunning)
  133. if status.Err() == nil {
  134. return nil
  135. }
  136. logrus.WithError(status.Err()).WithField("container", container.ID).Error("Container failed to exit within 10 seconds of kill - trying direct SIGKILL")
  137. if err := killProcessDirectly(container); err != nil {
  138. if isErrNoSuchProcess(err) {
  139. return nil
  140. }
  141. return err
  142. }
  143. // wait for container to exit one last time, if it doesn't then kill didnt work, so return error
  144. ctx2, cancel2 := context.WithTimeout(context.Background(), 2*time.Second)
  145. defer cancel2()
  146. if status := <-container.Wait(ctx2, containerpkg.WaitConditionNotRunning); status.Err() != nil {
  147. return errors.New("tried to kill container, but did not receive an exit event")
  148. }
  149. return nil
  150. }
  151. // killPossibleDeadProcess is a wrapper around killSig() suppressing "no such process" error.
  152. func (daemon *Daemon) killPossiblyDeadProcess(container *containerpkg.Container, sig int) error {
  153. err := daemon.killWithSignal(container, sig)
  154. if errdefs.IsNotFound(err) {
  155. e := errNoSuchProcess{container.GetPID(), sig}
  156. logrus.Debug(e)
  157. return e
  158. }
  159. return err
  160. }