container_unix.go 14 KB

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