container_unix.go 15 KB

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