container_unix.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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. // Container holds the fields specific to unixen implementations.
  25. // See CommonContainer for standard fields common to all containers.
  26. type Container struct {
  27. CommonContainer
  28. // Fields below here are platform specific.
  29. AppArmorProfile string
  30. HostnamePath string
  31. HostsPath string
  32. ShmPath string
  33. ResolvConfPath string
  34. SeccompProfile string
  35. NoNewPrivileges bool
  36. }
  37. // ExitStatus provides exit reasons for a container.
  38. type ExitStatus struct {
  39. // The exit code with which the container exited.
  40. ExitCode int
  41. // Whether the container encountered an OOM.
  42. OOMKilled bool
  43. }
  44. // CreateDaemonEnvironment returns the list of all environment variables given the list of
  45. // environment variables related to links.
  46. // Sets PATH, HOSTNAME and if container.Config.Tty is set: TERM.
  47. // The defaults set here do not override the values in container.Config.Env
  48. func (container *Container) CreateDaemonEnvironment(tty bool, linkedEnv []string) []string {
  49. // Setup environment
  50. env := []string{
  51. "PATH=" + system.DefaultPathEnv,
  52. "HOSTNAME=" + container.Config.Hostname,
  53. }
  54. if tty {
  55. env = append(env, "TERM=xterm")
  56. }
  57. env = append(env, linkedEnv...)
  58. // because the env on the container can override certain default values
  59. // we need to replace the 'env' keys where they match and append anything
  60. // else.
  61. env = ReplaceOrAppendEnvValues(env, container.Config.Env)
  62. return env
  63. }
  64. // TrySetNetworkMount attempts to set the network mounts given a provided destination and
  65. // the path to use for it; return true if the given destination was a network mount file
  66. func (container *Container) TrySetNetworkMount(destination string, path string) bool {
  67. if destination == "/etc/resolv.conf" {
  68. container.ResolvConfPath = path
  69. return true
  70. }
  71. if destination == "/etc/hostname" {
  72. container.HostnamePath = path
  73. return true
  74. }
  75. if destination == "/etc/hosts" {
  76. container.HostsPath = path
  77. return true
  78. }
  79. return false
  80. }
  81. // BuildHostnameFile writes the container's hostname file.
  82. func (container *Container) BuildHostnameFile() error {
  83. hostnamePath, err := container.GetRootResourcePath("hostname")
  84. if err != nil {
  85. return err
  86. }
  87. container.HostnamePath = hostnamePath
  88. return ioutil.WriteFile(container.HostnamePath, []byte(container.Config.Hostname+"\n"), 0644)
  89. }
  90. // NetworkMounts returns the list of network mounts.
  91. func (container *Container) NetworkMounts() []Mount {
  92. var mounts []Mount
  93. shared := container.HostConfig.NetworkMode.IsContainer()
  94. if container.ResolvConfPath != "" {
  95. if _, err := os.Stat(container.ResolvConfPath); err != nil {
  96. logrus.Warnf("ResolvConfPath set to %q, but can't stat this filename (err = %v); skipping", container.ResolvConfPath, err)
  97. } else {
  98. if !container.HasMountFor("/etc/resolv.conf") {
  99. label.Relabel(container.ResolvConfPath, container.MountLabel, shared)
  100. }
  101. writable := !container.HostConfig.ReadonlyRootfs
  102. if m, exists := container.MountPoints["/etc/resolv.conf"]; exists {
  103. writable = m.RW
  104. }
  105. mounts = append(mounts, Mount{
  106. Source: container.ResolvConfPath,
  107. Destination: "/etc/resolv.conf",
  108. Writable: writable,
  109. Propagation: string(volume.DefaultPropagationMode),
  110. })
  111. }
  112. }
  113. if container.HostnamePath != "" {
  114. if _, err := os.Stat(container.HostnamePath); err != nil {
  115. logrus.Warnf("HostnamePath set to %q, but can't stat this filename (err = %v); skipping", container.HostnamePath, err)
  116. } else {
  117. if !container.HasMountFor("/etc/hostname") {
  118. label.Relabel(container.HostnamePath, container.MountLabel, shared)
  119. }
  120. writable := !container.HostConfig.ReadonlyRootfs
  121. if m, exists := container.MountPoints["/etc/hostname"]; exists {
  122. writable = m.RW
  123. }
  124. mounts = append(mounts, Mount{
  125. Source: container.HostnamePath,
  126. Destination: "/etc/hostname",
  127. Writable: writable,
  128. Propagation: string(volume.DefaultPropagationMode),
  129. })
  130. }
  131. }
  132. if container.HostsPath != "" {
  133. if _, err := os.Stat(container.HostsPath); err != nil {
  134. logrus.Warnf("HostsPath set to %q, but can't stat this filename (err = %v); skipping", container.HostsPath, err)
  135. } else {
  136. if !container.HasMountFor("/etc/hosts") {
  137. label.Relabel(container.HostsPath, container.MountLabel, shared)
  138. }
  139. writable := !container.HostConfig.ReadonlyRootfs
  140. if m, exists := container.MountPoints["/etc/hosts"]; exists {
  141. writable = m.RW
  142. }
  143. mounts = append(mounts, Mount{
  144. Source: container.HostsPath,
  145. Destination: "/etc/hosts",
  146. Writable: writable,
  147. Propagation: string(volume.DefaultPropagationMode),
  148. })
  149. }
  150. }
  151. return mounts
  152. }
  153. // CopyImagePathContent copies files in destination to the volume.
  154. func (container *Container) CopyImagePathContent(v volume.Volume, destination string) error {
  155. rootfs, err := symlink.FollowSymlinkInScope(filepath.Join(container.BaseFS, destination), container.BaseFS)
  156. if err != nil {
  157. return err
  158. }
  159. if _, err = ioutil.ReadDir(rootfs); err != nil {
  160. if os.IsNotExist(err) {
  161. return nil
  162. }
  163. return err
  164. }
  165. id := stringid.GenerateNonCryptoID()
  166. path, err := v.Mount(id)
  167. if err != nil {
  168. return err
  169. }
  170. defer func() {
  171. if err := v.Unmount(id); err != nil {
  172. logrus.Warnf("error while unmounting volume %s: %v", v.Name(), err)
  173. }
  174. }()
  175. if err := label.Relabel(path, container.MountLabel, true); err != nil && err != unix.ENOTSUP {
  176. return err
  177. }
  178. return copyExistingContents(rootfs, path)
  179. }
  180. // ShmResourcePath returns path to shm
  181. func (container *Container) ShmResourcePath() (string, error) {
  182. return container.GetRootResourcePath("shm")
  183. }
  184. // HasMountFor checks if path is a mountpoint
  185. func (container *Container) HasMountFor(path string) bool {
  186. _, exists := container.MountPoints[path]
  187. return exists
  188. }
  189. // UnmountIpcMounts uses the provided unmount function to unmount shm and mqueue if they were mounted
  190. func (container *Container) UnmountIpcMounts(unmount func(pth string) error) {
  191. if container.HostConfig.IpcMode.IsContainer() || container.HostConfig.IpcMode.IsHost() {
  192. return
  193. }
  194. var warnings []string
  195. if !container.HasMountFor("/dev/shm") {
  196. shmPath, err := container.ShmResourcePath()
  197. if err != nil {
  198. logrus.Error(err)
  199. warnings = append(warnings, err.Error())
  200. } else if shmPath != "" {
  201. if err := unmount(shmPath); err != nil && !os.IsNotExist(err) {
  202. if mounted, mErr := mount.Mounted(shmPath); mounted || mErr != nil {
  203. warnings = append(warnings, fmt.Sprintf("failed to umount %s: %v", shmPath, err))
  204. }
  205. }
  206. }
  207. }
  208. if len(warnings) > 0 {
  209. logrus.Warnf("failed to cleanup ipc mounts:\n%v", strings.Join(warnings, "\n"))
  210. }
  211. }
  212. // IpcMounts returns the list of IPC mounts
  213. func (container *Container) IpcMounts() []Mount {
  214. var mounts []Mount
  215. if !container.HasMountFor("/dev/shm") {
  216. label.SetFileLabel(container.ShmPath, container.MountLabel)
  217. mounts = append(mounts, Mount{
  218. Source: container.ShmPath,
  219. Destination: "/dev/shm",
  220. Writable: true,
  221. Propagation: string(volume.DefaultPropagationMode),
  222. })
  223. }
  224. return mounts
  225. }
  226. // SecretMounts returns the mounts for the secret path.
  227. func (container *Container) SecretMounts() []Mount {
  228. var mounts []Mount
  229. for _, r := range container.SecretReferences {
  230. if r.File == nil {
  231. continue
  232. }
  233. mounts = append(mounts, Mount{
  234. Source: container.SecretFilePath(*r),
  235. Destination: getSecretTargetPath(r),
  236. Writable: false,
  237. })
  238. }
  239. return mounts
  240. }
  241. // UnmountSecrets unmounts the local tmpfs for secrets
  242. func (container *Container) UnmountSecrets() error {
  243. if _, err := os.Stat(container.SecretMountPath()); err != nil {
  244. if os.IsNotExist(err) {
  245. return nil
  246. }
  247. return err
  248. }
  249. return detachMounted(container.SecretMountPath())
  250. }
  251. // ConfigMounts returns the mounts for configs.
  252. func (container *Container) ConfigMounts() []Mount {
  253. var mounts []Mount
  254. for _, configRef := range container.ConfigReferences {
  255. if configRef.File == nil {
  256. continue
  257. }
  258. mounts = append(mounts, Mount{
  259. Source: container.ConfigFilePath(*configRef),
  260. Destination: configRef.File.Name,
  261. Writable: false,
  262. })
  263. }
  264. return mounts
  265. }
  266. // UpdateContainer updates configuration of a container.
  267. func (container *Container) UpdateContainer(hostConfig *containertypes.HostConfig) error {
  268. container.Lock()
  269. defer container.Unlock()
  270. // update resources of container
  271. resources := hostConfig.Resources
  272. cResources := &container.HostConfig.Resources
  273. // validate NanoCPUs, CPUPeriod, and CPUQuota
  274. // Becuase NanoCPU effectively updates CPUPeriod/CPUQuota,
  275. // once NanoCPU is already set, updating CPUPeriod/CPUQuota will be blocked, and vice versa.
  276. // In the following we make sure the intended update (resources) does not conflict with the existing (cResource).
  277. if resources.NanoCPUs > 0 && cResources.CPUPeriod > 0 {
  278. return fmt.Errorf("Conflicting options: Nano CPUs cannot be updated as CPU Period has already been set")
  279. }
  280. if resources.NanoCPUs > 0 && cResources.CPUQuota > 0 {
  281. return fmt.Errorf("Conflicting options: Nano CPUs cannot be updated as CPU Quota has already been set")
  282. }
  283. if resources.CPUPeriod > 0 && cResources.NanoCPUs > 0 {
  284. return fmt.Errorf("Conflicting options: CPU Period cannot be updated as NanoCPUs has already been set")
  285. }
  286. if resources.CPUQuota > 0 && cResources.NanoCPUs > 0 {
  287. return fmt.Errorf("Conflicting options: CPU Quota cannot be updated as NanoCPUs has already been set")
  288. }
  289. if resources.BlkioWeight != 0 {
  290. cResources.BlkioWeight = resources.BlkioWeight
  291. }
  292. if resources.CPUShares != 0 {
  293. cResources.CPUShares = resources.CPUShares
  294. }
  295. if resources.NanoCPUs != 0 {
  296. cResources.NanoCPUs = resources.NanoCPUs
  297. }
  298. if resources.CPUPeriod != 0 {
  299. cResources.CPUPeriod = resources.CPUPeriod
  300. }
  301. if resources.CPUQuota != 0 {
  302. cResources.CPUQuota = resources.CPUQuota
  303. }
  304. if resources.CpusetCpus != "" {
  305. cResources.CpusetCpus = resources.CpusetCpus
  306. }
  307. if resources.CpusetMems != "" {
  308. cResources.CpusetMems = resources.CpusetMems
  309. }
  310. if resources.Memory != 0 {
  311. // if memory limit smaller than already set memoryswap limit and doesn't
  312. // update the memoryswap limit, then error out.
  313. if resources.Memory > cResources.MemorySwap && resources.MemorySwap == 0 {
  314. return fmt.Errorf("Memory limit should be smaller than already set memoryswap limit, update the memoryswap at the same time")
  315. }
  316. cResources.Memory = resources.Memory
  317. }
  318. if resources.MemorySwap != 0 {
  319. cResources.MemorySwap = resources.MemorySwap
  320. }
  321. if resources.MemoryReservation != 0 {
  322. cResources.MemoryReservation = resources.MemoryReservation
  323. }
  324. if resources.KernelMemory != 0 {
  325. cResources.KernelMemory = resources.KernelMemory
  326. }
  327. // update HostConfig of container
  328. if hostConfig.RestartPolicy.Name != "" {
  329. if container.HostConfig.AutoRemove && !hostConfig.RestartPolicy.IsNone() {
  330. return fmt.Errorf("Restart policy cannot be updated because AutoRemove is enabled for the container")
  331. }
  332. container.HostConfig.RestartPolicy = hostConfig.RestartPolicy
  333. }
  334. if err := container.ToDisk(); err != nil {
  335. logrus.Errorf("Error saving updated container: %v", err)
  336. return err
  337. }
  338. return nil
  339. }
  340. // DetachAndUnmount uses a detached mount on all mount destinations, then
  341. // unmounts each volume normally.
  342. // This is used from daemon/archive for `docker cp`
  343. func (container *Container) DetachAndUnmount(volumeEventLog func(name, action string, attributes map[string]string)) error {
  344. networkMounts := container.NetworkMounts()
  345. mountPaths := make([]string, 0, len(container.MountPoints)+len(networkMounts))
  346. for _, mntPoint := range container.MountPoints {
  347. dest, err := container.GetResourcePath(mntPoint.Destination)
  348. if err != nil {
  349. logrus.Warnf("Failed to get volume destination path for container '%s' at '%s' while lazily unmounting: %v", container.ID, mntPoint.Destination, err)
  350. continue
  351. }
  352. mountPaths = append(mountPaths, dest)
  353. }
  354. for _, m := range networkMounts {
  355. dest, err := container.GetResourcePath(m.Destination)
  356. if err != nil {
  357. logrus.Warnf("Failed to get volume destination path for container '%s' at '%s' while lazily unmounting: %v", container.ID, m.Destination, err)
  358. continue
  359. }
  360. mountPaths = append(mountPaths, dest)
  361. }
  362. for _, mountPath := range mountPaths {
  363. if err := detachMounted(mountPath); err != nil {
  364. logrus.Warnf("%s unmountVolumes: Failed to do lazy umount fo volume '%s': %v", container.ID, mountPath, err)
  365. }
  366. }
  367. return container.UnmountVolumes(volumeEventLog)
  368. }
  369. // copyExistingContents copies from the source to the destination and
  370. // ensures the ownership is appropriately set.
  371. func copyExistingContents(source, destination string) error {
  372. volList, err := ioutil.ReadDir(source)
  373. if err != nil {
  374. return err
  375. }
  376. if len(volList) > 0 {
  377. srcList, err := ioutil.ReadDir(destination)
  378. if err != nil {
  379. return err
  380. }
  381. if len(srcList) == 0 {
  382. // If the source volume is empty, copies files from the root into the volume
  383. if err := chrootarchive.NewArchiver(nil).CopyWithTar(source, destination); err != nil {
  384. return err
  385. }
  386. }
  387. }
  388. return copyOwnership(source, destination)
  389. }
  390. // copyOwnership copies the permissions and uid:gid of the source file
  391. // to the destination file
  392. func copyOwnership(source, destination string) error {
  393. stat, err := system.Stat(source)
  394. if err != nil {
  395. return err
  396. }
  397. destStat, err := system.Stat(destination)
  398. if err != nil {
  399. return err
  400. }
  401. // In some cases, even though UID/GID match and it would effectively be a no-op,
  402. // this can return a permission denied error... for example if this is an NFS
  403. // mount.
  404. // Since it's not really an error that we can't chown to the same UID/GID, don't
  405. // even bother trying in such cases.
  406. if stat.UID() != destStat.UID() || stat.GID() != destStat.GID() {
  407. if err := os.Chown(destination, int(stat.UID()), int(stat.GID())); err != nil {
  408. return err
  409. }
  410. }
  411. if stat.Mode() != destStat.Mode() {
  412. return os.Chmod(destination, os.FileMode(stat.Mode()))
  413. }
  414. return nil
  415. }
  416. // TmpfsMounts returns the list of tmpfs mounts
  417. func (container *Container) TmpfsMounts() ([]Mount, error) {
  418. var mounts []Mount
  419. for dest, data := range container.HostConfig.Tmpfs {
  420. mounts = append(mounts, Mount{
  421. Source: "tmpfs",
  422. Destination: dest,
  423. Data: data,
  424. })
  425. }
  426. for dest, mnt := range container.MountPoints {
  427. if mnt.Type == mounttypes.TypeTmpfs {
  428. data, err := volume.ConvertTmpfsOptions(mnt.Spec.TmpfsOptions, mnt.Spec.ReadOnly)
  429. if err != nil {
  430. return nil, err
  431. }
  432. mounts = append(mounts, Mount{
  433. Source: "tmpfs",
  434. Destination: dest,
  435. Data: data,
  436. })
  437. }
  438. }
  439. return mounts, nil
  440. }
  441. // cleanResourcePath cleans a resource path and prepares to combine with mnt path
  442. func cleanResourcePath(path string) string {
  443. return filepath.Join(string(os.PathSeparator), path)
  444. }
  445. // EnableServiceDiscoveryOnDefaultNetwork Enable service discovery on default network
  446. func (container *Container) EnableServiceDiscoveryOnDefaultNetwork() bool {
  447. return false
  448. }