container_unix.go 14 KB

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