run.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. // +build windows
  2. package windows
  3. import (
  4. "encoding/json"
  5. "fmt"
  6. "os"
  7. "path/filepath"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "github.com/Sirupsen/logrus"
  12. "github.com/docker/docker/daemon/execdriver"
  13. "github.com/microsoft/hcsshim"
  14. )
  15. // defaultContainerNAT is the default name of the container NAT device that is
  16. // preconfigured on the server.
  17. const defaultContainerNAT = "ContainerNAT"
  18. type layer struct {
  19. ID string
  20. Path string
  21. }
  22. type defConfig struct {
  23. DefFile string
  24. }
  25. type portBinding struct {
  26. Protocol string
  27. InternalPort int
  28. ExternalPort int
  29. }
  30. type natSettings struct {
  31. Name string
  32. PortBindings []portBinding
  33. }
  34. type networkConnection struct {
  35. NetworkName string
  36. // TODO Windows: Add Ip4Address string to this structure when hooked up in
  37. // docker CLI. This is present in the HCS JSON handler.
  38. EnableNat bool
  39. Nat natSettings
  40. }
  41. type networkSettings struct {
  42. MacAddress string
  43. }
  44. type device struct {
  45. DeviceType string
  46. Connection interface{}
  47. Settings interface{}
  48. }
  49. type mappedDir struct {
  50. HostPath string
  51. ContainerPath string
  52. ReadOnly bool
  53. }
  54. type containerInit struct {
  55. SystemType string // HCS requires this to be hard-coded to "Container"
  56. Name string // Name of the container. We use the docker ID.
  57. Owner string // The management platform that created this container
  58. IsDummy bool // Used for development purposes.
  59. VolumePath string // Windows volume path for scratch space
  60. Devices []device // Devices used by the container
  61. IgnoreFlushesDuringBoot bool // Optimisation hint for container startup in Windows
  62. LayerFolderPath string // Where the layer folders are located
  63. Layers []layer // List of storage layers
  64. ProcessorWeight int64 `json:",omitempty"` // CPU Shares 0..10000 on Windows; where 0 will be ommited and HCS will default.
  65. HostName string // Hostname
  66. MappedDirectories []mappedDir // List of mapped directories (volumes/mounts)
  67. SandboxPath string // Location of unmounted sandbox (used for Hyper-V containers, not Windows Server containers)
  68. HvPartition bool // True if it a Hyper-V Container
  69. }
  70. // defaultOwner is a tag passed to HCS to allow it to differentiate between
  71. // container creator management stacks. We hard code "docker" in the case
  72. // of docker.
  73. const defaultOwner = "docker"
  74. // Run implements the exec driver Driver interface
  75. func (d *Driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, hooks execdriver.Hooks) (execdriver.ExitStatus, error) {
  76. var (
  77. term execdriver.Terminal
  78. err error
  79. )
  80. cu := &containerInit{
  81. SystemType: "Container",
  82. Name: c.ID,
  83. Owner: defaultOwner,
  84. IsDummy: dummyMode,
  85. VolumePath: c.Rootfs,
  86. IgnoreFlushesDuringBoot: c.FirstStart,
  87. LayerFolderPath: c.LayerFolder,
  88. ProcessorWeight: c.Resources.CPUShares,
  89. HostName: c.Hostname,
  90. }
  91. cu.HvPartition = c.HvPartition
  92. if cu.HvPartition {
  93. cu.SandboxPath = filepath.Dir(c.LayerFolder)
  94. } else {
  95. cu.VolumePath = c.Rootfs
  96. cu.LayerFolderPath = c.LayerFolder
  97. }
  98. for _, layerPath := range c.LayerPaths {
  99. _, filename := filepath.Split(layerPath)
  100. g, err := hcsshim.NameToGuid(filename)
  101. if err != nil {
  102. return execdriver.ExitStatus{ExitCode: -1}, err
  103. }
  104. cu.Layers = append(cu.Layers, layer{
  105. ID: g.ToString(),
  106. Path: layerPath,
  107. })
  108. }
  109. // Add the mounts (volumes, bind mounts etc) to the structure
  110. mds := make([]mappedDir, len(c.Mounts))
  111. for i, mount := range c.Mounts {
  112. mds[i] = mappedDir{
  113. HostPath: mount.Source,
  114. ContainerPath: mount.Destination,
  115. ReadOnly: !mount.Writable}
  116. }
  117. cu.MappedDirectories = mds
  118. // TODO Windows. At some point, when there is CLI on docker run to
  119. // enable the IP Address of the container to be passed into docker run,
  120. // the IP Address needs to be wired through to HCS in the JSON. It
  121. // would be present in c.Network.Interface.IPAddress. See matching
  122. // TODO in daemon\container_windows.go, function populateCommand.
  123. if c.Network.Interface != nil {
  124. var pbs []portBinding
  125. // Enumerate through the port bindings specified by the user and convert
  126. // them into the internal structure matching the JSON blob that can be
  127. // understood by the HCS.
  128. for i, v := range c.Network.Interface.PortBindings {
  129. proto := strings.ToUpper(i.Proto())
  130. if proto != "TCP" && proto != "UDP" {
  131. return execdriver.ExitStatus{ExitCode: -1}, fmt.Errorf("invalid protocol %s", i.Proto())
  132. }
  133. if len(v) > 1 {
  134. return execdriver.ExitStatus{ExitCode: -1}, fmt.Errorf("Windows does not support more than one host port in NAT settings")
  135. }
  136. for _, v2 := range v {
  137. var (
  138. iPort, ePort int
  139. err error
  140. )
  141. if len(v2.HostIP) != 0 {
  142. return execdriver.ExitStatus{ExitCode: -1}, fmt.Errorf("Windows does not support host IP addresses in NAT settings")
  143. }
  144. if ePort, err = strconv.Atoi(v2.HostPort); err != nil {
  145. return execdriver.ExitStatus{ExitCode: -1}, fmt.Errorf("invalid container port %s: %s", v2.HostPort, err)
  146. }
  147. if iPort, err = strconv.Atoi(i.Port()); err != nil {
  148. return execdriver.ExitStatus{ExitCode: -1}, fmt.Errorf("invalid internal port %s: %s", i.Port(), err)
  149. }
  150. if iPort < 0 || iPort > 65535 || ePort < 0 || ePort > 65535 {
  151. return execdriver.ExitStatus{ExitCode: -1}, fmt.Errorf("specified NAT port is not in allowed range")
  152. }
  153. pbs = append(pbs,
  154. portBinding{ExternalPort: ePort,
  155. InternalPort: iPort,
  156. Protocol: proto})
  157. }
  158. }
  159. // TODO Windows: TP3 workaround. Allow the user to override the name of
  160. // the Container NAT device through an environment variable. This will
  161. // ultimately be a global daemon parameter on Windows, similar to -b
  162. // for the name of the virtual switch (aka bridge).
  163. cn := os.Getenv("DOCKER_CONTAINER_NAT")
  164. if len(cn) == 0 {
  165. cn = defaultContainerNAT
  166. }
  167. dev := device{
  168. DeviceType: "Network",
  169. Connection: &networkConnection{
  170. NetworkName: c.Network.Interface.Bridge,
  171. // TODO Windows: Fixme, next line. Needs HCS fix.
  172. EnableNat: false,
  173. Nat: natSettings{
  174. Name: cn,
  175. PortBindings: pbs,
  176. },
  177. },
  178. }
  179. if c.Network.Interface.MacAddress != "" {
  180. windowsStyleMAC := strings.Replace(
  181. c.Network.Interface.MacAddress, ":", "-", -1)
  182. dev.Settings = networkSettings{
  183. MacAddress: windowsStyleMAC,
  184. }
  185. }
  186. cu.Devices = append(cu.Devices, dev)
  187. } else {
  188. logrus.Debugln("No network interface")
  189. }
  190. configurationb, err := json.Marshal(cu)
  191. if err != nil {
  192. return execdriver.ExitStatus{ExitCode: -1}, err
  193. }
  194. configuration := string(configurationb)
  195. // TODO Windows TP5 timeframe. Remove when TP4 is no longer supported.
  196. // The following a workaround for Windows TP4 which has a networking
  197. // bug which fairly frequently returns an error. Back off and retry.
  198. maxAttempts := 1
  199. if TP4RetryHack {
  200. maxAttempts = 5
  201. }
  202. i := 0
  203. for i < maxAttempts {
  204. i++
  205. err = hcsshim.CreateComputeSystem(c.ID, configuration)
  206. if err != nil {
  207. if TP4RetryHack {
  208. if !strings.Contains(err.Error(), `Win32 API call returned error r1=0x800401f3`) && // Invalid class string
  209. !strings.Contains(err.Error(), `Win32 API call returned error r1=0x80070490`) && // Element not found
  210. !strings.Contains(err.Error(), `Win32 API call returned error r1=0x80070002`) && // The system cannot find the file specified
  211. !strings.Contains(err.Error(), `Win32 API call returned error r1=0x800704c6`) && // The network is not present or not started
  212. !strings.Contains(err.Error(), `Win32 API call returned error r1=0x800700a1`) { // The specified path is invalid
  213. logrus.Debugln("Failed to create temporary container ", err)
  214. return execdriver.ExitStatus{ExitCode: -1}, err
  215. }
  216. logrus.Warnf("Invoking Windows TP4 retry hack (%d of %d)", i, maxAttempts-1)
  217. time.Sleep(50 * time.Millisecond)
  218. }
  219. } else {
  220. break
  221. }
  222. }
  223. // Start the container
  224. logrus.Debugln("Starting container ", c.ID)
  225. err = hcsshim.StartComputeSystem(c.ID)
  226. if err != nil {
  227. logrus.Errorf("Failed to start compute system: %s", err)
  228. return execdriver.ExitStatus{ExitCode: -1}, err
  229. }
  230. defer func() {
  231. // Stop the container
  232. if forceKill {
  233. logrus.Debugf("Forcibly terminating container %s", c.ID)
  234. if errno, err := hcsshim.TerminateComputeSystem(c.ID, hcsshim.TimeoutInfinite, "exec-run-defer"); err != nil {
  235. logrus.Warnf("Ignoring error from TerminateComputeSystem 0x%X %s", errno, err)
  236. }
  237. } else {
  238. logrus.Debugf("Shutting down container %s", c.ID)
  239. if errno, err := hcsshim.ShutdownComputeSystem(c.ID, hcsshim.TimeoutInfinite, "exec-run-defer"); err != nil {
  240. if errno != hcsshim.Win32SystemShutdownIsInProgress &&
  241. errno != hcsshim.Win32SpecifiedPathInvalid &&
  242. errno != hcsshim.Win32SystemCannotFindThePathSpecified {
  243. logrus.Warnf("Ignoring error from ShutdownComputeSystem 0x%X %s", errno, err)
  244. }
  245. }
  246. }
  247. }()
  248. createProcessParms := hcsshim.CreateProcessParams{
  249. EmulateConsole: c.ProcessConfig.Tty,
  250. WorkingDirectory: c.WorkingDir,
  251. ConsoleSize: c.ProcessConfig.ConsoleSize,
  252. }
  253. // Configure the environment for the process
  254. createProcessParms.Environment = setupEnvironmentVariables(c.ProcessConfig.Env)
  255. createProcessParms.CommandLine, err = createCommandLine(&c.ProcessConfig, c.ArgsEscaped)
  256. if err != nil {
  257. return execdriver.ExitStatus{ExitCode: -1}, err
  258. }
  259. // Start the command running in the container.
  260. pid, stdin, stdout, stderr, _, err := hcsshim.CreateProcessInComputeSystem(c.ID, pipes.Stdin != nil, true, !c.ProcessConfig.Tty, createProcessParms)
  261. if err != nil {
  262. logrus.Errorf("CreateProcessInComputeSystem() failed %s", err)
  263. return execdriver.ExitStatus{ExitCode: -1}, err
  264. }
  265. // Now that the process has been launched, begin copying data to and from
  266. // the named pipes for the std handles.
  267. setupPipes(stdin, stdout, stderr, pipes)
  268. //Save the PID as we'll need this in Kill()
  269. logrus.Debugf("PID %d", pid)
  270. c.ContainerPid = int(pid)
  271. if c.ProcessConfig.Tty {
  272. term = NewTtyConsole(c.ID, pid)
  273. } else {
  274. term = NewStdConsole()
  275. }
  276. c.ProcessConfig.Terminal = term
  277. // Maintain our list of active containers. We'll need this later for exec
  278. // and other commands.
  279. d.Lock()
  280. d.activeContainers[c.ID] = &activeContainer{
  281. command: c,
  282. }
  283. d.Unlock()
  284. if hooks.Start != nil {
  285. // A closed channel for OOM is returned here as it will be
  286. // non-blocking and return the correct result when read.
  287. chOOM := make(chan struct{})
  288. close(chOOM)
  289. hooks.Start(&c.ProcessConfig, int(pid), chOOM)
  290. }
  291. var (
  292. exitCode int32
  293. errno uint32
  294. )
  295. exitCode, errno, err = hcsshim.WaitForProcessInComputeSystem(c.ID, pid, hcsshim.TimeoutInfinite)
  296. if err != nil {
  297. if errno != hcsshim.Win32PipeHasBeenEnded {
  298. logrus.Warnf("WaitForProcessInComputeSystem failed (container may have been killed): %s", err)
  299. }
  300. // Do NOT return err here as the container would have
  301. // started, otherwise docker will deadlock. It's perfectly legitimate
  302. // for WaitForProcessInComputeSystem to fail in situations such
  303. // as the container being killed on another thread.
  304. return execdriver.ExitStatus{ExitCode: hcsshim.WaitErrExecFailed}, nil
  305. }
  306. logrus.Debugf("Exiting Run() exitCode %d id=%s", exitCode, c.ID)
  307. return execdriver.ExitStatus{ExitCode: int(exitCode)}, nil
  308. }
  309. // SupportsHooks implements the execdriver Driver interface.
  310. // The windows driver does not support the hook mechanism
  311. func (d *Driver) SupportsHooks() bool {
  312. return false
  313. }