run.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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. "path/filepath"
  10. "strconv"
  11. "strings"
  12. "github.com/Sirupsen/logrus"
  13. "github.com/docker/docker/daemon/execdriver"
  14. "github.com/microsoft/hcsshim"
  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 // HCS requires this to be hard-coded to "Container"
  52. Name string // Name of the container. We use the docker ID.
  53. Owner string // The management platform that created this container
  54. IsDummy bool // Used for development purposes.
  55. VolumePath string // Windows volume path for scratch space
  56. Devices []device // Devices used by the container
  57. IgnoreFlushesDuringBoot bool // Optimisation hint for container startup in Windows
  58. LayerFolderPath string // Where the layer folders are located
  59. Layers []layer // List of storage layers
  60. ProcessorWeight int64 // CPU Shares 1..9 on Windows; or 0 is platform default.
  61. }
  62. // defaultOwner is a tag passed to HCS to allow it to differentiate between
  63. // container creator management stacks. We hard code "docker" in the case
  64. // of docker.
  65. const defaultOwner = "docker"
  66. // Run implements the exec driver Driver interface
  67. func (d *Driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, hooks execdriver.Hooks) (execdriver.ExitStatus, error) {
  68. var (
  69. term execdriver.Terminal
  70. err error
  71. )
  72. // Make sure the client isn't asking for options which aren't supported
  73. err = checkSupportedOptions(c)
  74. if err != nil {
  75. return execdriver.ExitStatus{ExitCode: -1}, err
  76. }
  77. cu := &containerInit{
  78. SystemType: "Container",
  79. Name: c.ID,
  80. Owner: defaultOwner,
  81. IsDummy: dummyMode,
  82. VolumePath: c.Rootfs,
  83. IgnoreFlushesDuringBoot: c.FirstStart,
  84. LayerFolderPath: c.LayerFolder,
  85. ProcessorWeight: c.Resources.CPUShares,
  86. }
  87. for i := 0; i < len(c.LayerPaths); i++ {
  88. _, filename := filepath.Split(c.LayerPaths[i])
  89. g, err := hcsshim.NameToGuid(filename)
  90. if err != nil {
  91. return execdriver.ExitStatus{ExitCode: -1}, err
  92. }
  93. cu.Layers = append(cu.Layers, layer{
  94. ID: g.ToString(),
  95. Path: c.LayerPaths[i],
  96. })
  97. }
  98. // TODO Windows. At some point, when there is CLI on docker run to
  99. // enable the IP Address of the container to be passed into docker run,
  100. // the IP Address needs to be wired through to HCS in the JSON. It
  101. // would be present in c.Network.Interface.IPAddress. See matching
  102. // TODO in daemon\container_windows.go, function populateCommand.
  103. if c.Network.Interface != nil {
  104. var pbs []portBinding
  105. // Enumerate through the port bindings specified by the user and convert
  106. // them into the internal structure matching the JSON blob that can be
  107. // understood by the HCS.
  108. for i, v := range c.Network.Interface.PortBindings {
  109. proto := strings.ToUpper(i.Proto())
  110. if proto != "TCP" && proto != "UDP" {
  111. return execdriver.ExitStatus{ExitCode: -1}, fmt.Errorf("invalid protocol %s", i.Proto())
  112. }
  113. if len(v) > 1 {
  114. return execdriver.ExitStatus{ExitCode: -1}, fmt.Errorf("Windows does not support more than one host port in NAT settings")
  115. }
  116. for _, v2 := range v {
  117. var (
  118. iPort, ePort int
  119. err error
  120. )
  121. if len(v2.HostIP) != 0 {
  122. return execdriver.ExitStatus{ExitCode: -1}, fmt.Errorf("Windows does not support host IP addresses in NAT settings")
  123. }
  124. if ePort, err = strconv.Atoi(v2.HostPort); err != nil {
  125. return execdriver.ExitStatus{ExitCode: -1}, fmt.Errorf("invalid container port %s: %s", v2.HostPort, err)
  126. }
  127. if iPort, err = strconv.Atoi(i.Port()); err != nil {
  128. return execdriver.ExitStatus{ExitCode: -1}, fmt.Errorf("invalid internal port %s: %s", i.Port(), err)
  129. }
  130. if iPort < 0 || iPort > 65535 || ePort < 0 || ePort > 65535 {
  131. return execdriver.ExitStatus{ExitCode: -1}, fmt.Errorf("specified NAT port is not in allowed range")
  132. }
  133. pbs = append(pbs,
  134. portBinding{ExternalPort: ePort,
  135. InternalPort: iPort,
  136. Protocol: proto})
  137. }
  138. }
  139. // TODO Windows: TP3 workaround. Allow the user to override the name of
  140. // the Container NAT device through an environment variable. This will
  141. // ultimately be a global daemon parameter on Windows, similar to -b
  142. // for the name of the virtual switch (aka bridge).
  143. cn := os.Getenv("DOCKER_CONTAINER_NAT")
  144. if len(cn) == 0 {
  145. cn = defaultContainerNAT
  146. }
  147. dev := device{
  148. DeviceType: "Network",
  149. Connection: &networkConnection{
  150. NetworkName: c.Network.Interface.Bridge,
  151. // TODO Windows: Fixme, next line. Needs HCS fix.
  152. EnableNat: false,
  153. Nat: natSettings{
  154. Name: cn,
  155. PortBindings: pbs,
  156. },
  157. },
  158. }
  159. if c.Network.Interface.MacAddress != "" {
  160. windowsStyleMAC := strings.Replace(
  161. c.Network.Interface.MacAddress, ":", "-", -1)
  162. dev.Settings = networkSettings{
  163. MacAddress: windowsStyleMAC,
  164. }
  165. }
  166. cu.Devices = append(cu.Devices, dev)
  167. } else {
  168. logrus.Debugln("No network interface")
  169. }
  170. configurationb, err := json.Marshal(cu)
  171. if err != nil {
  172. return execdriver.ExitStatus{ExitCode: -1}, err
  173. }
  174. configuration := string(configurationb)
  175. err = hcsshim.CreateComputeSystem(c.ID, configuration)
  176. if err != nil {
  177. logrus.Debugln("Failed to create temporary container ", err)
  178. return execdriver.ExitStatus{ExitCode: -1}, err
  179. }
  180. // Start the container
  181. logrus.Debugln("Starting container ", c.ID)
  182. err = hcsshim.StartComputeSystem(c.ID)
  183. if err != nil {
  184. logrus.Errorf("Failed to start compute system: %s", err)
  185. return execdriver.ExitStatus{ExitCode: -1}, err
  186. }
  187. defer func() {
  188. // Stop the container
  189. if terminateMode {
  190. logrus.Debugf("Terminating container %s", c.ID)
  191. if err := hcsshim.TerminateComputeSystem(c.ID); err != nil {
  192. // IMPORTANT: Don't fail if fails to change state. It could already
  193. // have been stopped through kill().
  194. // Otherwise, the docker daemon will hang in job wait()
  195. logrus.Warnf("Ignoring error from TerminateComputeSystem %s", err)
  196. }
  197. } else {
  198. logrus.Debugf("Shutting down container %s", c.ID)
  199. if err := hcsshim.ShutdownComputeSystem(c.ID); err != nil {
  200. // IMPORTANT: Don't fail if fails to change state. It could already
  201. // have been stopped through kill().
  202. // Otherwise, the docker daemon will hang in job wait()
  203. logrus.Warnf("Ignoring error from ShutdownComputeSystem %s", err)
  204. }
  205. }
  206. }()
  207. createProcessParms := hcsshim.CreateProcessParams{
  208. EmulateConsole: c.ProcessConfig.Tty,
  209. WorkingDirectory: c.WorkingDir,
  210. ConsoleSize: c.ProcessConfig.ConsoleSize,
  211. }
  212. // Configure the environment for the process
  213. createProcessParms.Environment = setupEnvironmentVariables(c.ProcessConfig.Env)
  214. // This should get caught earlier, but just in case - validate that we
  215. // have something to run
  216. if c.ProcessConfig.Entrypoint == "" {
  217. err = errors.New("No entrypoint specified")
  218. logrus.Error(err)
  219. return execdriver.ExitStatus{ExitCode: -1}, err
  220. }
  221. // Build the command line of the process
  222. createProcessParms.CommandLine = c.ProcessConfig.Entrypoint
  223. for _, arg := range c.ProcessConfig.Arguments {
  224. logrus.Debugln("appending ", arg)
  225. createProcessParms.CommandLine += " " + arg
  226. }
  227. logrus.Debugf("CommandLine: %s", createProcessParms.CommandLine)
  228. // Start the command running in the container.
  229. pid, stdin, stdout, stderr, err := hcsshim.CreateProcessInComputeSystem(c.ID, pipes.Stdin != nil, true, !c.ProcessConfig.Tty, createProcessParms)
  230. if err != nil {
  231. logrus.Errorf("CreateProcessInComputeSystem() failed %s", err)
  232. return execdriver.ExitStatus{ExitCode: -1}, err
  233. }
  234. // Now that the process has been launched, begin copying data to and from
  235. // the named pipes for the std handles.
  236. setupPipes(stdin, stdout, stderr, pipes)
  237. //Save the PID as we'll need this in Kill()
  238. logrus.Debugf("PID %d", pid)
  239. c.ContainerPid = int(pid)
  240. if c.ProcessConfig.Tty {
  241. term = NewTtyConsole(c.ID, pid)
  242. } else {
  243. term = NewStdConsole()
  244. }
  245. c.ProcessConfig.Terminal = term
  246. // Maintain our list of active containers. We'll need this later for exec
  247. // and other commands.
  248. d.Lock()
  249. d.activeContainers[c.ID] = &activeContainer{
  250. command: c,
  251. }
  252. d.Unlock()
  253. if hooks.Start != nil {
  254. // A closed channel for OOM is returned here as it will be
  255. // non-blocking and return the correct result when read.
  256. chOOM := make(chan struct{})
  257. close(chOOM)
  258. hooks.Start(&c.ProcessConfig, int(pid), chOOM)
  259. }
  260. var exitCode int32
  261. exitCode, err = hcsshim.WaitForProcessInComputeSystem(c.ID, pid)
  262. if err != nil {
  263. logrus.Errorf("Failed to WaitForProcessInComputeSystem %s", err)
  264. return execdriver.ExitStatus{ExitCode: -1}, err
  265. }
  266. logrus.Debugf("Exiting Run() exitCode %d id=%s", exitCode, c.ID)
  267. return execdriver.ExitStatus{ExitCode: int(exitCode)}, nil
  268. }
  269. // SupportsHooks implements the execdriver Driver interface.
  270. // The windows driver does not support the hook mechanism
  271. func (d *Driver) SupportsHooks() bool {
  272. return false
  273. }