container_unix.go 14 KB

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