container_unix.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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. 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 {
  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. type conflictingUpdateOptions string
  237. func (e conflictingUpdateOptions) Error() string {
  238. return string(e)
  239. }
  240. func (e conflictingUpdateOptions) Conflict() {}
  241. // UpdateContainer updates configuration of a container. Callers must hold a Lock on the Container.
  242. func (container *Container) UpdateContainer(hostConfig *containertypes.HostConfig) error {
  243. // update resources of container
  244. resources := hostConfig.Resources
  245. cResources := &container.HostConfig.Resources
  246. // validate NanoCPUs, CPUPeriod, and CPUQuota
  247. // Because NanoCPU effectively updates CPUPeriod/CPUQuota,
  248. // once NanoCPU is already set, updating CPUPeriod/CPUQuota will be blocked, and vice versa.
  249. // In the following we make sure the intended update (resources) does not conflict with the existing (cResource).
  250. if resources.NanoCPUs > 0 && cResources.CPUPeriod > 0 {
  251. return conflictingUpdateOptions("Conflicting options: Nano CPUs cannot be updated as CPU Period has already been set")
  252. }
  253. if resources.NanoCPUs > 0 && cResources.CPUQuota > 0 {
  254. return conflictingUpdateOptions("Conflicting options: Nano CPUs cannot be updated as CPU Quota has already been set")
  255. }
  256. if resources.CPUPeriod > 0 && cResources.NanoCPUs > 0 {
  257. return conflictingUpdateOptions("Conflicting options: CPU Period cannot be updated as NanoCPUs has already been set")
  258. }
  259. if resources.CPUQuota > 0 && cResources.NanoCPUs > 0 {
  260. return conflictingUpdateOptions("Conflicting options: CPU Quota cannot be updated as NanoCPUs has already been set")
  261. }
  262. if resources.BlkioWeight != 0 {
  263. cResources.BlkioWeight = resources.BlkioWeight
  264. }
  265. if resources.CPUShares != 0 {
  266. cResources.CPUShares = resources.CPUShares
  267. }
  268. if resources.NanoCPUs != 0 {
  269. cResources.NanoCPUs = resources.NanoCPUs
  270. }
  271. if resources.CPUPeriod != 0 {
  272. cResources.CPUPeriod = resources.CPUPeriod
  273. }
  274. if resources.CPUQuota != 0 {
  275. cResources.CPUQuota = resources.CPUQuota
  276. }
  277. if resources.CpusetCpus != "" {
  278. cResources.CpusetCpus = resources.CpusetCpus
  279. }
  280. if resources.CpusetMems != "" {
  281. cResources.CpusetMems = resources.CpusetMems
  282. }
  283. if resources.Memory != 0 {
  284. // if memory limit smaller than already set memoryswap limit and doesn't
  285. // update the memoryswap limit, then error out.
  286. if resources.Memory > cResources.MemorySwap && resources.MemorySwap == 0 {
  287. return conflictingUpdateOptions("Memory limit should be smaller than already set memoryswap limit, update the memoryswap at the same time")
  288. }
  289. cResources.Memory = resources.Memory
  290. }
  291. if resources.MemorySwap != 0 {
  292. cResources.MemorySwap = resources.MemorySwap
  293. }
  294. if resources.MemoryReservation != 0 {
  295. cResources.MemoryReservation = resources.MemoryReservation
  296. }
  297. if resources.KernelMemory != 0 {
  298. cResources.KernelMemory = resources.KernelMemory
  299. }
  300. if resources.CPURealtimePeriod != 0 {
  301. cResources.CPURealtimePeriod = resources.CPURealtimePeriod
  302. }
  303. if resources.CPURealtimeRuntime != 0 {
  304. cResources.CPURealtimeRuntime = resources.CPURealtimeRuntime
  305. }
  306. // update HostConfig of container
  307. if hostConfig.RestartPolicy.Name != "" {
  308. if container.HostConfig.AutoRemove && !hostConfig.RestartPolicy.IsNone() {
  309. return conflictingUpdateOptions("Restart policy cannot be updated because AutoRemove is enabled for the container")
  310. }
  311. container.HostConfig.RestartPolicy = hostConfig.RestartPolicy
  312. }
  313. return nil
  314. }
  315. // DetachAndUnmount uses a detached mount on all mount destinations, then
  316. // unmounts each volume normally.
  317. // This is used from daemon/archive for `docker cp`
  318. func (container *Container) DetachAndUnmount(volumeEventLog func(name, action string, attributes map[string]string)) error {
  319. networkMounts := container.NetworkMounts()
  320. mountPaths := make([]string, 0, len(container.MountPoints)+len(networkMounts))
  321. for _, mntPoint := range container.MountPoints {
  322. dest, err := container.GetResourcePath(mntPoint.Destination)
  323. if err != nil {
  324. logrus.Warnf("Failed to get volume destination path for container '%s' at '%s' while lazily unmounting: %v", container.ID, mntPoint.Destination, err)
  325. continue
  326. }
  327. mountPaths = append(mountPaths, dest)
  328. }
  329. for _, m := range networkMounts {
  330. dest, err := container.GetResourcePath(m.Destination)
  331. if err != nil {
  332. logrus.Warnf("Failed to get volume destination path for container '%s' at '%s' while lazily unmounting: %v", container.ID, m.Destination, err)
  333. continue
  334. }
  335. mountPaths = append(mountPaths, dest)
  336. }
  337. for _, mountPath := range mountPaths {
  338. if err := detachMounted(mountPath); err != nil {
  339. logrus.Warnf("%s unmountVolumes: Failed to do lazy umount fo volume '%s': %v", container.ID, mountPath, err)
  340. }
  341. }
  342. return container.UnmountVolumes(volumeEventLog)
  343. }
  344. // copyExistingContents copies from the source to the destination and
  345. // ensures the ownership is appropriately set.
  346. func copyExistingContents(source, destination string) error {
  347. volList, err := ioutil.ReadDir(source)
  348. if err != nil {
  349. return err
  350. }
  351. if len(volList) > 0 {
  352. srcList, err := ioutil.ReadDir(destination)
  353. if err != nil {
  354. return err
  355. }
  356. if len(srcList) == 0 {
  357. // If the source volume is empty, copies files from the root into the volume
  358. if err := chrootarchive.NewArchiver(nil).CopyWithTar(source, destination); err != nil {
  359. return err
  360. }
  361. }
  362. }
  363. return copyOwnership(source, destination)
  364. }
  365. // copyOwnership copies the permissions and uid:gid of the source file
  366. // to the destination file
  367. func copyOwnership(source, destination string) error {
  368. stat, err := system.Stat(source)
  369. if err != nil {
  370. return err
  371. }
  372. destStat, err := system.Stat(destination)
  373. if err != nil {
  374. return err
  375. }
  376. // In some cases, even though UID/GID match and it would effectively be a no-op,
  377. // this can return a permission denied error... for example if this is an NFS
  378. // mount.
  379. // Since it's not really an error that we can't chown to the same UID/GID, don't
  380. // even bother trying in such cases.
  381. if stat.UID() != destStat.UID() || stat.GID() != destStat.GID() {
  382. if err := os.Chown(destination, int(stat.UID()), int(stat.GID())); err != nil {
  383. return err
  384. }
  385. }
  386. if stat.Mode() != destStat.Mode() {
  387. return os.Chmod(destination, os.FileMode(stat.Mode()))
  388. }
  389. return nil
  390. }
  391. // TmpfsMounts returns the list of tmpfs mounts
  392. func (container *Container) TmpfsMounts() ([]Mount, error) {
  393. parser := volume.NewParser(container.OS)
  394. var mounts []Mount
  395. for dest, data := range container.HostConfig.Tmpfs {
  396. mounts = append(mounts, Mount{
  397. Source: "tmpfs",
  398. Destination: dest,
  399. Data: data,
  400. })
  401. }
  402. for dest, mnt := range container.MountPoints {
  403. if mnt.Type == mounttypes.TypeTmpfs {
  404. data, err := parser.ConvertTmpfsOptions(mnt.Spec.TmpfsOptions, mnt.Spec.ReadOnly)
  405. if err != nil {
  406. return nil, err
  407. }
  408. mounts = append(mounts, Mount{
  409. Source: "tmpfs",
  410. Destination: dest,
  411. Data: data,
  412. })
  413. }
  414. }
  415. return mounts, nil
  416. }
  417. // EnableServiceDiscoveryOnDefaultNetwork Enable service discovery on default network
  418. func (container *Container) EnableServiceDiscoveryOnDefaultNetwork() bool {
  419. return false
  420. }
  421. // GetMountPoints gives a platform specific transformation to types.MountPoint. Callers must hold a Container lock.
  422. func (container *Container) GetMountPoints() []types.MountPoint {
  423. mountPoints := make([]types.MountPoint, 0, len(container.MountPoints))
  424. for _, m := range container.MountPoints {
  425. mountPoints = append(mountPoints, types.MountPoint{
  426. Type: m.Type,
  427. Name: m.Name,
  428. Source: m.Path(),
  429. Destination: m.Destination,
  430. Driver: m.Driver,
  431. Mode: m.Mode,
  432. RW: m.RW,
  433. Propagation: m.Propagation,
  434. })
  435. }
  436. return mountPoints
  437. }