container_unix.go 15 KB

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