oci_windows.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. package daemon // import "github.com/docker/docker/daemon"
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "os"
  7. "path/filepath"
  8. "strings"
  9. containertypes "github.com/docker/docker/api/types/container"
  10. imagetypes "github.com/docker/docker/api/types/image"
  11. "github.com/docker/docker/container"
  12. "github.com/docker/docker/errdefs"
  13. "github.com/docker/docker/oci"
  14. "github.com/docker/docker/pkg/sysinfo"
  15. "github.com/docker/docker/pkg/system"
  16. specs "github.com/opencontainers/runtime-spec/specs-go"
  17. "github.com/pkg/errors"
  18. "github.com/sirupsen/logrus"
  19. "golang.org/x/sys/windows/registry"
  20. )
  21. const (
  22. credentialSpecRegistryLocation = `SOFTWARE\Microsoft\Windows NT\CurrentVersion\Virtualization\Containers\CredentialSpecs`
  23. credentialSpecFileLocation = "CredentialSpecs"
  24. )
  25. func (daemon *Daemon) createSpec(c *container.Container) (*specs.Spec, error) {
  26. ctx := context.TODO()
  27. img, err := daemon.imageService.GetImage(ctx, string(c.ImageID), imagetypes.GetImageOpts{})
  28. if err != nil {
  29. return nil, err
  30. }
  31. if !system.IsOSSupported(img.OperatingSystem()) {
  32. return nil, system.ErrNotSupportedOperatingSystem
  33. }
  34. s := oci.DefaultSpec()
  35. linkedEnv, err := daemon.setupLinkedContainers(c)
  36. if err != nil {
  37. return nil, err
  38. }
  39. // Note, unlike Unix, we do NOT call into SetupWorkingDirectory as
  40. // this is done in VMCompute. Further, we couldn't do it for Hyper-V
  41. // containers anyway.
  42. if err := daemon.setupSecretDir(c); err != nil {
  43. return nil, err
  44. }
  45. if err := daemon.setupConfigDir(c); err != nil {
  46. return nil, err
  47. }
  48. // In s.Mounts
  49. mounts, err := daemon.setupMounts(c)
  50. if err != nil {
  51. return nil, err
  52. }
  53. var isHyperV bool
  54. if c.HostConfig.Isolation.IsDefault() {
  55. // Container using default isolation, so take the default from the daemon configuration
  56. isHyperV = daemon.defaultIsolation.IsHyperV()
  57. } else {
  58. // Container may be requesting an explicit isolation mode.
  59. isHyperV = c.HostConfig.Isolation.IsHyperV()
  60. }
  61. if isHyperV {
  62. s.Windows.HyperV = &specs.WindowsHyperV{}
  63. }
  64. // If the container has not been started, and has configs or secrets
  65. // secrets, create symlinks to each config and secret. If it has been
  66. // started before, the symlinks should have already been created. Also, it
  67. // is important to not mount a Hyper-V container that has been started
  68. // before, to protect the host from the container; for example, from
  69. // malicious mutation of NTFS data structures.
  70. if !c.HasBeenStartedBefore && (len(c.SecretReferences) > 0 || len(c.ConfigReferences) > 0) {
  71. // The container file system is mounted before this function is called,
  72. // except for Hyper-V containers, so mount it here in that case.
  73. if isHyperV {
  74. if err := daemon.Mount(c); err != nil {
  75. return nil, err
  76. }
  77. defer daemon.Unmount(c)
  78. }
  79. if err := c.CreateSecretSymlinks(); err != nil {
  80. return nil, err
  81. }
  82. if err := c.CreateConfigSymlinks(); err != nil {
  83. return nil, err
  84. }
  85. }
  86. secretMounts, err := c.SecretMounts()
  87. if err != nil {
  88. return nil, err
  89. }
  90. if secretMounts != nil {
  91. mounts = append(mounts, secretMounts...)
  92. }
  93. configMounts := c.ConfigMounts()
  94. if configMounts != nil {
  95. mounts = append(mounts, configMounts...)
  96. }
  97. for _, mount := range mounts {
  98. m := specs.Mount{
  99. Source: mount.Source,
  100. Destination: mount.Destination,
  101. }
  102. if !mount.Writable {
  103. m.Options = append(m.Options, "ro")
  104. }
  105. s.Mounts = append(s.Mounts, m)
  106. }
  107. // In s.Process
  108. s.Process.Cwd = c.Config.WorkingDir
  109. s.Process.Env = c.CreateDaemonEnvironment(c.Config.Tty, linkedEnv)
  110. s.Process.Terminal = c.Config.Tty
  111. if c.Config.Tty {
  112. s.Process.ConsoleSize = &specs.Box{
  113. Height: c.HostConfig.ConsoleSize[0],
  114. Width: c.HostConfig.ConsoleSize[1],
  115. }
  116. }
  117. s.Process.User.Username = c.Config.User
  118. s.Windows.LayerFolders, err = daemon.imageService.GetLayerFolders(img, c.RWLayer)
  119. if err != nil {
  120. return nil, errors.Wrapf(err, "container %s", c.ID)
  121. }
  122. dnsSearch := daemon.getDNSSearchSettings(c)
  123. // Get endpoints for the libnetwork allocated networks to the container
  124. var epList []string
  125. AllowUnqualifiedDNSQuery := false
  126. gwHNSID := ""
  127. if c.NetworkSettings != nil {
  128. for n := range c.NetworkSettings.Networks {
  129. sn, err := daemon.FindNetwork(n)
  130. if err != nil {
  131. continue
  132. }
  133. ep, err := getEndpointInNetwork(c.Name, sn)
  134. if err != nil {
  135. continue
  136. }
  137. data, err := ep.DriverInfo()
  138. if err != nil {
  139. continue
  140. }
  141. if data["GW_INFO"] != nil {
  142. gwInfo := data["GW_INFO"].(map[string]interface{})
  143. if gwInfo["hnsid"] != nil {
  144. gwHNSID = gwInfo["hnsid"].(string)
  145. }
  146. }
  147. if data["hnsid"] != nil {
  148. epList = append(epList, data["hnsid"].(string))
  149. }
  150. if data["AllowUnqualifiedDNSQuery"] != nil {
  151. AllowUnqualifiedDNSQuery = true
  152. }
  153. }
  154. }
  155. var networkSharedContainerID string
  156. if c.HostConfig.NetworkMode.IsContainer() {
  157. networkSharedContainerID = c.NetworkSharedContainerID
  158. for _, ep := range c.SharedEndpointList {
  159. epList = append(epList, ep)
  160. }
  161. }
  162. if gwHNSID != "" {
  163. epList = append(epList, gwHNSID)
  164. }
  165. s.Windows.Network = &specs.WindowsNetwork{
  166. AllowUnqualifiedDNSQuery: AllowUnqualifiedDNSQuery,
  167. DNSSearchList: dnsSearch,
  168. EndpointList: epList,
  169. NetworkSharedContainerName: networkSharedContainerID,
  170. }
  171. if err := daemon.createSpecWindowsFields(c, &s, isHyperV); err != nil {
  172. return nil, err
  173. }
  174. if logrus.IsLevelEnabled(logrus.DebugLevel) {
  175. if b, err := json.Marshal(&s); err == nil {
  176. logrus.Debugf("Generated spec: %s", string(b))
  177. }
  178. }
  179. return &s, nil
  180. }
  181. // Sets the Windows-specific fields of the OCI spec
  182. func (daemon *Daemon) createSpecWindowsFields(c *container.Container, s *specs.Spec, isHyperV bool) error {
  183. s.Hostname = c.FullHostname()
  184. if len(s.Process.Cwd) == 0 {
  185. // We default to C:\ to workaround the oddity of the case that the
  186. // default directory for cmd running as LocalSystem (or
  187. // ContainerAdministrator) is c:\windows\system32. Hence docker run
  188. // <image> cmd will by default end in c:\windows\system32, rather
  189. // than 'root' (/) on Linux. The oddity is that if you have a dockerfile
  190. // which has no WORKDIR and has a COPY file ., . will be interpreted
  191. // as c:\. Hence, setting it to default of c:\ makes for consistency.
  192. s.Process.Cwd = `C:\`
  193. }
  194. if c.Config.ArgsEscaped {
  195. s.Process.CommandLine = c.Path
  196. if len(c.Args) > 0 {
  197. s.Process.CommandLine += " " + system.EscapeArgs(c.Args)
  198. }
  199. } else {
  200. s.Process.Args = append([]string{c.Path}, c.Args...)
  201. }
  202. s.Root.Readonly = false // Windows does not support a read-only root filesystem
  203. if !isHyperV {
  204. if c.BaseFS == "" {
  205. return errors.New("createSpecWindowsFields: BaseFS of container " + c.ID + " is unexpectedly empty")
  206. }
  207. s.Root.Path = c.BaseFS // This is not set for Hyper-V containers
  208. if !strings.HasSuffix(s.Root.Path, `\`) {
  209. s.Root.Path = s.Root.Path + `\` // Ensure a correctly formatted volume GUID path \\?\Volume{GUID}\
  210. }
  211. }
  212. // First boot optimization
  213. s.Windows.IgnoreFlushesDuringBoot = !c.HasBeenStartedBefore
  214. setResourcesInSpec(c, s, isHyperV)
  215. // Read and add credentials from the security options if a credential spec has been provided.
  216. if err := daemon.setWindowsCredentialSpec(c, s); err != nil {
  217. return err
  218. }
  219. devices, err := setupWindowsDevices(c.HostConfig.Devices)
  220. if err != nil {
  221. return err
  222. }
  223. s.Windows.Devices = append(s.Windows.Devices, devices...)
  224. return nil
  225. }
  226. var errInvalidCredentialSpecSecOpt = errdefs.InvalidParameter(fmt.Errorf("invalid credential spec security option - value must be prefixed by 'file://', 'registry://', or 'raw://' followed by a non-empty value"))
  227. // setWindowsCredentialSpec sets the spec's `Windows.CredentialSpec`
  228. // field if relevant
  229. func (daemon *Daemon) setWindowsCredentialSpec(c *container.Container, s *specs.Spec) error {
  230. if c.HostConfig == nil || c.HostConfig.SecurityOpt == nil {
  231. return nil
  232. }
  233. // TODO (jrouge/wk8): if provided with several security options, we silently ignore
  234. // all but the last one (provided they're all valid, otherwise we do return an error);
  235. // this doesn't seem like a great idea?
  236. credentialSpec := ""
  237. for _, secOpt := range c.HostConfig.SecurityOpt {
  238. optSplits := strings.SplitN(secOpt, "=", 2)
  239. if len(optSplits) != 2 {
  240. return errdefs.InvalidParameter(fmt.Errorf("invalid security option: no equals sign in supplied value %s", secOpt))
  241. }
  242. if !strings.EqualFold(optSplits[0], "credentialspec") {
  243. return errdefs.InvalidParameter(fmt.Errorf("security option not supported: %s", optSplits[0]))
  244. }
  245. credSpecSplits := strings.SplitN(optSplits[1], "://", 2)
  246. if len(credSpecSplits) != 2 || credSpecSplits[1] == "" {
  247. return errInvalidCredentialSpecSecOpt
  248. }
  249. value := credSpecSplits[1]
  250. var err error
  251. switch strings.ToLower(credSpecSplits[0]) {
  252. case "file":
  253. if credentialSpec, err = readCredentialSpecFile(c.ID, daemon.root, filepath.Clean(value)); err != nil {
  254. return errdefs.InvalidParameter(err)
  255. }
  256. case "registry":
  257. if credentialSpec, err = readCredentialSpecRegistry(c.ID, value); err != nil {
  258. return errdefs.InvalidParameter(err)
  259. }
  260. case "config":
  261. // if the container does not have a DependencyStore, then it
  262. // isn't swarmkit managed. In order to avoid creating any
  263. // impression that `config://` is a valid API, return the same
  264. // error as if you'd passed any other random word.
  265. if c.DependencyStore == nil {
  266. return errInvalidCredentialSpecSecOpt
  267. }
  268. csConfig, err := c.DependencyStore.Configs().Get(value)
  269. if err != nil {
  270. return errdefs.System(errors.Wrap(err, "error getting value from config store"))
  271. }
  272. // stuff the resulting secret data into a string to use as the
  273. // CredentialSpec
  274. credentialSpec = string(csConfig.Spec.Data)
  275. case "raw":
  276. credentialSpec = value
  277. default:
  278. return errInvalidCredentialSpecSecOpt
  279. }
  280. }
  281. if credentialSpec != "" {
  282. if s.Windows == nil {
  283. s.Windows = &specs.Windows{}
  284. }
  285. s.Windows.CredentialSpec = credentialSpec
  286. }
  287. return nil
  288. }
  289. func setResourcesInSpec(c *container.Container, s *specs.Spec, isHyperV bool) {
  290. // In s.Windows.Resources
  291. cpuShares := uint16(c.HostConfig.CPUShares)
  292. cpuMaximum := uint16(c.HostConfig.CPUPercent) * 100
  293. cpuCount := uint64(c.HostConfig.CPUCount)
  294. if c.HostConfig.NanoCPUs > 0 {
  295. if isHyperV {
  296. cpuCount = uint64(c.HostConfig.NanoCPUs / 1e9)
  297. leftoverNanoCPUs := c.HostConfig.NanoCPUs % 1e9
  298. if leftoverNanoCPUs != 0 {
  299. cpuCount++
  300. cpuMaximum = uint16(c.HostConfig.NanoCPUs / int64(cpuCount) / (1e9 / 10000))
  301. if cpuMaximum < 1 {
  302. // The requested NanoCPUs is so small that we rounded to 0, use 1 instead
  303. cpuMaximum = 1
  304. }
  305. }
  306. } else {
  307. cpuMaximum = uint16(c.HostConfig.NanoCPUs / int64(sysinfo.NumCPU()) / (1e9 / 10000))
  308. if cpuMaximum < 1 {
  309. // The requested NanoCPUs is so small that we rounded to 0, use 1 instead
  310. cpuMaximum = 1
  311. }
  312. }
  313. }
  314. if cpuMaximum != 0 || cpuShares != 0 || cpuCount != 0 {
  315. if s.Windows.Resources == nil {
  316. s.Windows.Resources = &specs.WindowsResources{}
  317. }
  318. s.Windows.Resources.CPU = &specs.WindowsCPUResources{
  319. Maximum: &cpuMaximum,
  320. Shares: &cpuShares,
  321. Count: &cpuCount,
  322. }
  323. }
  324. memoryLimit := uint64(c.HostConfig.Memory)
  325. if memoryLimit != 0 {
  326. if s.Windows.Resources == nil {
  327. s.Windows.Resources = &specs.WindowsResources{}
  328. }
  329. s.Windows.Resources.Memory = &specs.WindowsMemoryResources{
  330. Limit: &memoryLimit,
  331. }
  332. }
  333. if c.HostConfig.IOMaximumBandwidth != 0 || c.HostConfig.IOMaximumIOps != 0 {
  334. if s.Windows.Resources == nil {
  335. s.Windows.Resources = &specs.WindowsResources{}
  336. }
  337. s.Windows.Resources.Storage = &specs.WindowsStorageResources{
  338. Bps: &c.HostConfig.IOMaximumBandwidth,
  339. Iops: &c.HostConfig.IOMaximumIOps,
  340. }
  341. }
  342. }
  343. // mergeUlimits merge the Ulimits from HostConfig with daemon defaults, and update HostConfig
  344. // It will do nothing on non-Linux platform
  345. func (daemon *Daemon) mergeUlimits(c *containertypes.HostConfig) {
  346. return
  347. }
  348. // registryKey is an interface wrapper around `registry.Key`,
  349. // listing only the methods we care about here.
  350. // It's mainly useful to easily allow mocking the registry in tests.
  351. type registryKey interface {
  352. GetStringValue(name string) (val string, valtype uint32, err error)
  353. Close() error
  354. }
  355. var registryOpenKeyFunc = func(baseKey registry.Key, path string, access uint32) (registryKey, error) {
  356. return registry.OpenKey(baseKey, path, access)
  357. }
  358. // readCredentialSpecRegistry is a helper function to read a credential spec from
  359. // the registry. If not found, we return an empty string and warn in the log.
  360. // This allows for staging on machines which do not have the necessary components.
  361. func readCredentialSpecRegistry(id, name string) (string, error) {
  362. key, err := registryOpenKeyFunc(registry.LOCAL_MACHINE, credentialSpecRegistryLocation, registry.QUERY_VALUE)
  363. if err != nil {
  364. return "", errors.Wrapf(err, "failed handling spec %q for container %s - registry key %s could not be opened", name, id, credentialSpecRegistryLocation)
  365. }
  366. defer key.Close()
  367. value, _, err := key.GetStringValue(name)
  368. if err != nil {
  369. if err == registry.ErrNotExist {
  370. return "", fmt.Errorf("registry credential spec %q for container %s was not found", name, id)
  371. }
  372. return "", errors.Wrapf(err, "error reading credential spec %q from registry for container %s", name, id)
  373. }
  374. return value, nil
  375. }
  376. // readCredentialSpecFile is a helper function to read a credential spec from
  377. // a file. If not found, we return an empty string and warn in the log.
  378. // This allows for staging on machines which do not have the necessary components.
  379. func readCredentialSpecFile(id, root, location string) (string, error) {
  380. if filepath.IsAbs(location) {
  381. return "", fmt.Errorf("invalid credential spec - file:// path cannot be absolute")
  382. }
  383. base := filepath.Join(root, credentialSpecFileLocation)
  384. full := filepath.Join(base, location)
  385. if !strings.HasPrefix(full, base) {
  386. return "", fmt.Errorf("invalid credential spec - file:// path must be under %s", base)
  387. }
  388. bcontents, err := os.ReadFile(full)
  389. if err != nil {
  390. return "", errors.Wrapf(err, "credential spec for container %s could not be read from file %q", id, full)
  391. }
  392. return string(bcontents[:]), nil
  393. }
  394. func setupWindowsDevices(devices []containertypes.DeviceMapping) (specDevices []specs.WindowsDevice, err error) {
  395. if len(devices) == 0 {
  396. return
  397. }
  398. for _, deviceMapping := range devices {
  399. devicePath := deviceMapping.PathOnHost
  400. if strings.HasPrefix(devicePath, "class/") {
  401. devicePath = strings.Replace(devicePath, "class/", "class://", 1)
  402. }
  403. srcParts := strings.SplitN(devicePath, "://", 2)
  404. if len(srcParts) != 2 {
  405. return nil, errors.Errorf("invalid device assignment path: '%s', must be 'class/ID' or 'IDType://ID'", deviceMapping.PathOnHost)
  406. }
  407. if srcParts[0] == "" {
  408. return nil, errors.Errorf("invalid device assignment path: '%s', IDType cannot be empty", deviceMapping.PathOnHost)
  409. }
  410. wd := specs.WindowsDevice{
  411. ID: srcParts[1],
  412. IDType: srcParts[0],
  413. }
  414. specDevices = append(specDevices, wd)
  415. }
  416. return
  417. }