run.go 9.7 KB

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