oci_windows.go 15 KB

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