container_unix.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  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. // 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 ioutil.WriteFile(container.HostnamePath, []byte(container.Config.Hostname+"\n"), 0644)
  56. }
  57. // NetworkMounts returns the list of network mounts.
  58. func (container *Container) NetworkMounts() []Mount {
  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. logrus.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. logrus.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. logrus.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. logrus.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. networkMounts := container.NetworkMounts()
  332. mountPaths := make([]string, 0, len(container.MountPoints)+len(networkMounts))
  333. for _, mntPoint := range container.MountPoints {
  334. dest, err := container.GetResourcePath(mntPoint.Destination)
  335. if err != nil {
  336. logrus.Warnf("Failed to get volume destination path for container '%s' at '%s' while lazily unmounting: %v", container.ID, mntPoint.Destination, err)
  337. continue
  338. }
  339. mountPaths = append(mountPaths, dest)
  340. }
  341. for _, m := range networkMounts {
  342. dest, err := container.GetResourcePath(m.Destination)
  343. if err != nil {
  344. logrus.Warnf("Failed to get volume destination path for container '%s' at '%s' while lazily unmounting: %v", container.ID, m.Destination, err)
  345. continue
  346. }
  347. mountPaths = append(mountPaths, dest)
  348. }
  349. for _, mountPath := range mountPaths {
  350. if err := mount.Unmount(mountPath); err != nil {
  351. logrus.WithError(err).WithField("container", container.ID).
  352. Warn("Unable to unmount")
  353. }
  354. }
  355. return container.UnmountVolumes(volumeEventLog)
  356. }
  357. // ignoreUnsupportedXAttrs ignores errors when extended attributes
  358. // are not supported
  359. func ignoreUnsupportedXAttrs() fs.CopyDirOpt {
  360. xeh := func(dst, src, xattrKey string, err error) error {
  361. if !errors.Is(err, syscall.ENOTSUP) {
  362. return err
  363. }
  364. return nil
  365. }
  366. return fs.WithXAttrErrorHandler(xeh)
  367. }
  368. // copyExistingContents copies from the source to the destination and
  369. // ensures the ownership is appropriately set.
  370. func copyExistingContents(source, destination string) error {
  371. dstList, err := ioutil.ReadDir(destination)
  372. if err != nil {
  373. return err
  374. }
  375. if len(dstList) != 0 {
  376. // destination is not empty, do not copy
  377. return nil
  378. }
  379. return fs.CopyDir(destination, source, ignoreUnsupportedXAttrs())
  380. }
  381. // TmpfsMounts returns the list of tmpfs mounts
  382. func (container *Container) TmpfsMounts() ([]Mount, error) {
  383. var mounts []Mount
  384. for dest, data := range container.HostConfig.Tmpfs {
  385. mounts = append(mounts, Mount{
  386. Source: "tmpfs",
  387. Destination: dest,
  388. Data: data,
  389. })
  390. }
  391. parser := volumemounts.NewParser()
  392. for dest, mnt := range container.MountPoints {
  393. if mnt.Type == mounttypes.TypeTmpfs {
  394. data, err := parser.ConvertTmpfsOptions(mnt.Spec.TmpfsOptions, mnt.Spec.ReadOnly)
  395. if err != nil {
  396. return nil, err
  397. }
  398. mounts = append(mounts, Mount{
  399. Source: "tmpfs",
  400. Destination: dest,
  401. Data: data,
  402. })
  403. }
  404. }
  405. return mounts, nil
  406. }
  407. // GetMountPoints gives a platform specific transformation to types.MountPoint. Callers must hold a Container lock.
  408. func (container *Container) GetMountPoints() []types.MountPoint {
  409. mountPoints := make([]types.MountPoint, 0, len(container.MountPoints))
  410. for _, m := range container.MountPoints {
  411. mountPoints = append(mountPoints, types.MountPoint{
  412. Type: m.Type,
  413. Name: m.Name,
  414. Source: m.Path(),
  415. Destination: m.Destination,
  416. Driver: m.Driver,
  417. Mode: m.Mode,
  418. RW: m.RW,
  419. Propagation: m.Propagation,
  420. })
  421. }
  422. return mountPoints
  423. }
  424. // ConfigFilePath returns the path to the on-disk location of a config.
  425. // On unix, configs are always considered secret
  426. func (container *Container) ConfigFilePath(configRef swarmtypes.ConfigReference) (string, error) {
  427. mounts, err := container.SecretMountPath()
  428. if err != nil {
  429. return "", err
  430. }
  431. return filepath.Join(mounts, configRef.ConfigID), nil
  432. }