container_unix.go 14 KB

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