container_unix.go 14 KB

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