container_unix.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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. containertypes "github.com/docker/docker/api/types/container"
  11. mounttypes "github.com/docker/docker/api/types/mount"
  12. "github.com/docker/docker/pkg/chrootarchive"
  13. "github.com/docker/docker/pkg/mount"
  14. "github.com/docker/docker/pkg/stringid"
  15. "github.com/docker/docker/pkg/symlink"
  16. "github.com/docker/docker/pkg/system"
  17. "github.com/docker/docker/volume"
  18. "github.com/opencontainers/selinux/go-selinux/label"
  19. "golang.org/x/sys/unix"
  20. )
  21. const (
  22. containerSecretMountPath = "/run/secrets"
  23. )
  24. // ExitStatus provides exit reasons for a container.
  25. type ExitStatus struct {
  26. // The exit code with which the container exited.
  27. ExitCode int
  28. // Whether the container encountered an OOM.
  29. OOMKilled bool
  30. }
  31. // TrySetNetworkMount attempts to set the network mounts given a provided destination and
  32. // the path to use for it; return true if the given destination was a network mount file
  33. func (container *Container) TrySetNetworkMount(destination string, path string) bool {
  34. if destination == "/etc/resolv.conf" {
  35. container.ResolvConfPath = path
  36. return true
  37. }
  38. if destination == "/etc/hostname" {
  39. container.HostnamePath = path
  40. return true
  41. }
  42. if destination == "/etc/hosts" {
  43. container.HostsPath = path
  44. return true
  45. }
  46. return false
  47. }
  48. // BuildHostnameFile writes the container's hostname file.
  49. func (container *Container) BuildHostnameFile() error {
  50. hostnamePath, err := container.GetRootResourcePath("hostname")
  51. if err != nil {
  52. return err
  53. }
  54. container.HostnamePath = hostnamePath
  55. return ioutil.WriteFile(container.HostnamePath, []byte(container.Config.Hostname+"\n"), 0644)
  56. }
  57. // NetworkMounts returns the list of network mounts.
  58. func (container *Container) NetworkMounts() []Mount {
  59. var mounts []Mount
  60. shared := container.HostConfig.NetworkMode.IsContainer()
  61. if container.ResolvConfPath != "" {
  62. if _, err := os.Stat(container.ResolvConfPath); err != nil {
  63. logrus.Warnf("ResolvConfPath set to %q, but can't stat this filename (err = %v); skipping", container.ResolvConfPath, err)
  64. } else {
  65. if !container.HasMountFor("/etc/resolv.conf") {
  66. label.Relabel(container.ResolvConfPath, container.MountLabel, shared)
  67. }
  68. writable := !container.HostConfig.ReadonlyRootfs
  69. if m, exists := container.MountPoints["/etc/resolv.conf"]; exists {
  70. writable = m.RW
  71. }
  72. mounts = append(mounts, Mount{
  73. Source: container.ResolvConfPath,
  74. Destination: "/etc/resolv.conf",
  75. Writable: writable,
  76. Propagation: string(volume.DefaultPropagationMode),
  77. })
  78. }
  79. }
  80. if container.HostnamePath != "" {
  81. if _, err := os.Stat(container.HostnamePath); err != nil {
  82. logrus.Warnf("HostnamePath set to %q, but can't stat this filename (err = %v); skipping", container.HostnamePath, err)
  83. } else {
  84. if !container.HasMountFor("/etc/hostname") {
  85. label.Relabel(container.HostnamePath, container.MountLabel, shared)
  86. }
  87. writable := !container.HostConfig.ReadonlyRootfs
  88. if m, exists := container.MountPoints["/etc/hostname"]; exists {
  89. writable = m.RW
  90. }
  91. mounts = append(mounts, Mount{
  92. Source: container.HostnamePath,
  93. Destination: "/etc/hostname",
  94. Writable: writable,
  95. Propagation: string(volume.DefaultPropagationMode),
  96. })
  97. }
  98. }
  99. if container.HostsPath != "" {
  100. if _, err := os.Stat(container.HostsPath); err != nil {
  101. logrus.Warnf("HostsPath set to %q, but can't stat this filename (err = %v); skipping", container.HostsPath, err)
  102. } else {
  103. if !container.HasMountFor("/etc/hosts") {
  104. label.Relabel(container.HostsPath, container.MountLabel, shared)
  105. }
  106. writable := !container.HostConfig.ReadonlyRootfs
  107. if m, exists := container.MountPoints["/etc/hosts"]; exists {
  108. writable = m.RW
  109. }
  110. mounts = append(mounts, Mount{
  111. Source: container.HostsPath,
  112. Destination: "/etc/hosts",
  113. Writable: writable,
  114. Propagation: string(volume.DefaultPropagationMode),
  115. })
  116. }
  117. }
  118. return mounts
  119. }
  120. // CopyImagePathContent copies files in destination to the volume.
  121. func (container *Container) CopyImagePathContent(v volume.Volume, destination string) error {
  122. rootfs, err := symlink.FollowSymlinkInScope(filepath.Join(container.BaseFS, destination), container.BaseFS)
  123. if err != nil {
  124. return err
  125. }
  126. if _, err = ioutil.ReadDir(rootfs); err != nil {
  127. if os.IsNotExist(err) {
  128. return nil
  129. }
  130. return err
  131. }
  132. id := stringid.GenerateNonCryptoID()
  133. path, err := v.Mount(id)
  134. if err != nil {
  135. return err
  136. }
  137. defer func() {
  138. if err := v.Unmount(id); err != nil {
  139. logrus.Warnf("error while unmounting volume %s: %v", v.Name(), err)
  140. }
  141. }()
  142. if err := label.Relabel(path, container.MountLabel, true); err != nil && err != unix.ENOTSUP {
  143. return err
  144. }
  145. return copyExistingContents(rootfs, path)
  146. }
  147. // ShmResourcePath returns path to shm
  148. func (container *Container) ShmResourcePath() (string, error) {
  149. return container.GetRootResourcePath("shm")
  150. }
  151. // HasMountFor checks if path is a mountpoint
  152. func (container *Container) HasMountFor(path string) bool {
  153. _, exists := container.MountPoints[path]
  154. return exists
  155. }
  156. // UnmountIpcMounts uses the provided unmount function to unmount shm and mqueue if they were mounted
  157. func (container *Container) UnmountIpcMounts(unmount func(pth string) error) {
  158. if container.HostConfig.IpcMode.IsContainer() || container.HostConfig.IpcMode.IsHost() {
  159. return
  160. }
  161. var warnings []string
  162. if !container.HasMountFor("/dev/shm") {
  163. shmPath, err := container.ShmResourcePath()
  164. if err != nil {
  165. logrus.Error(err)
  166. warnings = append(warnings, err.Error())
  167. } else if shmPath != "" {
  168. if err := unmount(shmPath); err != nil && !os.IsNotExist(err) {
  169. if mounted, mErr := mount.Mounted(shmPath); mounted || mErr != nil {
  170. warnings = append(warnings, fmt.Sprintf("failed to umount %s: %v", shmPath, err))
  171. }
  172. }
  173. }
  174. }
  175. if len(warnings) > 0 {
  176. logrus.Warnf("failed to cleanup ipc mounts:\n%v", strings.Join(warnings, "\n"))
  177. }
  178. }
  179. // IpcMounts returns the list of IPC mounts
  180. func (container *Container) IpcMounts() []Mount {
  181. var mounts []Mount
  182. if !container.HasMountFor("/dev/shm") {
  183. label.SetFileLabel(container.ShmPath, container.MountLabel)
  184. mounts = append(mounts, Mount{
  185. Source: container.ShmPath,
  186. Destination: "/dev/shm",
  187. Writable: true,
  188. Propagation: string(volume.DefaultPropagationMode),
  189. })
  190. }
  191. return mounts
  192. }
  193. // SecretMounts returns the mounts for the secret path.
  194. func (container *Container) SecretMounts() []Mount {
  195. var mounts []Mount
  196. for _, r := range container.SecretReferences {
  197. if r.File == nil {
  198. continue
  199. }
  200. mounts = append(mounts, Mount{
  201. Source: container.SecretFilePath(*r),
  202. Destination: getSecretTargetPath(r),
  203. Writable: false,
  204. })
  205. }
  206. return mounts
  207. }
  208. // UnmountSecrets unmounts the local tmpfs for secrets
  209. func (container *Container) UnmountSecrets() error {
  210. if _, err := os.Stat(container.SecretMountPath()); err != nil {
  211. if os.IsNotExist(err) {
  212. return nil
  213. }
  214. return err
  215. }
  216. return detachMounted(container.SecretMountPath())
  217. }
  218. // ConfigMounts returns the mounts for configs.
  219. func (container *Container) ConfigMounts() []Mount {
  220. var mounts []Mount
  221. for _, configRef := range container.ConfigReferences {
  222. if configRef.File == nil {
  223. continue
  224. }
  225. mounts = append(mounts, Mount{
  226. Source: container.ConfigFilePath(*configRef),
  227. Destination: configRef.File.Name,
  228. Writable: false,
  229. })
  230. }
  231. return mounts
  232. }
  233. // UpdateContainer updates configuration of a container.
  234. func (container *Container) UpdateContainer(hostConfig *containertypes.HostConfig) error {
  235. container.Lock()
  236. defer container.Unlock()
  237. // update resources of container
  238. resources := hostConfig.Resources
  239. cResources := &container.HostConfig.Resources
  240. // validate NanoCPUs, CPUPeriod, and CPUQuota
  241. // Becuase 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 fmt.Errorf("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 fmt.Errorf("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 fmt.Errorf("Conflicting options: CPU Period cannot be updated as NanoCPUs has already been set")
  252. }
  253. if resources.CPUQuota > 0 && cResources.NanoCPUs > 0 {
  254. return fmt.Errorf("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 fmt.Errorf("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 fmt.Errorf("Restart policy cannot be updated because AutoRemove is enabled for the container")
  298. }
  299. container.HostConfig.RestartPolicy = hostConfig.RestartPolicy
  300. }
  301. if err := container.ToDisk(); err != nil {
  302. logrus.Errorf("Error saving updated container: %v", err)
  303. return err
  304. }
  305. return nil
  306. }
  307. // DetachAndUnmount uses a detached mount on all mount destinations, then
  308. // unmounts each volume normally.
  309. // This is used from daemon/archive for `docker cp`
  310. func (container *Container) DetachAndUnmount(volumeEventLog func(name, action string, attributes map[string]string)) error {
  311. networkMounts := container.NetworkMounts()
  312. mountPaths := make([]string, 0, len(container.MountPoints)+len(networkMounts))
  313. for _, mntPoint := range container.MountPoints {
  314. dest, err := container.GetResourcePath(mntPoint.Destination)
  315. if err != nil {
  316. logrus.Warnf("Failed to get volume destination path for container '%s' at '%s' while lazily unmounting: %v", container.ID, mntPoint.Destination, err)
  317. continue
  318. }
  319. mountPaths = append(mountPaths, dest)
  320. }
  321. for _, m := range networkMounts {
  322. dest, err := container.GetResourcePath(m.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, m.Destination, err)
  325. continue
  326. }
  327. mountPaths = append(mountPaths, dest)
  328. }
  329. for _, mountPath := range mountPaths {
  330. if err := detachMounted(mountPath); err != nil {
  331. logrus.Warnf("%s unmountVolumes: Failed to do lazy umount fo volume '%s': %v", container.ID, mountPath, err)
  332. }
  333. }
  334. return container.UnmountVolumes(volumeEventLog)
  335. }
  336. // copyExistingContents copies from the source to the destination and
  337. // ensures the ownership is appropriately set.
  338. func copyExistingContents(source, destination string) error {
  339. volList, err := ioutil.ReadDir(source)
  340. if err != nil {
  341. return err
  342. }
  343. if len(volList) > 0 {
  344. srcList, err := ioutil.ReadDir(destination)
  345. if err != nil {
  346. return err
  347. }
  348. if len(srcList) == 0 {
  349. // If the source volume is empty, copies files from the root into the volume
  350. if err := chrootarchive.NewArchiver(nil).CopyWithTar(source, destination); err != nil {
  351. return err
  352. }
  353. }
  354. }
  355. return copyOwnership(source, destination)
  356. }
  357. // copyOwnership copies the permissions and uid:gid of the source file
  358. // to the destination file
  359. func copyOwnership(source, destination string) error {
  360. stat, err := system.Stat(source)
  361. if err != nil {
  362. return err
  363. }
  364. destStat, err := system.Stat(destination)
  365. if err != nil {
  366. return err
  367. }
  368. // In some cases, even though UID/GID match and it would effectively be a no-op,
  369. // this can return a permission denied error... for example if this is an NFS
  370. // mount.
  371. // Since it's not really an error that we can't chown to the same UID/GID, don't
  372. // even bother trying in such cases.
  373. if stat.UID() != destStat.UID() || stat.GID() != destStat.GID() {
  374. if err := os.Chown(destination, int(stat.UID()), int(stat.GID())); err != nil {
  375. return err
  376. }
  377. }
  378. if stat.Mode() != destStat.Mode() {
  379. return os.Chmod(destination, os.FileMode(stat.Mode()))
  380. }
  381. return nil
  382. }
  383. // TmpfsMounts returns the list of tmpfs mounts
  384. func (container *Container) TmpfsMounts() ([]Mount, error) {
  385. var mounts []Mount
  386. for dest, data := range container.HostConfig.Tmpfs {
  387. mounts = append(mounts, Mount{
  388. Source: "tmpfs",
  389. Destination: dest,
  390. Data: data,
  391. })
  392. }
  393. for dest, mnt := range container.MountPoints {
  394. if mnt.Type == mounttypes.TypeTmpfs {
  395. data, err := volume.ConvertTmpfsOptions(mnt.Spec.TmpfsOptions, mnt.Spec.ReadOnly)
  396. if err != nil {
  397. return nil, err
  398. }
  399. mounts = append(mounts, Mount{
  400. Source: "tmpfs",
  401. Destination: dest,
  402. Data: data,
  403. })
  404. }
  405. }
  406. return mounts, nil
  407. }
  408. // cleanResourcePath cleans a resource path and prepares to combine with mnt path
  409. func cleanResourcePath(path string) string {
  410. return filepath.Join(string(os.PathSeparator), path)
  411. }
  412. // EnableServiceDiscoveryOnDefaultNetwork Enable service discovery on default network
  413. func (container *Container) EnableServiceDiscoveryOnDefaultNetwork() bool {
  414. return false
  415. }