container_unix.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. // +build linux freebsd solaris
  2. package container
  3. import (
  4. "io/ioutil"
  5. "os"
  6. "path/filepath"
  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/chrootarchive"
  11. "github.com/docker/docker/pkg/mount"
  12. "github.com/docker/docker/pkg/stringid"
  13. "github.com/docker/docker/pkg/symlink"
  14. "github.com/docker/docker/pkg/system"
  15. "github.com/docker/docker/volume"
  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. containerSecretMountPath = "/run/secrets"
  23. )
  24. // ExitStatus provides exit reasons for a container.
  25. type ExitStatus struct {
  26. // The exit code with which the container exited.
  27. ExitCode int
  28. // Whether the container encountered an OOM.
  29. OOMKilled bool
  30. }
  31. // TrySetNetworkMount attempts to set the network mounts given a provided destination and
  32. // the path to use for it; return true if the given destination was a network mount file
  33. func (container *Container) TrySetNetworkMount(destination string, path string) bool {
  34. if destination == "/etc/resolv.conf" {
  35. container.ResolvConfPath = path
  36. return true
  37. }
  38. if destination == "/etc/hostname" {
  39. container.HostnamePath = path
  40. return true
  41. }
  42. if destination == "/etc/hosts" {
  43. container.HostsPath = path
  44. return true
  45. }
  46. return false
  47. }
  48. // BuildHostnameFile writes the container's hostname file.
  49. func (container *Container) BuildHostnameFile() error {
  50. hostnamePath, err := container.GetRootResourcePath("hostname")
  51. if err != nil {
  52. return err
  53. }
  54. container.HostnamePath = hostnamePath
  55. return ioutil.WriteFile(container.HostnamePath, []byte(container.Config.Hostname+"\n"), 0644)
  56. }
  57. // NetworkMounts returns the list of network mounts.
  58. func (container *Container) NetworkMounts() []Mount {
  59. var mounts []Mount
  60. shared := container.HostConfig.NetworkMode.IsContainer()
  61. parser := volume.NewParser(container.Platform)
  62. if container.ResolvConfPath != "" {
  63. if _, err := os.Stat(container.ResolvConfPath); err != nil {
  64. logrus.Warnf("ResolvConfPath set to %q, but can't stat this filename (err = %v); skipping", container.ResolvConfPath, err)
  65. } else {
  66. if !container.HasMountFor("/etc/resolv.conf") {
  67. label.Relabel(container.ResolvConfPath, container.MountLabel, shared)
  68. }
  69. writable := !container.HostConfig.ReadonlyRootfs
  70. if m, exists := container.MountPoints["/etc/resolv.conf"]; exists {
  71. writable = m.RW
  72. }
  73. mounts = append(mounts, Mount{
  74. Source: container.ResolvConfPath,
  75. Destination: "/etc/resolv.conf",
  76. Writable: writable,
  77. Propagation: string(parser.DefaultPropagationMode()),
  78. })
  79. }
  80. }
  81. if container.HostnamePath != "" {
  82. if _, err := os.Stat(container.HostnamePath); err != nil {
  83. logrus.Warnf("HostnamePath set to %q, but can't stat this filename (err = %v); skipping", container.HostnamePath, err)
  84. } else {
  85. if !container.HasMountFor("/etc/hostname") {
  86. label.Relabel(container.HostnamePath, container.MountLabel, shared)
  87. }
  88. writable := !container.HostConfig.ReadonlyRootfs
  89. if m, exists := container.MountPoints["/etc/hostname"]; exists {
  90. writable = m.RW
  91. }
  92. mounts = append(mounts, Mount{
  93. Source: container.HostnamePath,
  94. Destination: "/etc/hostname",
  95. Writable: writable,
  96. Propagation: string(parser.DefaultPropagationMode()),
  97. })
  98. }
  99. }
  100. if container.HostsPath != "" {
  101. if _, err := os.Stat(container.HostsPath); err != nil {
  102. logrus.Warnf("HostsPath set to %q, but can't stat this filename (err = %v); skipping", container.HostsPath, err)
  103. } else {
  104. if !container.HasMountFor("/etc/hosts") {
  105. label.Relabel(container.HostsPath, container.MountLabel, shared)
  106. }
  107. writable := !container.HostConfig.ReadonlyRootfs
  108. if m, exists := container.MountPoints["/etc/hosts"]; exists {
  109. writable = m.RW
  110. }
  111. mounts = append(mounts, Mount{
  112. Source: container.HostsPath,
  113. Destination: "/etc/hosts",
  114. Writable: writable,
  115. Propagation: string(parser.DefaultPropagationMode()),
  116. })
  117. }
  118. }
  119. return mounts
  120. }
  121. // CopyImagePathContent copies files in destination to the volume.
  122. func (container *Container) CopyImagePathContent(v volume.Volume, destination string) error {
  123. rootfs, err := symlink.FollowSymlinkInScope(filepath.Join(container.BaseFS, destination), container.BaseFS)
  124. if err != nil {
  125. return err
  126. }
  127. if _, err = ioutil.ReadDir(rootfs); err != nil {
  128. if os.IsNotExist(err) {
  129. return nil
  130. }
  131. return err
  132. }
  133. id := stringid.GenerateNonCryptoID()
  134. path, err := v.Mount(id)
  135. if err != nil {
  136. return err
  137. }
  138. defer func() {
  139. if err := v.Unmount(id); err != nil {
  140. logrus.Warnf("error while unmounting volume %s: %v", v.Name(), err)
  141. }
  142. }()
  143. if err := label.Relabel(path, container.MountLabel, true); err != nil && err != unix.ENOTSUP {
  144. return err
  145. }
  146. return copyExistingContents(rootfs, path)
  147. }
  148. // ShmResourcePath returns path to shm
  149. func (container *Container) ShmResourcePath() (string, error) {
  150. return container.GetRootResourcePath("shm")
  151. }
  152. // HasMountFor checks if path is a mountpoint
  153. func (container *Container) HasMountFor(path string) bool {
  154. _, exists := container.MountPoints[path]
  155. return exists
  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.Platform)
  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 {
  199. var mounts []Mount
  200. for _, r := range container.SecretReferences {
  201. if r.File == nil {
  202. continue
  203. }
  204. mounts = append(mounts, Mount{
  205. Source: container.SecretFilePath(*r),
  206. Destination: getSecretTargetPath(r),
  207. Writable: false,
  208. })
  209. }
  210. return mounts
  211. }
  212. // UnmountSecrets unmounts the local tmpfs for secrets
  213. func (container *Container) UnmountSecrets() error {
  214. if _, err := os.Stat(container.SecretMountPath()); err != nil {
  215. if os.IsNotExist(err) {
  216. return nil
  217. }
  218. return err
  219. }
  220. return detachMounted(container.SecretMountPath())
  221. }
  222. // ConfigMounts returns the mounts for configs.
  223. func (container *Container) ConfigMounts() []Mount {
  224. var mounts []Mount
  225. for _, configRef := range container.ConfigReferences {
  226. if configRef.File == nil {
  227. continue
  228. }
  229. mounts = append(mounts, Mount{
  230. Source: container.ConfigFilePath(*configRef),
  231. Destination: configRef.File.Name,
  232. Writable: false,
  233. })
  234. }
  235. return mounts
  236. }
  237. type conflictingUpdateOptions string
  238. func (e conflictingUpdateOptions) Error() string {
  239. return string(e)
  240. }
  241. func (e conflictingUpdateOptions) Conflict() {}
  242. // UpdateContainer updates configuration of a container. Callers must hold a Lock on the Container.
  243. func (container *Container) UpdateContainer(hostConfig *containertypes.HostConfig) error {
  244. // update resources of container
  245. resources := hostConfig.Resources
  246. cResources := &container.HostConfig.Resources
  247. // validate NanoCPUs, CPUPeriod, and CPUQuota
  248. // Because NanoCPU effectively updates CPUPeriod/CPUQuota,
  249. // once NanoCPU is already set, updating CPUPeriod/CPUQuota will be blocked, and vice versa.
  250. // In the following we make sure the intended update (resources) does not conflict with the existing (cResource).
  251. if resources.NanoCPUs > 0 && cResources.CPUPeriod > 0 {
  252. return conflictingUpdateOptions("Conflicting options: Nano CPUs cannot be updated as CPU Period has already been set")
  253. }
  254. if resources.NanoCPUs > 0 && cResources.CPUQuota > 0 {
  255. return conflictingUpdateOptions("Conflicting options: Nano CPUs cannot be updated as CPU Quota has already been set")
  256. }
  257. if resources.CPUPeriod > 0 && cResources.NanoCPUs > 0 {
  258. return conflictingUpdateOptions("Conflicting options: CPU Period cannot be updated as NanoCPUs has already been set")
  259. }
  260. if resources.CPUQuota > 0 && cResources.NanoCPUs > 0 {
  261. return conflictingUpdateOptions("Conflicting options: CPU Quota cannot be updated as NanoCPUs has already been set")
  262. }
  263. if resources.BlkioWeight != 0 {
  264. cResources.BlkioWeight = resources.BlkioWeight
  265. }
  266. if resources.CPUShares != 0 {
  267. cResources.CPUShares = resources.CPUShares
  268. }
  269. if resources.NanoCPUs != 0 {
  270. cResources.NanoCPUs = resources.NanoCPUs
  271. }
  272. if resources.CPUPeriod != 0 {
  273. cResources.CPUPeriod = resources.CPUPeriod
  274. }
  275. if resources.CPUQuota != 0 {
  276. cResources.CPUQuota = resources.CPUQuota
  277. }
  278. if resources.CpusetCpus != "" {
  279. cResources.CpusetCpus = resources.CpusetCpus
  280. }
  281. if resources.CpusetMems != "" {
  282. cResources.CpusetMems = resources.CpusetMems
  283. }
  284. if resources.Memory != 0 {
  285. // if memory limit smaller than already set memoryswap limit and doesn't
  286. // update the memoryswap limit, then error out.
  287. if resources.Memory > cResources.MemorySwap && resources.MemorySwap == 0 {
  288. return conflictingUpdateOptions("Memory limit should be smaller than already set memoryswap limit, update the memoryswap at the same time")
  289. }
  290. cResources.Memory = resources.Memory
  291. }
  292. if resources.MemorySwap != 0 {
  293. cResources.MemorySwap = resources.MemorySwap
  294. }
  295. if resources.MemoryReservation != 0 {
  296. cResources.MemoryReservation = resources.MemoryReservation
  297. }
  298. if resources.KernelMemory != 0 {
  299. cResources.KernelMemory = resources.KernelMemory
  300. }
  301. // update HostConfig of container
  302. if hostConfig.RestartPolicy.Name != "" {
  303. if container.HostConfig.AutoRemove && !hostConfig.RestartPolicy.IsNone() {
  304. return conflictingUpdateOptions("Restart policy cannot be updated because AutoRemove is enabled for the container")
  305. }
  306. container.HostConfig.RestartPolicy = hostConfig.RestartPolicy
  307. }
  308. return nil
  309. }
  310. // DetachAndUnmount uses a detached mount on all mount destinations, then
  311. // unmounts each volume normally.
  312. // This is used from daemon/archive for `docker cp`
  313. func (container *Container) DetachAndUnmount(volumeEventLog func(name, action string, attributes map[string]string)) error {
  314. networkMounts := container.NetworkMounts()
  315. mountPaths := make([]string, 0, len(container.MountPoints)+len(networkMounts))
  316. for _, mntPoint := range container.MountPoints {
  317. dest, err := container.GetResourcePath(mntPoint.Destination)
  318. if err != nil {
  319. logrus.Warnf("Failed to get volume destination path for container '%s' at '%s' while lazily unmounting: %v", container.ID, mntPoint.Destination, err)
  320. continue
  321. }
  322. mountPaths = append(mountPaths, dest)
  323. }
  324. for _, m := range networkMounts {
  325. dest, err := container.GetResourcePath(m.Destination)
  326. if err != nil {
  327. logrus.Warnf("Failed to get volume destination path for container '%s' at '%s' while lazily unmounting: %v", container.ID, m.Destination, err)
  328. continue
  329. }
  330. mountPaths = append(mountPaths, dest)
  331. }
  332. for _, mountPath := range mountPaths {
  333. if err := detachMounted(mountPath); err != nil {
  334. logrus.Warnf("%s unmountVolumes: Failed to do lazy umount fo volume '%s': %v", container.ID, mountPath, err)
  335. }
  336. }
  337. return container.UnmountVolumes(volumeEventLog)
  338. }
  339. // copyExistingContents copies from the source to the destination and
  340. // ensures the ownership is appropriately set.
  341. func copyExistingContents(source, destination string) error {
  342. volList, err := ioutil.ReadDir(source)
  343. if err != nil {
  344. return err
  345. }
  346. if len(volList) > 0 {
  347. srcList, err := ioutil.ReadDir(destination)
  348. if err != nil {
  349. return err
  350. }
  351. if len(srcList) == 0 {
  352. // If the source volume is empty, copies files from the root into the volume
  353. if err := chrootarchive.NewArchiver(nil).CopyWithTar(source, destination); err != nil {
  354. return err
  355. }
  356. }
  357. }
  358. return copyOwnership(source, destination)
  359. }
  360. // copyOwnership copies the permissions and uid:gid of the source file
  361. // to the destination file
  362. func copyOwnership(source, destination string) error {
  363. stat, err := system.Stat(source)
  364. if err != nil {
  365. return err
  366. }
  367. destStat, err := system.Stat(destination)
  368. if err != nil {
  369. return err
  370. }
  371. // In some cases, even though UID/GID match and it would effectively be a no-op,
  372. // this can return a permission denied error... for example if this is an NFS
  373. // mount.
  374. // Since it's not really an error that we can't chown to the same UID/GID, don't
  375. // even bother trying in such cases.
  376. if stat.UID() != destStat.UID() || stat.GID() != destStat.GID() {
  377. if err := os.Chown(destination, int(stat.UID()), int(stat.GID())); err != nil {
  378. return err
  379. }
  380. }
  381. if stat.Mode() != destStat.Mode() {
  382. return os.Chmod(destination, os.FileMode(stat.Mode()))
  383. }
  384. return nil
  385. }
  386. // TmpfsMounts returns the list of tmpfs mounts
  387. func (container *Container) TmpfsMounts() ([]Mount, error) {
  388. parser := volume.NewParser(container.Platform)
  389. var mounts []Mount
  390. for dest, data := range container.HostConfig.Tmpfs {
  391. mounts = append(mounts, Mount{
  392. Source: "tmpfs",
  393. Destination: dest,
  394. Data: data,
  395. })
  396. }
  397. for dest, mnt := range container.MountPoints {
  398. if mnt.Type == mounttypes.TypeTmpfs {
  399. data, err := parser.ConvertTmpfsOptions(mnt.Spec.TmpfsOptions, mnt.Spec.ReadOnly)
  400. if err != nil {
  401. return nil, err
  402. }
  403. mounts = append(mounts, Mount{
  404. Source: "tmpfs",
  405. Destination: dest,
  406. Data: data,
  407. })
  408. }
  409. }
  410. return mounts, nil
  411. }
  412. // cleanResourcePath cleans a resource path and prepares to combine with mnt path
  413. func cleanResourcePath(path string) string {
  414. return filepath.Join(string(os.PathSeparator), path)
  415. }
  416. // EnableServiceDiscoveryOnDefaultNetwork Enable service discovery on default network
  417. func (container *Container) EnableServiceDiscoveryOnDefaultNetwork() bool {
  418. return false
  419. }
  420. // GetMountPoints gives a platform specific transformation to types.MountPoint. Callers must hold a Container lock.
  421. func (container *Container) GetMountPoints() []types.MountPoint {
  422. mountPoints := make([]types.MountPoint, 0, len(container.MountPoints))
  423. for _, m := range container.MountPoints {
  424. mountPoints = append(mountPoints, types.MountPoint{
  425. Type: m.Type,
  426. Name: m.Name,
  427. Source: m.Path(),
  428. Destination: m.Destination,
  429. Driver: m.Driver,
  430. Mode: m.Mode,
  431. RW: m.RW,
  432. Propagation: m.Propagation,
  433. })
  434. }
  435. return mountPoints
  436. }