container_windows.go 11 KB

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