container_unix.go 14 KB

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