container_unix.go 14 KB

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