run.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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. "os"
  9. "strconv"
  10. "strings"
  11. "github.com/Sirupsen/logrus"
  12. "github.com/docker/docker/daemon/execdriver"
  13. "github.com/microsoft/hcsshim"
  14. "github.com/natefinch/npipe"
  15. )
  16. // defaultContainerNAT is the default name of the container NAT device that is
  17. // preconfigured on the server.
  18. const defaultContainerNAT = "ContainerNAT"
  19. type layer struct {
  20. ID string
  21. Path string
  22. }
  23. type defConfig struct {
  24. DefFile string
  25. }
  26. type portBinding struct {
  27. Protocol string
  28. InternalPort int
  29. ExternalPort int
  30. }
  31. type natSettings struct {
  32. Name string
  33. PortBindings []portBinding
  34. }
  35. type networkConnection struct {
  36. NetworkName string
  37. // TODO Windows: Add Ip4Address string to this structure when hooked up in
  38. // docker CLI. This is present in the HCS JSON handler.
  39. EnableNat bool
  40. Nat natSettings
  41. }
  42. type networkSettings struct {
  43. MacAddress string
  44. }
  45. type device struct {
  46. DeviceType string
  47. Connection interface{}
  48. Settings interface{}
  49. }
  50. type containerInit struct {
  51. SystemType string
  52. Name string
  53. IsDummy bool
  54. VolumePath string
  55. Devices []device
  56. IgnoreFlushesDuringBoot bool
  57. LayerFolderPath string
  58. Layers []layer
  59. }
  60. // Run implements the exec driver Driver interface
  61. func (d *Driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, startCallback execdriver.StartCallback) (execdriver.ExitStatus, error) {
  62. var (
  63. term execdriver.Terminal
  64. err error
  65. inListen, outListen, errListen *npipe.PipeListener
  66. )
  67. // Make sure the client isn't asking for options which aren't supported
  68. err = checkSupportedOptions(c)
  69. if err != nil {
  70. return execdriver.ExitStatus{ExitCode: -1}, err
  71. }
  72. cu := &containerInit{
  73. SystemType: "Container",
  74. Name: c.ID,
  75. IsDummy: dummyMode,
  76. VolumePath: c.Rootfs,
  77. IgnoreFlushesDuringBoot: c.FirstStart,
  78. LayerFolderPath: c.LayerFolder,
  79. }
  80. for i := 0; i < len(c.LayerPaths); i++ {
  81. cu.Layers = append(cu.Layers, layer{
  82. ID: hcsshim.NewGUID(c.LayerPaths[i]).ToString(),
  83. Path: c.LayerPaths[i],
  84. })
  85. }
  86. // TODO Windows. At some point, when there is CLI on docker run to
  87. // enable the IP Address of the container to be passed into docker run,
  88. // the IP Address needs to be wired through to HCS in the JSON. It
  89. // would be present in c.Network.Interface.IPAddress. See matching
  90. // TODO in daemon\container_windows.go, function populateCommand.
  91. if c.Network.Interface != nil {
  92. var pbs []portBinding
  93. // Enumerate through the port bindings specified by the user and convert
  94. // them into the internal structure matching the JSON blob that can be
  95. // understood by the HCS.
  96. for i, v := range c.Network.Interface.PortBindings {
  97. proto := strings.ToUpper(i.Proto())
  98. if proto != "TCP" && proto != "UDP" {
  99. return execdriver.ExitStatus{ExitCode: -1}, fmt.Errorf("invalid protocol %s", i.Proto())
  100. }
  101. if len(v) > 1 {
  102. return execdriver.ExitStatus{ExitCode: -1}, fmt.Errorf("Windows does not support more than one host port in NAT settings")
  103. }
  104. for _, v2 := range v {
  105. var (
  106. iPort, ePort int
  107. err error
  108. )
  109. if len(v2.HostIP) != 0 {
  110. return execdriver.ExitStatus{ExitCode: -1}, fmt.Errorf("Windows does not support host IP addresses in NAT settings")
  111. }
  112. if ePort, err = strconv.Atoi(v2.HostPort); err != nil {
  113. return execdriver.ExitStatus{ExitCode: -1}, fmt.Errorf("invalid container port %s: %s", v2.HostPort, err)
  114. }
  115. if iPort, err = strconv.Atoi(i.Port()); err != nil {
  116. return execdriver.ExitStatus{ExitCode: -1}, fmt.Errorf("invalid internal port %s: %s", i.Port(), err)
  117. }
  118. if iPort < 0 || iPort > 65535 || ePort < 0 || ePort > 65535 {
  119. return execdriver.ExitStatus{ExitCode: -1}, fmt.Errorf("specified NAT port is not in allowed range")
  120. }
  121. pbs = append(pbs,
  122. portBinding{ExternalPort: ePort,
  123. InternalPort: iPort,
  124. Protocol: proto})
  125. }
  126. }
  127. // TODO Windows: TP3 workaround. Allow the user to override the name of
  128. // the Container NAT device through an environment variable. This will
  129. // ultimately be a global daemon parameter on Windows, similar to -b
  130. // for the name of the virtual switch (aka bridge).
  131. cn := os.Getenv("DOCKER_CONTAINER_NAT")
  132. if len(cn) == 0 {
  133. cn = defaultContainerNAT
  134. }
  135. dev := device{
  136. DeviceType: "Network",
  137. Connection: &networkConnection{
  138. NetworkName: c.Network.Interface.Bridge,
  139. // TODO Windows: Fixme, next line. Needs HCS fix.
  140. EnableNat: false,
  141. Nat: natSettings{
  142. Name: cn,
  143. PortBindings: pbs,
  144. },
  145. },
  146. }
  147. if c.Network.Interface.MacAddress != "" {
  148. windowsStyleMAC := strings.Replace(
  149. c.Network.Interface.MacAddress, ":", "-", -1)
  150. dev.Settings = networkSettings{
  151. MacAddress: windowsStyleMAC,
  152. }
  153. }
  154. cu.Devices = append(cu.Devices, dev)
  155. } else {
  156. logrus.Debugln("No network interface")
  157. }
  158. configurationb, err := json.Marshal(cu)
  159. if err != nil {
  160. return execdriver.ExitStatus{ExitCode: -1}, err
  161. }
  162. configuration := string(configurationb)
  163. err = hcsshim.CreateComputeSystem(c.ID, configuration)
  164. if err != nil {
  165. logrus.Debugln("Failed to create temporary container ", err)
  166. return execdriver.ExitStatus{ExitCode: -1}, err
  167. }
  168. // Start the container
  169. logrus.Debugln("Starting container ", c.ID)
  170. err = hcsshim.StartComputeSystem(c.ID)
  171. if err != nil {
  172. logrus.Errorf("Failed to start compute system: %s", err)
  173. return execdriver.ExitStatus{ExitCode: -1}, err
  174. }
  175. defer func() {
  176. // Stop the container
  177. if terminateMode {
  178. logrus.Debugf("Terminating container %s", c.ID)
  179. if err := hcsshim.TerminateComputeSystem(c.ID); err != nil {
  180. // IMPORTANT: Don't fail if fails to change state. It could already
  181. // have been stopped through kill().
  182. // Otherwise, the docker daemon will hang in job wait()
  183. logrus.Warnf("Ignoring error from TerminateComputeSystem %s", err)
  184. }
  185. } else {
  186. logrus.Debugf("Shutting down container %s", c.ID)
  187. if err := hcsshim.ShutdownComputeSystem(c.ID); err != nil {
  188. // IMPORTANT: Don't fail if fails to change state. It could already
  189. // have been stopped through kill().
  190. // Otherwise, the docker daemon will hang in job wait()
  191. logrus.Warnf("Ignoring error from ShutdownComputeSystem %s", err)
  192. }
  193. }
  194. }()
  195. // We use a different pipe name between real and dummy mode in the HCS
  196. var serverPipeFormat, clientPipeFormat string
  197. if dummyMode {
  198. clientPipeFormat = `\\.\pipe\docker-run-%[1]s-%[2]s`
  199. serverPipeFormat = clientPipeFormat
  200. } else {
  201. clientPipeFormat = `\\.\pipe\docker-run-%[2]s`
  202. serverPipeFormat = `\\.\Containers\%[1]s\Device\NamedPipe\docker-run-%[2]s`
  203. }
  204. createProcessParms := hcsshim.CreateProcessParams{
  205. EmulateConsole: c.ProcessConfig.Tty,
  206. WorkingDirectory: c.WorkingDir,
  207. ConsoleSize: c.ProcessConfig.ConsoleSize,
  208. }
  209. // Configure the environment for the process
  210. createProcessParms.Environment = setupEnvironmentVariables(c.ProcessConfig.Env)
  211. // Connect stdin
  212. if pipes.Stdin != nil {
  213. stdInPipe := fmt.Sprintf(serverPipeFormat, c.ID, "stdin")
  214. createProcessParms.StdInPipe = fmt.Sprintf(clientPipeFormat, c.ID, "stdin")
  215. // Listen on the named pipe
  216. inListen, err = npipe.Listen(stdInPipe)
  217. if err != nil {
  218. logrus.Errorf("stdin failed to listen on %s err=%s", stdInPipe, err)
  219. return execdriver.ExitStatus{ExitCode: -1}, err
  220. }
  221. defer inListen.Close()
  222. // Launch a goroutine to do the accept. We do this so that we can
  223. // cause an otherwise blocking goroutine to gracefully close when
  224. // the caller (us) closes the listener
  225. go stdinAccept(inListen, stdInPipe, pipes.Stdin)
  226. }
  227. // Connect stdout
  228. stdOutPipe := fmt.Sprintf(serverPipeFormat, c.ID, "stdout")
  229. createProcessParms.StdOutPipe = fmt.Sprintf(clientPipeFormat, c.ID, "stdout")
  230. outListen, err = npipe.Listen(stdOutPipe)
  231. if err != nil {
  232. logrus.Errorf("stdout failed to listen on %s err=%s", stdOutPipe, err)
  233. return execdriver.ExitStatus{ExitCode: -1}, err
  234. }
  235. defer outListen.Close()
  236. go stdouterrAccept(outListen, stdOutPipe, pipes.Stdout)
  237. // No stderr on TTY.
  238. if !c.ProcessConfig.Tty {
  239. // Connect stderr
  240. stdErrPipe := fmt.Sprintf(serverPipeFormat, c.ID, "stderr")
  241. createProcessParms.StdErrPipe = fmt.Sprintf(clientPipeFormat, c.ID, "stderr")
  242. errListen, err = npipe.Listen(stdErrPipe)
  243. if err != nil {
  244. logrus.Errorf("stderr failed to listen on %s err=%s", stdErrPipe, err)
  245. return execdriver.ExitStatus{ExitCode: -1}, err
  246. }
  247. defer errListen.Close()
  248. go stdouterrAccept(errListen, stdErrPipe, pipes.Stderr)
  249. }
  250. // This should get caught earlier, but just in case - validate that we
  251. // have something to run
  252. if c.ProcessConfig.Entrypoint == "" {
  253. err = errors.New("No entrypoint specified")
  254. logrus.Error(err)
  255. return execdriver.ExitStatus{ExitCode: -1}, err
  256. }
  257. // Build the command line of the process
  258. createProcessParms.CommandLine = c.ProcessConfig.Entrypoint
  259. for _, arg := range c.ProcessConfig.Arguments {
  260. logrus.Debugln("appending ", arg)
  261. createProcessParms.CommandLine += " " + arg
  262. }
  263. logrus.Debugf("CommandLine: %s", createProcessParms.CommandLine)
  264. // Start the command running in the container.
  265. var pid uint32
  266. pid, err = hcsshim.CreateProcessInComputeSystem(c.ID, createProcessParms)
  267. if err != nil {
  268. logrus.Errorf("CreateProcessInComputeSystem() failed %s", err)
  269. return execdriver.ExitStatus{ExitCode: -1}, err
  270. }
  271. //Save the PID as we'll need this in Kill()
  272. logrus.Debugf("PID %d", pid)
  273. c.ContainerPid = int(pid)
  274. if c.ProcessConfig.Tty {
  275. term = NewTtyConsole(c.ID, pid)
  276. } else {
  277. term = NewStdConsole()
  278. }
  279. c.ProcessConfig.Terminal = term
  280. // Maintain our list of active containers. We'll need this later for exec
  281. // and other commands.
  282. d.Lock()
  283. d.activeContainers[c.ID] = &activeContainer{
  284. command: c,
  285. }
  286. d.Unlock()
  287. // Invoke the start callback
  288. if startCallback != nil {
  289. startCallback(&c.ProcessConfig, int(pid))
  290. }
  291. var exitCode int32
  292. exitCode, err = hcsshim.WaitForProcessInComputeSystem(c.ID, pid)
  293. if err != nil {
  294. logrus.Errorf("Failed to WaitForProcessInComputeSystem %s", err)
  295. return execdriver.ExitStatus{ExitCode: -1}, err
  296. }
  297. logrus.Debugf("Exiting Run() exitCode %d id=%s", exitCode, c.ID)
  298. return execdriver.ExitStatus{ExitCode: int(exitCode)}, nil
  299. }