container_unix.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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/mount"
  14. "github.com/docker/docker/pkg/stringid"
  15. "github.com/docker/docker/volume"
  16. volumemounts "github.com/docker/docker/volume/mounts"
  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.GenerateNonCryptoID()
  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 uses the provided unmount function to unmount shm if it was mounted
  161. func (container *Container) UnmountIpcMount(unmount func(pth string) error) 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 = unmount(shmPath); err != nil && !os.IsNotExist(err) {
  175. if mounted, mErr := mount.Mounted(shmPath); mounted || mErr != nil {
  176. return errors.Wrapf(err, "umount %s", shmPath)
  177. }
  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(container.OS)
  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: r.File.Name,
  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. // update HostConfig of container
  315. if hostConfig.RestartPolicy.Name != "" {
  316. if container.HostConfig.AutoRemove && !hostConfig.RestartPolicy.IsNone() {
  317. return conflictingUpdateOptions("Restart policy cannot be updated because AutoRemove is enabled for the container")
  318. }
  319. container.HostConfig.RestartPolicy = hostConfig.RestartPolicy
  320. }
  321. return nil
  322. }
  323. // DetachAndUnmount uses a detached mount on all mount destinations, then
  324. // unmounts each volume normally.
  325. // This is used from daemon/archive for `docker cp`
  326. func (container *Container) DetachAndUnmount(volumeEventLog func(name, action string, attributes map[string]string)) error {
  327. networkMounts := container.NetworkMounts()
  328. mountPaths := make([]string, 0, len(container.MountPoints)+len(networkMounts))
  329. for _, mntPoint := range container.MountPoints {
  330. dest, err := container.GetResourcePath(mntPoint.Destination)
  331. if err != nil {
  332. logrus.Warnf("Failed to get volume destination path for container '%s' at '%s' while lazily unmounting: %v", container.ID, mntPoint.Destination, err)
  333. continue
  334. }
  335. mountPaths = append(mountPaths, dest)
  336. }
  337. for _, m := range networkMounts {
  338. dest, err := container.GetResourcePath(m.Destination)
  339. if err != nil {
  340. logrus.Warnf("Failed to get volume destination path for container '%s' at '%s' while lazily unmounting: %v", container.ID, m.Destination, err)
  341. continue
  342. }
  343. mountPaths = append(mountPaths, dest)
  344. }
  345. for _, mountPath := range mountPaths {
  346. if err := mount.Unmount(mountPath); err != nil {
  347. logrus.Warnf("%s unmountVolumes: Failed to do lazy umount fo volume '%s': %v", container.ID, mountPath, err)
  348. }
  349. }
  350. return container.UnmountVolumes(volumeEventLog)
  351. }
  352. // ignoreUnsupportedXAttrs ignores errors when extended attributes
  353. // are not supported
  354. func ignoreUnsupportedXAttrs() fs.CopyDirOpt {
  355. xeh := func(dst, src, xattrKey string, err error) error {
  356. if errors.Cause(err) != syscall.ENOTSUP {
  357. return err
  358. }
  359. return nil
  360. }
  361. return fs.WithXAttrErrorHandler(xeh)
  362. }
  363. // copyExistingContents copies from the source to the destination and
  364. // ensures the ownership is appropriately set.
  365. func copyExistingContents(source, destination string) error {
  366. dstList, err := ioutil.ReadDir(destination)
  367. if err != nil {
  368. return err
  369. }
  370. if len(dstList) != 0 {
  371. // destination is not empty, do not copy
  372. return nil
  373. }
  374. return fs.CopyDir(destination, source, ignoreUnsupportedXAttrs())
  375. }
  376. // TmpfsMounts returns the list of tmpfs mounts
  377. func (container *Container) TmpfsMounts() ([]Mount, error) {
  378. parser := volumemounts.NewParser(container.OS)
  379. var mounts []Mount
  380. for dest, data := range container.HostConfig.Tmpfs {
  381. mounts = append(mounts, Mount{
  382. Source: "tmpfs",
  383. Destination: dest,
  384. Data: data,
  385. })
  386. }
  387. for dest, mnt := range container.MountPoints {
  388. if mnt.Type == mounttypes.TypeTmpfs {
  389. data, err := parser.ConvertTmpfsOptions(mnt.Spec.TmpfsOptions, mnt.Spec.ReadOnly)
  390. if err != nil {
  391. return nil, err
  392. }
  393. mounts = append(mounts, Mount{
  394. Source: "tmpfs",
  395. Destination: dest,
  396. Data: data,
  397. })
  398. }
  399. }
  400. return mounts, nil
  401. }
  402. // EnableServiceDiscoveryOnDefaultNetwork Enable service discovery on default network
  403. func (container *Container) EnableServiceDiscoveryOnDefaultNetwork() bool {
  404. return false
  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. }