container_unix.go 14 KB

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