kill.go 6.0 KB

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