container_unix.go 14 KB

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