container_unix.go 14 KB

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