container_unix.go 14 KB

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