container_unix.go 14 KB

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