run.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. // +build windows
  2. package windows
  3. // Note this is alpha code for the bring up of containers on Windows.
  4. import (
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "strings"
  9. "github.com/Sirupsen/logrus"
  10. "github.com/docker/docker/daemon/execdriver"
  11. "github.com/microsoft/hcsshim"
  12. "github.com/natefinch/npipe"
  13. )
  14. type layer struct {
  15. ID string
  16. Path string
  17. }
  18. type defConfig struct {
  19. DefFile string
  20. }
  21. type networkConnection struct {
  22. NetworkName string
  23. EnableNat bool
  24. }
  25. type networkSettings struct {
  26. MacAddress string
  27. }
  28. type device struct {
  29. DeviceType string
  30. Connection interface{}
  31. Settings interface{}
  32. }
  33. type containerInit struct {
  34. SystemType string
  35. Name string
  36. IsDummy bool
  37. VolumePath string
  38. Devices []device
  39. IgnoreFlushesDuringBoot bool
  40. LayerFolderPath string
  41. Layers []layer
  42. }
  43. // Run implements the exec driver Driver interface
  44. func (d *Driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, startCallback execdriver.StartCallback) (execdriver.ExitStatus, error) {
  45. var (
  46. term execdriver.Terminal
  47. err error
  48. inListen, outListen, errListen *npipe.PipeListener
  49. )
  50. // Make sure the client isn't asking for options which aren't supported
  51. err = checkSupportedOptions(c)
  52. if err != nil {
  53. return execdriver.ExitStatus{ExitCode: -1}, err
  54. }
  55. cu := &containerInit{
  56. SystemType: "Container",
  57. Name: c.ID,
  58. IsDummy: dummyMode,
  59. VolumePath: c.Rootfs,
  60. IgnoreFlushesDuringBoot: c.FirstStart,
  61. LayerFolderPath: c.LayerFolder,
  62. }
  63. for i := 0; i < len(c.LayerPaths); i++ {
  64. cu.Layers = append(cu.Layers, layer{
  65. ID: hcsshim.NewGUID(c.LayerPaths[i]).ToString(),
  66. Path: c.LayerPaths[i],
  67. })
  68. }
  69. if c.Network.Interface != nil {
  70. dev := device{
  71. DeviceType: "Network",
  72. Connection: &networkConnection{
  73. NetworkName: c.Network.Interface.Bridge,
  74. EnableNat: false,
  75. },
  76. }
  77. if c.Network.Interface.MacAddress != "" {
  78. windowsStyleMAC := strings.Replace(
  79. c.Network.Interface.MacAddress, ":", "-", -1)
  80. dev.Settings = networkSettings{
  81. MacAddress: windowsStyleMAC,
  82. }
  83. }
  84. logrus.Debugf("Virtual switch '%s', mac='%s'", c.Network.Interface.Bridge, c.Network.Interface.MacAddress)
  85. cu.Devices = append(cu.Devices, dev)
  86. } else {
  87. logrus.Debugln("No network interface")
  88. }
  89. configurationb, err := json.Marshal(cu)
  90. if err != nil {
  91. return execdriver.ExitStatus{ExitCode: -1}, err
  92. }
  93. configuration := string(configurationb)
  94. err = hcsshim.CreateComputeSystem(c.ID, configuration)
  95. if err != nil {
  96. logrus.Debugln("Failed to create temporary container ", err)
  97. return execdriver.ExitStatus{ExitCode: -1}, err
  98. }
  99. // Start the container
  100. logrus.Debugln("Starting container ", c.ID)
  101. err = hcsshim.StartComputeSystem(c.ID)
  102. if err != nil {
  103. logrus.Errorf("Failed to start compute system: %s", err)
  104. return execdriver.ExitStatus{ExitCode: -1}, err
  105. }
  106. defer func() {
  107. // Stop the container
  108. if terminateMode {
  109. logrus.Debugf("Terminating container %s", c.ID)
  110. if err := hcsshim.TerminateComputeSystem(c.ID); err != nil {
  111. // IMPORTANT: Don't fail if fails to change state. It could already
  112. // have been stopped through kill().
  113. // Otherwise, the docker daemon will hang in job wait()
  114. logrus.Warnf("Ignoring error from TerminateComputeSystem %s", err)
  115. }
  116. } else {
  117. logrus.Debugf("Shutting down container %s", c.ID)
  118. if err := hcsshim.ShutdownComputeSystem(c.ID); err != nil {
  119. // IMPORTANT: Don't fail if fails to change state. It could already
  120. // have been stopped through kill().
  121. // Otherwise, the docker daemon will hang in job wait()
  122. logrus.Warnf("Ignoring error from ShutdownComputeSystem %s", err)
  123. }
  124. }
  125. }()
  126. // We use a different pipe name between real and dummy mode in the HCS
  127. var serverPipeFormat, clientPipeFormat string
  128. if dummyMode {
  129. clientPipeFormat = `\\.\pipe\docker-run-%[1]s-%[2]s`
  130. serverPipeFormat = clientPipeFormat
  131. } else {
  132. clientPipeFormat = `\\.\pipe\docker-run-%[2]s`
  133. serverPipeFormat = `\\.\Containers\%[1]s\Device\NamedPipe\docker-run-%[2]s`
  134. }
  135. createProcessParms := hcsshim.CreateProcessParams{
  136. EmulateConsole: c.ProcessConfig.Tty,
  137. WorkingDirectory: c.WorkingDir,
  138. ConsoleSize: c.ProcessConfig.ConsoleSize,
  139. }
  140. // Configure the environment for the process
  141. createProcessParms.Environment = setupEnvironmentVariables(c.ProcessConfig.Env)
  142. // Connect stdin
  143. if pipes.Stdin != nil {
  144. stdInPipe := fmt.Sprintf(serverPipeFormat, c.ID, "stdin")
  145. createProcessParms.StdInPipe = fmt.Sprintf(clientPipeFormat, c.ID, "stdin")
  146. // Listen on the named pipe
  147. inListen, err = npipe.Listen(stdInPipe)
  148. if err != nil {
  149. logrus.Errorf("stdin failed to listen on %s err=%s", stdInPipe, err)
  150. return execdriver.ExitStatus{ExitCode: -1}, err
  151. }
  152. defer inListen.Close()
  153. // Launch a goroutine to do the accept. We do this so that we can
  154. // cause an otherwise blocking goroutine to gracefully close when
  155. // the caller (us) closes the listener
  156. go stdinAccept(inListen, stdInPipe, pipes.Stdin)
  157. }
  158. // Connect stdout
  159. stdOutPipe := fmt.Sprintf(serverPipeFormat, c.ID, "stdout")
  160. createProcessParms.StdOutPipe = fmt.Sprintf(clientPipeFormat, c.ID, "stdout")
  161. outListen, err = npipe.Listen(stdOutPipe)
  162. if err != nil {
  163. logrus.Errorf("stdout failed to listen on %s err=%s", stdOutPipe, err)
  164. return execdriver.ExitStatus{ExitCode: -1}, err
  165. }
  166. defer outListen.Close()
  167. go stdouterrAccept(outListen, stdOutPipe, pipes.Stdout)
  168. // No stderr on TTY.
  169. if !c.ProcessConfig.Tty {
  170. // Connect stderr
  171. stdErrPipe := fmt.Sprintf(serverPipeFormat, c.ID, "stderr")
  172. createProcessParms.StdErrPipe = fmt.Sprintf(clientPipeFormat, c.ID, "stderr")
  173. errListen, err = npipe.Listen(stdErrPipe)
  174. if err != nil {
  175. logrus.Errorf("stderr failed to listen on %s err=%s", stdErrPipe, err)
  176. return execdriver.ExitStatus{ExitCode: -1}, err
  177. }
  178. defer errListen.Close()
  179. go stdouterrAccept(errListen, stdErrPipe, pipes.Stderr)
  180. }
  181. // This should get caught earlier, but just in case - validate that we
  182. // have something to run
  183. if c.ProcessConfig.Entrypoint == "" {
  184. err = errors.New("No entrypoint specified")
  185. logrus.Error(err)
  186. return execdriver.ExitStatus{ExitCode: -1}, err
  187. }
  188. // Build the command line of the process
  189. createProcessParms.CommandLine = c.ProcessConfig.Entrypoint
  190. for _, arg := range c.ProcessConfig.Arguments {
  191. logrus.Debugln("appending ", arg)
  192. createProcessParms.CommandLine += " " + arg
  193. }
  194. logrus.Debugf("CommandLine: %s", createProcessParms.CommandLine)
  195. // Start the command running in the container.
  196. var pid uint32
  197. pid, err = hcsshim.CreateProcessInComputeSystem(c.ID, createProcessParms)
  198. if err != nil {
  199. logrus.Errorf("CreateProcessInComputeSystem() failed %s", err)
  200. return execdriver.ExitStatus{ExitCode: -1}, err
  201. }
  202. //Save the PID as we'll need this in Kill()
  203. logrus.Debugf("PID %d", pid)
  204. c.ContainerPid = int(pid)
  205. if c.ProcessConfig.Tty {
  206. term = NewTtyConsole(c.ID, pid)
  207. } else {
  208. term = NewStdConsole()
  209. }
  210. c.ProcessConfig.Terminal = term
  211. // Maintain our list of active containers. We'll need this later for exec
  212. // and other commands.
  213. d.Lock()
  214. d.activeContainers[c.ID] = &activeContainer{
  215. command: c,
  216. }
  217. d.Unlock()
  218. // Invoke the start callback
  219. if startCallback != nil {
  220. startCallback(&c.ProcessConfig, int(pid))
  221. }
  222. var exitCode int32
  223. exitCode, err = hcsshim.WaitForProcessInComputeSystem(c.ID, pid)
  224. if err != nil {
  225. logrus.Errorf("Failed to WaitForProcessInComputeSystem %s", err)
  226. return execdriver.ExitStatus{ExitCode: -1}, err
  227. }
  228. logrus.Debugf("Exiting Run() exitCode %d id=%s", exitCode, c.ID)
  229. return execdriver.ExitStatus{ExitCode: int(exitCode)}, nil
  230. }