container_unix.go 14 KB

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