container_unix.go 14 KB

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