container_unix.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. //go:build !windows
  2. package container // import "github.com/docker/docker/container"
  3. import (
  4. "context"
  5. "os"
  6. "path/filepath"
  7. "syscall"
  8. "github.com/containerd/continuity/fs"
  9. "github.com/containerd/log"
  10. "github.com/docker/docker/api/types"
  11. containertypes "github.com/docker/docker/api/types/container"
  12. "github.com/docker/docker/api/types/events"
  13. mounttypes "github.com/docker/docker/api/types/mount"
  14. swarmtypes "github.com/docker/docker/api/types/swarm"
  15. "github.com/docker/docker/pkg/stringid"
  16. "github.com/docker/docker/volume"
  17. volumemounts "github.com/docker/docker/volume/mounts"
  18. "github.com/moby/sys/mount"
  19. "github.com/opencontainers/selinux/go-selinux/label"
  20. "github.com/pkg/errors"
  21. )
  22. const (
  23. // defaultStopSignal is the default syscall signal used to stop a container.
  24. defaultStopSignal = "SIGTERM"
  25. // defaultStopTimeout sets the default time, in seconds, to wait
  26. // for the graceful container stop before forcefully terminating it.
  27. defaultStopTimeout = 10
  28. containerConfigMountPath = "/"
  29. containerSecretMountPath = "/run/secrets"
  30. )
  31. // TrySetNetworkMount attempts to set the network mounts given a provided destination and
  32. // the path to use for it; return true if the given destination was a network mount file
  33. func (container *Container) TrySetNetworkMount(destination string, path string) bool {
  34. if destination == "/etc/resolv.conf" {
  35. container.ResolvConfPath = path
  36. return true
  37. }
  38. if destination == "/etc/hostname" {
  39. container.HostnamePath = path
  40. return true
  41. }
  42. if destination == "/etc/hosts" {
  43. container.HostsPath = path
  44. return true
  45. }
  46. return false
  47. }
  48. // BuildHostnameFile writes the container's hostname file.
  49. func (container *Container) BuildHostnameFile() error {
  50. hostnamePath, err := container.GetRootResourcePath("hostname")
  51. if err != nil {
  52. return err
  53. }
  54. container.HostnamePath = hostnamePath
  55. return os.WriteFile(container.HostnamePath, []byte(container.Config.Hostname+"\n"), 0o644)
  56. }
  57. // NetworkMounts returns the list of network mounts.
  58. func (container *Container) NetworkMounts() []Mount {
  59. ctx := context.TODO()
  60. var mounts []Mount
  61. shared := container.HostConfig.NetworkMode.IsContainer()
  62. parser := volumemounts.NewParser()
  63. if container.ResolvConfPath != "" {
  64. if _, err := os.Stat(container.ResolvConfPath); err != nil {
  65. log.G(ctx).Warnf("ResolvConfPath set to %q, but can't stat this filename (err = %v); skipping", container.ResolvConfPath, err)
  66. } else {
  67. writable := !container.HostConfig.ReadonlyRootfs
  68. if m, exists := container.MountPoints["/etc/resolv.conf"]; exists {
  69. writable = m.RW
  70. } else {
  71. label.Relabel(container.ResolvConfPath, container.MountLabel, shared)
  72. }
  73. mounts = append(mounts, Mount{
  74. Source: container.ResolvConfPath,
  75. Destination: "/etc/resolv.conf",
  76. Writable: writable,
  77. Propagation: string(parser.DefaultPropagationMode()),
  78. })
  79. }
  80. }
  81. if container.HostnamePath != "" {
  82. if _, err := os.Stat(container.HostnamePath); err != nil {
  83. log.G(ctx).Warnf("HostnamePath set to %q, but can't stat this filename (err = %v); skipping", container.HostnamePath, err)
  84. } else {
  85. writable := !container.HostConfig.ReadonlyRootfs
  86. if m, exists := container.MountPoints["/etc/hostname"]; exists {
  87. writable = m.RW
  88. } else {
  89. label.Relabel(container.HostnamePath, container.MountLabel, shared)
  90. }
  91. mounts = append(mounts, Mount{
  92. Source: container.HostnamePath,
  93. Destination: "/etc/hostname",
  94. Writable: writable,
  95. Propagation: string(parser.DefaultPropagationMode()),
  96. })
  97. }
  98. }
  99. if container.HostsPath != "" {
  100. if _, err := os.Stat(container.HostsPath); err != nil {
  101. log.G(ctx).Warnf("HostsPath set to %q, but can't stat this filename (err = %v); skipping", container.HostsPath, err)
  102. } else {
  103. writable := !container.HostConfig.ReadonlyRootfs
  104. if m, exists := container.MountPoints["/etc/hosts"]; exists {
  105. writable = m.RW
  106. } else {
  107. label.Relabel(container.HostsPath, container.MountLabel, shared)
  108. }
  109. mounts = append(mounts, Mount{
  110. Source: container.HostsPath,
  111. Destination: "/etc/hosts",
  112. Writable: writable,
  113. Propagation: string(parser.DefaultPropagationMode()),
  114. })
  115. }
  116. }
  117. return mounts
  118. }
  119. // CopyImagePathContent copies files in destination to the volume.
  120. func (container *Container) CopyImagePathContent(v volume.Volume, destination string) error {
  121. rootfs, err := container.GetResourcePath(destination)
  122. if err != nil {
  123. return err
  124. }
  125. if _, err := os.Stat(rootfs); err != nil {
  126. if os.IsNotExist(err) {
  127. return nil
  128. }
  129. return err
  130. }
  131. id := stringid.GenerateRandomID()
  132. path, err := v.Mount(id)
  133. if err != nil {
  134. return err
  135. }
  136. defer func() {
  137. if err := v.Unmount(id); err != nil {
  138. log.G(context.TODO()).Warnf("error while unmounting volume %s: %v", v.Name(), err)
  139. }
  140. }()
  141. if err := label.Relabel(path, container.MountLabel, true); err != nil && !errors.Is(err, syscall.ENOTSUP) {
  142. return err
  143. }
  144. return copyExistingContents(rootfs, path)
  145. }
  146. // ShmResourcePath returns path to shm
  147. func (container *Container) ShmResourcePath() (string, error) {
  148. return container.MountsResourcePath("shm")
  149. }
  150. // HasMountFor checks if path is a mountpoint
  151. func (container *Container) HasMountFor(path string) bool {
  152. _, exists := container.MountPoints[path]
  153. if exists {
  154. return true
  155. }
  156. // Also search among the tmpfs mounts
  157. for dest := range container.HostConfig.Tmpfs {
  158. if dest == path {
  159. return true
  160. }
  161. }
  162. return false
  163. }
  164. // UnmountIpcMount unmounts shm if it was mounted
  165. func (container *Container) UnmountIpcMount() error {
  166. if container.HasMountFor("/dev/shm") {
  167. return nil
  168. }
  169. // container.ShmPath should not be used here as it may point
  170. // to the host's or other container's /dev/shm
  171. shmPath, err := container.ShmResourcePath()
  172. if err != nil {
  173. return err
  174. }
  175. if shmPath == "" {
  176. return nil
  177. }
  178. if err = mount.Unmount(shmPath); err != nil && !errors.Is(err, os.ErrNotExist) {
  179. return err
  180. }
  181. return nil
  182. }
  183. // IpcMounts returns the list of IPC mounts
  184. func (container *Container) IpcMounts() []Mount {
  185. var mounts []Mount
  186. parser := volumemounts.NewParser()
  187. if container.HasMountFor("/dev/shm") {
  188. return mounts
  189. }
  190. if container.ShmPath == "" {
  191. return mounts
  192. }
  193. label.SetFileLabel(container.ShmPath, container.MountLabel)
  194. mounts = append(mounts, Mount{
  195. Source: container.ShmPath,
  196. Destination: "/dev/shm",
  197. Writable: true,
  198. Propagation: string(parser.DefaultPropagationMode()),
  199. })
  200. return mounts
  201. }
  202. // SecretMounts returns the mounts for the secret path.
  203. func (container *Container) SecretMounts() ([]Mount, error) {
  204. var mounts []Mount
  205. for _, r := range container.SecretReferences {
  206. if r.File == nil {
  207. continue
  208. }
  209. src, err := container.SecretFilePath(*r)
  210. if err != nil {
  211. return nil, err
  212. }
  213. mounts = append(mounts, Mount{
  214. Source: src,
  215. Destination: getSecretTargetPath(r),
  216. Writable: false,
  217. })
  218. }
  219. for _, r := range container.ConfigReferences {
  220. fPath, err := container.ConfigFilePath(*r)
  221. if err != nil {
  222. return nil, err
  223. }
  224. mounts = append(mounts, Mount{
  225. Source: fPath,
  226. Destination: getConfigTargetPath(r),
  227. Writable: false,
  228. })
  229. }
  230. return mounts, nil
  231. }
  232. // UnmountSecrets unmounts the local tmpfs for secrets
  233. func (container *Container) UnmountSecrets() error {
  234. p, err := container.SecretMountPath()
  235. if err != nil {
  236. return err
  237. }
  238. if _, err := os.Stat(p); err != nil {
  239. if os.IsNotExist(err) {
  240. return nil
  241. }
  242. return err
  243. }
  244. return mount.RecursiveUnmount(p)
  245. }
  246. type conflictingUpdateOptions string
  247. func (e conflictingUpdateOptions) Error() string {
  248. return string(e)
  249. }
  250. func (e conflictingUpdateOptions) Conflict() {}
  251. // UpdateContainer updates configuration of a container. Callers must hold a Lock on the Container.
  252. func (container *Container) UpdateContainer(hostConfig *containertypes.HostConfig) error {
  253. // update resources of container
  254. resources := hostConfig.Resources
  255. cResources := &container.HostConfig.Resources
  256. // validate NanoCPUs, CPUPeriod, and CPUQuota
  257. // Because NanoCPU effectively updates CPUPeriod/CPUQuota,
  258. // once NanoCPU is already set, updating CPUPeriod/CPUQuota will be blocked, and vice versa.
  259. // In the following we make sure the intended update (resources) does not conflict with the existing (cResource).
  260. if resources.NanoCPUs > 0 && cResources.CPUPeriod > 0 {
  261. return conflictingUpdateOptions("Conflicting options: Nano CPUs cannot be updated as CPU Period has already been set")
  262. }
  263. if resources.NanoCPUs > 0 && cResources.CPUQuota > 0 {
  264. return conflictingUpdateOptions("Conflicting options: Nano CPUs cannot be updated as CPU Quota has already been set")
  265. }
  266. if resources.CPUPeriod > 0 && cResources.NanoCPUs > 0 {
  267. return conflictingUpdateOptions("Conflicting options: CPU Period cannot be updated as NanoCPUs has already been set")
  268. }
  269. if resources.CPUQuota > 0 && cResources.NanoCPUs > 0 {
  270. return conflictingUpdateOptions("Conflicting options: CPU Quota cannot be updated as NanoCPUs has already been set")
  271. }
  272. if resources.BlkioWeight != 0 {
  273. cResources.BlkioWeight = resources.BlkioWeight
  274. }
  275. if resources.CPUShares != 0 {
  276. cResources.CPUShares = resources.CPUShares
  277. }
  278. if resources.NanoCPUs != 0 {
  279. cResources.NanoCPUs = resources.NanoCPUs
  280. }
  281. if resources.CPUPeriod != 0 {
  282. cResources.CPUPeriod = resources.CPUPeriod
  283. }
  284. if resources.CPUQuota != 0 {
  285. cResources.CPUQuota = resources.CPUQuota
  286. }
  287. if resources.CpusetCpus != "" {
  288. cResources.CpusetCpus = resources.CpusetCpus
  289. }
  290. if resources.CpusetMems != "" {
  291. cResources.CpusetMems = resources.CpusetMems
  292. }
  293. if resources.Memory != 0 {
  294. // if memory limit smaller than already set memoryswap limit and doesn't
  295. // update the memoryswap limit, then error out.
  296. if resources.Memory > cResources.MemorySwap && resources.MemorySwap == 0 {
  297. return conflictingUpdateOptions("Memory limit should be smaller than already set memoryswap limit, update the memoryswap at the same time")
  298. }
  299. cResources.Memory = resources.Memory
  300. }
  301. if resources.MemorySwap != 0 {
  302. cResources.MemorySwap = resources.MemorySwap
  303. }
  304. if resources.MemoryReservation != 0 {
  305. cResources.MemoryReservation = resources.MemoryReservation
  306. }
  307. if resources.KernelMemory != 0 {
  308. cResources.KernelMemory = resources.KernelMemory
  309. }
  310. if resources.CPURealtimePeriod != 0 {
  311. cResources.CPURealtimePeriod = resources.CPURealtimePeriod
  312. }
  313. if resources.CPURealtimeRuntime != 0 {
  314. cResources.CPURealtimeRuntime = resources.CPURealtimeRuntime
  315. }
  316. if resources.PidsLimit != nil {
  317. cResources.PidsLimit = resources.PidsLimit
  318. }
  319. // update HostConfig of container
  320. if hostConfig.RestartPolicy.Name != "" {
  321. if container.HostConfig.AutoRemove && !hostConfig.RestartPolicy.IsNone() {
  322. return conflictingUpdateOptions("Restart policy cannot be updated because AutoRemove is enabled for the container")
  323. }
  324. container.HostConfig.RestartPolicy = hostConfig.RestartPolicy
  325. }
  326. return nil
  327. }
  328. // DetachAndUnmount uses a detached mount on all mount destinations, then
  329. // unmounts each volume normally.
  330. // This is used from daemon/archive for `docker cp`
  331. func (container *Container) DetachAndUnmount(volumeEventLog func(name string, action events.Action, attributes map[string]string)) error {
  332. ctx := context.TODO()
  333. networkMounts := container.NetworkMounts()
  334. mountPaths := make([]string, 0, len(container.MountPoints)+len(networkMounts))
  335. for _, mntPoint := range container.MountPoints {
  336. dest, err := container.GetResourcePath(mntPoint.Destination)
  337. if err != nil {
  338. log.G(ctx).Warnf("Failed to get volume destination path for container '%s' at '%s' while lazily unmounting: %v", container.ID, mntPoint.Destination, err)
  339. continue
  340. }
  341. mountPaths = append(mountPaths, dest)
  342. }
  343. for _, m := range networkMounts {
  344. dest, err := container.GetResourcePath(m.Destination)
  345. if err != nil {
  346. log.G(ctx).Warnf("Failed to get volume destination path for container '%s' at '%s' while lazily unmounting: %v", container.ID, m.Destination, err)
  347. continue
  348. }
  349. mountPaths = append(mountPaths, dest)
  350. }
  351. for _, mountPath := range mountPaths {
  352. if err := mount.Unmount(mountPath); err != nil {
  353. log.G(ctx).WithError(err).WithField("container", container.ID).
  354. Warn("Unable to unmount")
  355. }
  356. }
  357. return container.UnmountVolumes(volumeEventLog)
  358. }
  359. // ignoreUnsupportedXAttrs ignores errors when extended attributes
  360. // are not supported
  361. func ignoreUnsupportedXAttrs() fs.CopyDirOpt {
  362. xeh := func(dst, src, xattrKey string, err error) error {
  363. if !errors.Is(err, syscall.ENOTSUP) {
  364. return err
  365. }
  366. return nil
  367. }
  368. return fs.WithXAttrErrorHandler(xeh)
  369. }
  370. // copyExistingContents copies from the source to the destination and
  371. // ensures the ownership is appropriately set.
  372. func copyExistingContents(source, destination string) error {
  373. dstList, err := os.ReadDir(destination)
  374. if err != nil {
  375. return err
  376. }
  377. if len(dstList) != 0 {
  378. // destination is not empty, do not copy
  379. return nil
  380. }
  381. return fs.CopyDir(destination, source, ignoreUnsupportedXAttrs())
  382. }
  383. // TmpfsMounts returns the list of tmpfs mounts
  384. func (container *Container) TmpfsMounts() ([]Mount, error) {
  385. var mounts []Mount
  386. for dest, data := range container.HostConfig.Tmpfs {
  387. mounts = append(mounts, Mount{
  388. Source: "tmpfs",
  389. Destination: dest,
  390. Data: data,
  391. })
  392. }
  393. parser := volumemounts.NewParser()
  394. for dest, mnt := range container.MountPoints {
  395. if mnt.Type == mounttypes.TypeTmpfs {
  396. data, err := parser.ConvertTmpfsOptions(mnt.Spec.TmpfsOptions, mnt.Spec.ReadOnly)
  397. if err != nil {
  398. return nil, err
  399. }
  400. mounts = append(mounts, Mount{
  401. Source: "tmpfs",
  402. Destination: dest,
  403. Data: data,
  404. })
  405. }
  406. }
  407. return mounts, nil
  408. }
  409. // GetMountPoints gives a platform specific transformation to types.MountPoint. Callers must hold a Container lock.
  410. func (container *Container) GetMountPoints() []types.MountPoint {
  411. mountPoints := make([]types.MountPoint, 0, len(container.MountPoints))
  412. for _, m := range container.MountPoints {
  413. mountPoints = append(mountPoints, types.MountPoint{
  414. Type: m.Type,
  415. Name: m.Name,
  416. Source: m.Path(),
  417. Destination: m.Destination,
  418. Driver: m.Driver,
  419. Mode: m.Mode,
  420. RW: m.RW,
  421. Propagation: m.Propagation,
  422. })
  423. }
  424. return mountPoints
  425. }
  426. // ConfigFilePath returns the path to the on-disk location of a config.
  427. // On unix, configs are always considered secret
  428. func (container *Container) ConfigFilePath(configRef swarmtypes.ConfigReference) (string, error) {
  429. mounts, err := container.SecretMountPath()
  430. if err != nil {
  431. return "", err
  432. }
  433. return filepath.Join(mounts, configRef.ConfigID), nil
  434. }