container_windows.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. package libcontainerd
  2. import (
  3. "io"
  4. "strings"
  5. "syscall"
  6. "time"
  7. "github.com/Microsoft/hcsshim"
  8. "github.com/Sirupsen/logrus"
  9. )
  10. type container struct {
  11. containerCommon
  12. // Platform specific fields are below here. There are none presently on Windows.
  13. options []CreateOption
  14. // The ociSpec is required, as client.Create() needs a spec,
  15. // but can be called from the RestartManager context which does not
  16. // otherwise have access to the Spec
  17. ociSpec Spec
  18. manualStopRequested bool
  19. hcsContainer hcsshim.Container
  20. }
  21. func (ctr *container) newProcess(friendlyName string) *process {
  22. return &process{
  23. processCommon: processCommon{
  24. containerID: ctr.containerID,
  25. friendlyName: friendlyName,
  26. client: ctr.client,
  27. },
  28. }
  29. }
  30. func (ctr *container) start() error {
  31. var err error
  32. isServicing := false
  33. for _, option := range ctr.options {
  34. if s, ok := option.(*ServicingOption); ok && s.IsServicing {
  35. isServicing = true
  36. }
  37. }
  38. // Start the container. If this is a servicing container, this call will block
  39. // until the container is done with the servicing execution.
  40. logrus.Debugln("libcontainerd: starting container ", ctr.containerID)
  41. if err = ctr.hcsContainer.Start(); err != nil {
  42. logrus.Errorf("libcontainerd: failed to start container: %s", err)
  43. if err := ctr.terminate(); err != nil {
  44. logrus.Errorf("libcontainerd: failed to cleanup after a failed Start. %s", err)
  45. } else {
  46. logrus.Debugln("libcontainerd: cleaned up after failed Start by calling Terminate")
  47. }
  48. return err
  49. }
  50. // Note we always tell HCS to
  51. // create stdout as it's required regardless of '-i' or '-t' options, so that
  52. // docker can always grab the output through logs. We also tell HCS to always
  53. // create stdin, even if it's not used - it will be closed shortly. Stderr
  54. // is only created if it we're not -t.
  55. createProcessParms := &hcsshim.ProcessConfig{
  56. EmulateConsole: ctr.ociSpec.Process.Terminal,
  57. WorkingDirectory: ctr.ociSpec.Process.Cwd,
  58. ConsoleSize: ctr.ociSpec.Process.InitialConsoleSize,
  59. CreateStdInPipe: !isServicing,
  60. CreateStdOutPipe: !isServicing,
  61. CreateStdErrPipe: !ctr.ociSpec.Process.Terminal && !isServicing,
  62. }
  63. // Configure the environment for the process
  64. createProcessParms.Environment = setupEnvironmentVariables(ctr.ociSpec.Process.Env)
  65. createProcessParms.CommandLine = strings.Join(ctr.ociSpec.Process.Args, " ")
  66. // Start the command running in the container.
  67. hcsProcess, err := ctr.hcsContainer.CreateProcess(createProcessParms)
  68. if err != nil {
  69. logrus.Errorf("libcontainerd: CreateProcess() failed %s", err)
  70. if err := ctr.terminate(); err != nil {
  71. logrus.Errorf("libcontainerd: failed to cleanup after a failed CreateProcess. %s", err)
  72. } else {
  73. logrus.Debugln("libcontainerd: cleaned up after failed CreateProcess by calling Terminate")
  74. }
  75. return err
  76. }
  77. ctr.startedAt = time.Now()
  78. // Save the hcs Process and PID
  79. ctr.process.friendlyName = InitFriendlyName
  80. pid := hcsProcess.Pid()
  81. ctr.process.hcsProcess = hcsProcess
  82. // If this is a servicing container, wait on the process synchronously here and
  83. // immediately call shutdown/terminate when it returns.
  84. if isServicing {
  85. exitCode := ctr.waitProcessExitCode(&ctr.process)
  86. if exitCode != 0 {
  87. logrus.Warnf("libcontainerd: servicing container %s returned non-zero exit code %d", ctr.containerID, exitCode)
  88. return ctr.terminate()
  89. }
  90. return ctr.shutdown()
  91. }
  92. var stdout, stderr io.ReadCloser
  93. var stdin io.WriteCloser
  94. stdin, stdout, stderr, err = hcsProcess.Stdio()
  95. if err != nil {
  96. logrus.Errorf("libcontainerd: failed to get stdio pipes: %s", err)
  97. if err := ctr.terminate(); err != nil {
  98. logrus.Errorf("libcontainerd: failed to cleanup after a failed Stdio. %s", err)
  99. }
  100. return err
  101. }
  102. iopipe := &IOPipe{Terminal: ctr.ociSpec.Process.Terminal}
  103. iopipe.Stdin = createStdInCloser(stdin, hcsProcess)
  104. // TEMP: Work around Windows BS/DEL behavior.
  105. iopipe.Stdin = fixStdinBackspaceBehavior(iopipe.Stdin, ctr.ociSpec.Platform.OSVersion, ctr.ociSpec.Process.Terminal)
  106. // Convert io.ReadClosers to io.Readers
  107. if stdout != nil {
  108. iopipe.Stdout = openReaderFromPipe(stdout)
  109. }
  110. if stderr != nil {
  111. iopipe.Stderr = openReaderFromPipe(stderr)
  112. }
  113. // Save the PID
  114. logrus.Debugf("libcontainerd: process started - PID %d", pid)
  115. ctr.systemPid = uint32(pid)
  116. // Spin up a go routine waiting for exit to handle cleanup
  117. go ctr.waitExit(&ctr.process, true)
  118. ctr.client.appendContainer(ctr)
  119. if err := ctr.client.backend.AttachStreams(ctr.containerID, *iopipe); err != nil {
  120. // OK to return the error here, as waitExit will handle tear-down in HCS
  121. return err
  122. }
  123. // Tell the docker engine that the container has started.
  124. si := StateInfo{
  125. CommonStateInfo: CommonStateInfo{
  126. State: StateStart,
  127. Pid: ctr.systemPid, // Not sure this is needed? Double-check monitor.go in daemon BUGBUG @jhowardmsft
  128. }}
  129. return ctr.client.backend.StateChanged(ctr.containerID, si)
  130. }
  131. // waitProcessExitCode will wait for the given process to exit and return its error code.
  132. func (ctr *container) waitProcessExitCode(process *process) int {
  133. // Block indefinitely for the process to exit.
  134. err := process.hcsProcess.Wait()
  135. if err != nil {
  136. if herr, ok := err.(*hcsshim.ProcessError); ok && herr.Err != syscall.ERROR_BROKEN_PIPE {
  137. logrus.Warnf("libcontainerd: Wait() failed (container may have been killed): %s", err)
  138. }
  139. // Fall through here, do not return. This ensures we attempt to continue the
  140. // shutdown in HCS and tell the docker engine that the process/container
  141. // has exited to avoid a container being dropped on the floor.
  142. }
  143. exitCode, err := process.hcsProcess.ExitCode()
  144. if err != nil {
  145. if herr, ok := err.(*hcsshim.ProcessError); ok && herr.Err != syscall.ERROR_BROKEN_PIPE {
  146. logrus.Warnf("libcontainerd: unable to get exit code from container %s", ctr.containerID)
  147. }
  148. // Since we got an error retrieving the exit code, make sure that the code we return
  149. // doesn't incorrectly indicate success.
  150. exitCode = -1
  151. // Fall through here, do not return. This ensures we attempt to continue the
  152. // shutdown in HCS and tell the docker engine that the process/container
  153. // has exited to avoid a container being dropped on the floor.
  154. }
  155. if err := process.hcsProcess.Close(); err != nil {
  156. logrus.Errorf("libcontainerd: hcsProcess.Close(): %v", err)
  157. }
  158. return exitCode
  159. }
  160. // waitExit runs as a goroutine waiting for the process to exit. It's
  161. // equivalent to (in the linux containerd world) where events come in for
  162. // state change notifications from containerd.
  163. func (ctr *container) waitExit(process *process, isFirstProcessToStart bool) error {
  164. logrus.Debugln("libcontainerd: waitExit() on pid", process.systemPid)
  165. exitCode := ctr.waitProcessExitCode(process)
  166. // Assume the container has exited
  167. si := StateInfo{
  168. CommonStateInfo: CommonStateInfo{
  169. State: StateExit,
  170. ExitCode: uint32(exitCode),
  171. Pid: process.systemPid,
  172. ProcessID: process.friendlyName,
  173. },
  174. UpdatePending: false,
  175. }
  176. // But it could have been an exec'd process which exited
  177. if !isFirstProcessToStart {
  178. si.State = StateExitProcess
  179. } else {
  180. updatePending, err := ctr.hcsContainer.HasPendingUpdates()
  181. if err != nil {
  182. logrus.Warnf("libcontainerd: HasPendingUpdates() failed (container may have been killed): %s", err)
  183. } else {
  184. si.UpdatePending = updatePending
  185. }
  186. logrus.Debugf("libcontainerd: shutting down container %s", ctr.containerID)
  187. if err := ctr.shutdown(); err != nil {
  188. logrus.Debugf("libcontainerd: failed to shutdown container %s", ctr.containerID)
  189. } else {
  190. logrus.Debugf("libcontainerd: completed shutting down container %s", ctr.containerID)
  191. }
  192. if err := ctr.hcsContainer.Close(); err != nil {
  193. logrus.Error(err)
  194. }
  195. if !ctr.manualStopRequested && ctr.restartManager != nil {
  196. restart, wait, err := ctr.restartManager.ShouldRestart(uint32(exitCode), false, time.Since(ctr.startedAt))
  197. if err != nil {
  198. logrus.Error(err)
  199. } else if restart {
  200. si.State = StateRestart
  201. ctr.restarting = true
  202. go func() {
  203. err := <-wait
  204. ctr.restarting = false
  205. ctr.client.deleteContainer(ctr.friendlyName)
  206. if err != nil {
  207. si.State = StateExit
  208. if err := ctr.client.backend.StateChanged(ctr.containerID, si); err != nil {
  209. logrus.Error(err)
  210. }
  211. logrus.Error(err)
  212. } else {
  213. ctr.client.Create(ctr.containerID, ctr.ociSpec, ctr.options...)
  214. }
  215. }()
  216. }
  217. }
  218. // Remove process from list if we have exited
  219. // We need to do so here in case the Message Handler decides to restart it.
  220. if si.State == StateExit {
  221. ctr.client.deleteContainer(ctr.friendlyName)
  222. }
  223. }
  224. // Call into the backend to notify it of the state change.
  225. logrus.Debugf("libcontainerd: waitExit() calling backend.StateChanged %+v", si)
  226. if err := ctr.client.backend.StateChanged(ctr.containerID, si); err != nil {
  227. logrus.Error(err)
  228. }
  229. logrus.Debugf("libcontainerd: waitExit() completed OK, %+v", si)
  230. return nil
  231. }
  232. func (ctr *container) shutdown() error {
  233. const shutdownTimeout = time.Minute * 5
  234. err := ctr.hcsContainer.Shutdown()
  235. if err == hcsshim.ErrVmcomputeOperationPending {
  236. // Explicit timeout to avoid a (remote) possibility that shutdown hangs indefinitely.
  237. err = ctr.hcsContainer.WaitTimeout(shutdownTimeout)
  238. } else if err == hcsshim.ErrVmcomputeAlreadyStopped {
  239. err = nil
  240. }
  241. if err != nil {
  242. logrus.Debugf("libcontainerd: error shutting down container %s %v calling terminate", ctr.containerID, err)
  243. if err := ctr.terminate(); err != nil {
  244. return err
  245. }
  246. return err
  247. }
  248. return nil
  249. }
  250. func (ctr *container) terminate() error {
  251. const terminateTimeout = time.Minute * 5
  252. err := ctr.hcsContainer.Terminate()
  253. if err == hcsshim.ErrVmcomputeOperationPending {
  254. err = ctr.hcsContainer.WaitTimeout(terminateTimeout)
  255. } else if err == hcsshim.ErrVmcomputeAlreadyStopped {
  256. err = nil
  257. }
  258. if err != nil {
  259. logrus.Debugf("libcontainerd: error terminating container %s %v", ctr.containerID, err)
  260. return err
  261. }
  262. return nil
  263. }