container_unix.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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.MountsResourcePath("shm")
  141. }
  142. // HasMountFor checks if path is a mountpoint
  143. func (container *Container) HasMountFor(path string) bool {
  144. _, exists := container.MountPoints[path]
  145. if exists {
  146. return true
  147. }
  148. // Also search among the tmpfs mounts
  149. for dest := range container.HostConfig.Tmpfs {
  150. if dest == path {
  151. return true
  152. }
  153. }
  154. return false
  155. }
  156. // UnmountIpcMount uses the provided unmount function to unmount shm if it was mounted
  157. func (container *Container) UnmountIpcMount(unmount func(pth string) error) error {
  158. if container.HasMountFor("/dev/shm") {
  159. return nil
  160. }
  161. // container.ShmPath should not be used here as it may point
  162. // to the host's or other container's /dev/shm
  163. shmPath, err := container.ShmResourcePath()
  164. if err != nil {
  165. return err
  166. }
  167. if shmPath == "" {
  168. return nil
  169. }
  170. if err = unmount(shmPath); err != nil && !os.IsNotExist(err) {
  171. if mounted, mErr := mount.Mounted(shmPath); mounted || mErr != nil {
  172. return errors.Wrapf(err, "umount %s", shmPath)
  173. }
  174. }
  175. return nil
  176. }
  177. // IpcMounts returns the list of IPC mounts
  178. func (container *Container) IpcMounts() []Mount {
  179. var mounts []Mount
  180. parser := volume.NewParser(container.OS)
  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(parser.DefaultPropagationMode()),
  193. })
  194. return mounts
  195. }
  196. // SecretMounts returns the mounts for the secret path.
  197. func (container *Container) SecretMounts() ([]Mount, error) {
  198. var mounts []Mount
  199. for _, r := range container.SecretReferences {
  200. if r.File == nil {
  201. continue
  202. }
  203. src, err := container.SecretFilePath(*r)
  204. if err != nil {
  205. return nil, err
  206. }
  207. mounts = append(mounts, Mount{
  208. Source: src,
  209. Destination: getSecretTargetPath(r),
  210. Writable: false,
  211. })
  212. }
  213. return mounts, nil
  214. }
  215. // UnmountSecrets unmounts the local tmpfs for secrets
  216. func (container *Container) UnmountSecrets() error {
  217. p, err := container.SecretMountPath()
  218. if err != nil {
  219. return err
  220. }
  221. if _, err := os.Stat(p); err != nil {
  222. if os.IsNotExist(err) {
  223. return nil
  224. }
  225. return err
  226. }
  227. return mount.RecursiveUnmount(p)
  228. }
  229. // ConfigMounts returns the mounts for configs.
  230. func (container *Container) ConfigMounts() ([]Mount, error) {
  231. var mounts []Mount
  232. for _, configRef := range container.ConfigReferences {
  233. if configRef.File == nil {
  234. continue
  235. }
  236. src, err := container.ConfigFilePath(*configRef)
  237. if err != nil {
  238. return nil, err
  239. }
  240. mounts = append(mounts, Mount{
  241. Source: src,
  242. Destination: configRef.File.Name,
  243. Writable: false,
  244. })
  245. }
  246. return mounts, nil
  247. }
  248. type conflictingUpdateOptions string
  249. func (e conflictingUpdateOptions) Error() string {
  250. return string(e)
  251. }
  252. func (e conflictingUpdateOptions) Conflict() {}
  253. // UpdateContainer updates configuration of a container. Callers must hold a Lock on the Container.
  254. func (container *Container) UpdateContainer(hostConfig *containertypes.HostConfig) error {
  255. // update resources of container
  256. resources := hostConfig.Resources
  257. cResources := &container.HostConfig.Resources
  258. // validate NanoCPUs, CPUPeriod, and CPUQuota
  259. // Because NanoCPU effectively updates CPUPeriod/CPUQuota,
  260. // once NanoCPU is already set, updating CPUPeriod/CPUQuota will be blocked, and vice versa.
  261. // In the following we make sure the intended update (resources) does not conflict with the existing (cResource).
  262. if resources.NanoCPUs > 0 && cResources.CPUPeriod > 0 {
  263. return conflictingUpdateOptions("Conflicting options: Nano CPUs cannot be updated as CPU Period has already been set")
  264. }
  265. if resources.NanoCPUs > 0 && cResources.CPUQuota > 0 {
  266. return conflictingUpdateOptions("Conflicting options: Nano CPUs cannot be updated as CPU Quota has already been set")
  267. }
  268. if resources.CPUPeriod > 0 && cResources.NanoCPUs > 0 {
  269. return conflictingUpdateOptions("Conflicting options: CPU Period cannot be updated as NanoCPUs has already been set")
  270. }
  271. if resources.CPUQuota > 0 && cResources.NanoCPUs > 0 {
  272. return conflictingUpdateOptions("Conflicting options: CPU Quota cannot be updated as NanoCPUs has already been set")
  273. }
  274. if resources.BlkioWeight != 0 {
  275. cResources.BlkioWeight = resources.BlkioWeight
  276. }
  277. if resources.CPUShares != 0 {
  278. cResources.CPUShares = resources.CPUShares
  279. }
  280. if resources.NanoCPUs != 0 {
  281. cResources.NanoCPUs = resources.NanoCPUs
  282. }
  283. if resources.CPUPeriod != 0 {
  284. cResources.CPUPeriod = resources.CPUPeriod
  285. }
  286. if resources.CPUQuota != 0 {
  287. cResources.CPUQuota = resources.CPUQuota
  288. }
  289. if resources.CpusetCpus != "" {
  290. cResources.CpusetCpus = resources.CpusetCpus
  291. }
  292. if resources.CpusetMems != "" {
  293. cResources.CpusetMems = resources.CpusetMems
  294. }
  295. if resources.Memory != 0 {
  296. // if memory limit smaller than already set memoryswap limit and doesn't
  297. // update the memoryswap limit, then error out.
  298. if resources.Memory > cResources.MemorySwap && resources.MemorySwap == 0 {
  299. return conflictingUpdateOptions("Memory limit should be smaller than already set memoryswap limit, update the memoryswap at the same time")
  300. }
  301. cResources.Memory = resources.Memory
  302. }
  303. if resources.MemorySwap != 0 {
  304. cResources.MemorySwap = resources.MemorySwap
  305. }
  306. if resources.MemoryReservation != 0 {
  307. cResources.MemoryReservation = resources.MemoryReservation
  308. }
  309. if resources.KernelMemory != 0 {
  310. cResources.KernelMemory = resources.KernelMemory
  311. }
  312. if resources.CPURealtimePeriod != 0 {
  313. cResources.CPURealtimePeriod = resources.CPURealtimePeriod
  314. }
  315. if resources.CPURealtimeRuntime != 0 {
  316. cResources.CPURealtimeRuntime = resources.CPURealtimeRuntime
  317. }
  318. // update HostConfig of container
  319. if hostConfig.RestartPolicy.Name != "" {
  320. if container.HostConfig.AutoRemove && !hostConfig.RestartPolicy.IsNone() {
  321. return conflictingUpdateOptions("Restart policy cannot be updated because AutoRemove is enabled for the container")
  322. }
  323. container.HostConfig.RestartPolicy = hostConfig.RestartPolicy
  324. }
  325. return nil
  326. }
  327. // DetachAndUnmount uses a detached mount on all mount destinations, then
  328. // unmounts each volume normally.
  329. // This is used from daemon/archive for `docker cp`
  330. func (container *Container) DetachAndUnmount(volumeEventLog func(name, action string, attributes map[string]string)) error {
  331. networkMounts := container.NetworkMounts()
  332. mountPaths := make([]string, 0, len(container.MountPoints)+len(networkMounts))
  333. for _, mntPoint := range container.MountPoints {
  334. dest, err := container.GetResourcePath(mntPoint.Destination)
  335. if err != nil {
  336. logrus.Warnf("Failed to get volume destination path for container '%s' at '%s' while lazily unmounting: %v", container.ID, mntPoint.Destination, err)
  337. continue
  338. }
  339. mountPaths = append(mountPaths, dest)
  340. }
  341. for _, m := range networkMounts {
  342. dest, err := container.GetResourcePath(m.Destination)
  343. if err != nil {
  344. logrus.Warnf("Failed to get volume destination path for container '%s' at '%s' while lazily unmounting: %v", container.ID, m.Destination, err)
  345. continue
  346. }
  347. mountPaths = append(mountPaths, dest)
  348. }
  349. for _, mountPath := range mountPaths {
  350. if err := detachMounted(mountPath); err != nil {
  351. logrus.Warnf("%s unmountVolumes: Failed to do lazy umount fo volume '%s': %v", container.ID, mountPath, err)
  352. }
  353. }
  354. return container.UnmountVolumes(volumeEventLog)
  355. }
  356. // copyExistingContents copies from the source to the destination and
  357. // ensures the ownership is appropriately set.
  358. func copyExistingContents(source, destination string) error {
  359. volList, err := ioutil.ReadDir(source)
  360. if err != nil {
  361. return err
  362. }
  363. if len(volList) > 0 {
  364. srcList, err := ioutil.ReadDir(destination)
  365. if err != nil {
  366. return err
  367. }
  368. if len(srcList) == 0 {
  369. // If the source volume is empty, copies files from the root into the volume
  370. if err := chrootarchive.NewArchiver(nil).CopyWithTar(source, destination); err != nil {
  371. return err
  372. }
  373. }
  374. }
  375. return copyOwnership(source, destination)
  376. }
  377. // copyOwnership copies the permissions and uid:gid of the source file
  378. // to the destination file
  379. func copyOwnership(source, destination string) error {
  380. stat, err := system.Stat(source)
  381. if err != nil {
  382. return err
  383. }
  384. destStat, err := system.Stat(destination)
  385. if err != nil {
  386. return err
  387. }
  388. // In some cases, even though UID/GID match and it would effectively be a no-op,
  389. // this can return a permission denied error... for example if this is an NFS
  390. // mount.
  391. // Since it's not really an error that we can't chown to the same UID/GID, don't
  392. // even bother trying in such cases.
  393. if stat.UID() != destStat.UID() || stat.GID() != destStat.GID() {
  394. if err := os.Chown(destination, int(stat.UID()), int(stat.GID())); err != nil {
  395. return err
  396. }
  397. }
  398. if stat.Mode() != destStat.Mode() {
  399. return os.Chmod(destination, os.FileMode(stat.Mode()))
  400. }
  401. return nil
  402. }
  403. // TmpfsMounts returns the list of tmpfs mounts
  404. func (container *Container) TmpfsMounts() ([]Mount, error) {
  405. parser := volume.NewParser(container.OS)
  406. var mounts []Mount
  407. for dest, data := range container.HostConfig.Tmpfs {
  408. mounts = append(mounts, Mount{
  409. Source: "tmpfs",
  410. Destination: dest,
  411. Data: data,
  412. })
  413. }
  414. for dest, mnt := range container.MountPoints {
  415. if mnt.Type == mounttypes.TypeTmpfs {
  416. data, err := parser.ConvertTmpfsOptions(mnt.Spec.TmpfsOptions, mnt.Spec.ReadOnly)
  417. if err != nil {
  418. return nil, err
  419. }
  420. mounts = append(mounts, Mount{
  421. Source: "tmpfs",
  422. Destination: dest,
  423. Data: data,
  424. })
  425. }
  426. }
  427. return mounts, nil
  428. }
  429. // EnableServiceDiscoveryOnDefaultNetwork Enable service discovery on default network
  430. func (container *Container) EnableServiceDiscoveryOnDefaultNetwork() bool {
  431. return false
  432. }
  433. // GetMountPoints gives a platform specific transformation to types.MountPoint. Callers must hold a Container lock.
  434. func (container *Container) GetMountPoints() []types.MountPoint {
  435. mountPoints := make([]types.MountPoint, 0, len(container.MountPoints))
  436. for _, m := range container.MountPoints {
  437. mountPoints = append(mountPoints, types.MountPoint{
  438. Type: m.Type,
  439. Name: m.Name,
  440. Source: m.Path(),
  441. Destination: m.Destination,
  442. Driver: m.Driver,
  443. Mode: m.Mode,
  444. RW: m.RW,
  445. Propagation: m.Propagation,
  446. })
  447. }
  448. return mountPoints
  449. }