container_unix.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. // +build !windows
  2. package container // import "github.com/docker/docker/container"
  3. import (
  4. "io/ioutil"
  5. "os"
  6. "path/filepath"
  7. "github.com/containerd/continuity/fs"
  8. "github.com/docker/docker/api/types"
  9. containertypes "github.com/docker/docker/api/types/container"
  10. mounttypes "github.com/docker/docker/api/types/mount"
  11. swarmtypes "github.com/docker/docker/api/types/swarm"
  12. "github.com/docker/docker/pkg/mount"
  13. "github.com/docker/docker/pkg/stringid"
  14. "github.com/docker/docker/volume"
  15. volumemounts "github.com/docker/docker/volume/mounts"
  16. "github.com/opencontainers/selinux/go-selinux/label"
  17. "github.com/pkg/errors"
  18. "github.com/sirupsen/logrus"
  19. "golang.org/x/sys/unix"
  20. )
  21. const (
  22. // DefaultStopTimeout sets the default time, in seconds, to wait
  23. // for the graceful container stop before forcefully terminating it.
  24. DefaultStopTimeout = 10
  25. containerSecretMountPath = "/run/secrets"
  26. )
  27. // TrySetNetworkMount attempts to set the network mounts given a provided destination and
  28. // the path to use for it; return true if the given destination was a network mount file
  29. func (container *Container) TrySetNetworkMount(destination string, path string) bool {
  30. if destination == "/etc/resolv.conf" {
  31. container.ResolvConfPath = path
  32. return true
  33. }
  34. if destination == "/etc/hostname" {
  35. container.HostnamePath = path
  36. return true
  37. }
  38. if destination == "/etc/hosts" {
  39. container.HostsPath = path
  40. return true
  41. }
  42. return false
  43. }
  44. // BuildHostnameFile writes the container's hostname file.
  45. func (container *Container) BuildHostnameFile() error {
  46. hostnamePath, err := container.GetRootResourcePath("hostname")
  47. if err != nil {
  48. return err
  49. }
  50. container.HostnamePath = hostnamePath
  51. return ioutil.WriteFile(container.HostnamePath, []byte(container.Config.Hostname+"\n"), 0644)
  52. }
  53. // NetworkMounts returns the list of network mounts.
  54. func (container *Container) NetworkMounts() []Mount {
  55. var mounts []Mount
  56. shared := container.HostConfig.NetworkMode.IsContainer()
  57. parser := volumemounts.NewParser(container.OS)
  58. if container.ResolvConfPath != "" {
  59. if _, err := os.Stat(container.ResolvConfPath); err != nil {
  60. logrus.Warnf("ResolvConfPath set to %q, but can't stat this filename (err = %v); skipping", container.ResolvConfPath, err)
  61. } else {
  62. writable := !container.HostConfig.ReadonlyRootfs
  63. if m, exists := container.MountPoints["/etc/resolv.conf"]; exists {
  64. writable = m.RW
  65. } else {
  66. label.Relabel(container.ResolvConfPath, container.MountLabel, shared)
  67. }
  68. mounts = append(mounts, Mount{
  69. Source: container.ResolvConfPath,
  70. Destination: "/etc/resolv.conf",
  71. Writable: writable,
  72. Propagation: string(parser.DefaultPropagationMode()),
  73. })
  74. }
  75. }
  76. if container.HostnamePath != "" {
  77. if _, err := os.Stat(container.HostnamePath); err != nil {
  78. logrus.Warnf("HostnamePath set to %q, but can't stat this filename (err = %v); skipping", container.HostnamePath, err)
  79. } else {
  80. writable := !container.HostConfig.ReadonlyRootfs
  81. if m, exists := container.MountPoints["/etc/hostname"]; exists {
  82. writable = m.RW
  83. } else {
  84. label.Relabel(container.HostnamePath, container.MountLabel, shared)
  85. }
  86. mounts = append(mounts, Mount{
  87. Source: container.HostnamePath,
  88. Destination: "/etc/hostname",
  89. Writable: writable,
  90. Propagation: string(parser.DefaultPropagationMode()),
  91. })
  92. }
  93. }
  94. if container.HostsPath != "" {
  95. if _, err := os.Stat(container.HostsPath); err != nil {
  96. logrus.Warnf("HostsPath set to %q, but can't stat this filename (err = %v); skipping", container.HostsPath, err)
  97. } else {
  98. writable := !container.HostConfig.ReadonlyRootfs
  99. if m, exists := container.MountPoints["/etc/hosts"]; exists {
  100. writable = m.RW
  101. } else {
  102. label.Relabel(container.HostsPath, container.MountLabel, shared)
  103. }
  104. mounts = append(mounts, Mount{
  105. Source: container.HostsPath,
  106. Destination: "/etc/hosts",
  107. Writable: writable,
  108. Propagation: string(parser.DefaultPropagationMode()),
  109. })
  110. }
  111. }
  112. return mounts
  113. }
  114. // CopyImagePathContent copies files in destination to the volume.
  115. func (container *Container) CopyImagePathContent(v volume.Volume, destination string) error {
  116. rootfs, err := container.GetResourcePath(destination)
  117. if err != nil {
  118. return err
  119. }
  120. if _, err := os.Stat(rootfs); err != nil {
  121. if os.IsNotExist(err) {
  122. return nil
  123. }
  124. return err
  125. }
  126. id := stringid.GenerateNonCryptoID()
  127. path, err := v.Mount(id)
  128. if err != nil {
  129. return err
  130. }
  131. defer func() {
  132. if err := v.Unmount(id); err != nil {
  133. logrus.Warnf("error while unmounting volume %s: %v", v.Name(), err)
  134. }
  135. }()
  136. if err := label.Relabel(path, container.MountLabel, true); err != nil && err != unix.ENOTSUP {
  137. return err
  138. }
  139. return copyExistingContents(rootfs, path)
  140. }
  141. // ShmResourcePath returns path to shm
  142. func (container *Container) ShmResourcePath() (string, error) {
  143. return container.MountsResourcePath("shm")
  144. }
  145. // HasMountFor checks if path is a mountpoint
  146. func (container *Container) HasMountFor(path string) bool {
  147. _, exists := container.MountPoints[path]
  148. if exists {
  149. return true
  150. }
  151. // Also search among the tmpfs mounts
  152. for dest := range container.HostConfig.Tmpfs {
  153. if dest == path {
  154. return true
  155. }
  156. }
  157. return false
  158. }
  159. // UnmountIpcMount uses the provided unmount function to unmount shm if it was mounted
  160. func (container *Container) UnmountIpcMount(unmount func(pth string) error) error {
  161. if container.HasMountFor("/dev/shm") {
  162. return nil
  163. }
  164. // container.ShmPath should not be used here as it may point
  165. // to the host's or other container's /dev/shm
  166. shmPath, err := container.ShmResourcePath()
  167. if err != nil {
  168. return err
  169. }
  170. if shmPath == "" {
  171. return nil
  172. }
  173. if err = unmount(shmPath); err != nil && !os.IsNotExist(err) {
  174. if mounted, mErr := mount.Mounted(shmPath); mounted || mErr != nil {
  175. return errors.Wrapf(err, "umount %s", shmPath)
  176. }
  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: r.File.Name,
  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. // update HostConfig of container
  314. if hostConfig.RestartPolicy.Name != "" {
  315. if container.HostConfig.AutoRemove && !hostConfig.RestartPolicy.IsNone() {
  316. return conflictingUpdateOptions("Restart policy cannot be updated because AutoRemove is enabled for the container")
  317. }
  318. container.HostConfig.RestartPolicy = hostConfig.RestartPolicy
  319. }
  320. return nil
  321. }
  322. // DetachAndUnmount uses a detached mount on all mount destinations, then
  323. // unmounts each volume normally.
  324. // This is used from daemon/archive for `docker cp`
  325. func (container *Container) DetachAndUnmount(volumeEventLog func(name, action string, attributes map[string]string)) error {
  326. networkMounts := container.NetworkMounts()
  327. mountPaths := make([]string, 0, len(container.MountPoints)+len(networkMounts))
  328. for _, mntPoint := range container.MountPoints {
  329. dest, err := container.GetResourcePath(mntPoint.Destination)
  330. if err != nil {
  331. logrus.Warnf("Failed to get volume destination path for container '%s' at '%s' while lazily unmounting: %v", container.ID, mntPoint.Destination, err)
  332. continue
  333. }
  334. mountPaths = append(mountPaths, dest)
  335. }
  336. for _, m := range networkMounts {
  337. dest, err := container.GetResourcePath(m.Destination)
  338. if err != nil {
  339. logrus.Warnf("Failed to get volume destination path for container '%s' at '%s' while lazily unmounting: %v", container.ID, m.Destination, err)
  340. continue
  341. }
  342. mountPaths = append(mountPaths, dest)
  343. }
  344. for _, mountPath := range mountPaths {
  345. if err := mount.Unmount(mountPath); err != nil {
  346. logrus.Warnf("%s unmountVolumes: Failed to do lazy umount for volume '%s': %v", container.ID, mountPath, err)
  347. }
  348. }
  349. return container.UnmountVolumes(volumeEventLog)
  350. }
  351. // copyExistingContents copies from the source to the destination and
  352. // ensures the ownership is appropriately set.
  353. func copyExistingContents(source, destination string) error {
  354. dstList, err := ioutil.ReadDir(destination)
  355. if err != nil {
  356. return err
  357. }
  358. if len(dstList) != 0 {
  359. // destination is not empty, do not copy
  360. return nil
  361. }
  362. return fs.CopyDir(destination, source)
  363. }
  364. // TmpfsMounts returns the list of tmpfs mounts
  365. func (container *Container) TmpfsMounts() ([]Mount, error) {
  366. parser := volumemounts.NewParser(container.OS)
  367. var mounts []Mount
  368. for dest, data := range container.HostConfig.Tmpfs {
  369. mounts = append(mounts, Mount{
  370. Source: "tmpfs",
  371. Destination: dest,
  372. Data: data,
  373. })
  374. }
  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. // EnableServiceDiscoveryOnDefaultNetwork Enable service discovery on default network
  391. func (container *Container) EnableServiceDiscoveryOnDefaultNetwork() bool {
  392. return false
  393. }
  394. // GetMountPoints gives a platform specific transformation to types.MountPoint. Callers must hold a Container lock.
  395. func (container *Container) GetMountPoints() []types.MountPoint {
  396. mountPoints := make([]types.MountPoint, 0, len(container.MountPoints))
  397. for _, m := range container.MountPoints {
  398. mountPoints = append(mountPoints, types.MountPoint{
  399. Type: m.Type,
  400. Name: m.Name,
  401. Source: m.Path(),
  402. Destination: m.Destination,
  403. Driver: m.Driver,
  404. Mode: m.Mode,
  405. RW: m.RW,
  406. Propagation: m.Propagation,
  407. })
  408. }
  409. return mountPoints
  410. }
  411. // ConfigFilePath returns the path to the on-disk location of a config.
  412. // On unix, configs are always considered secret
  413. func (container *Container) ConfigFilePath(configRef swarmtypes.ConfigReference) (string, error) {
  414. mounts, err := container.SecretMountPath()
  415. if err != nil {
  416. return "", err
  417. }
  418. return filepath.Join(mounts, configRef.ConfigID), nil
  419. }