container_unix.go 14 KB

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