container_unix.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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. 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. // SecretMountPath returns the path of the secret mount for the container
  153. func (container *Container) SecretMountPath() string {
  154. return filepath.Join(container.Root, "secrets")
  155. }
  156. // CopyImagePathContent copies files in destination to the volume.
  157. func (container *Container) CopyImagePathContent(v volume.Volume, destination string) error {
  158. rootfs, err := symlink.FollowSymlinkInScope(filepath.Join(container.BaseFS, destination), container.BaseFS)
  159. if err != nil {
  160. return err
  161. }
  162. if _, err = ioutil.ReadDir(rootfs); err != nil {
  163. if os.IsNotExist(err) {
  164. return nil
  165. }
  166. return err
  167. }
  168. id := stringid.GenerateNonCryptoID()
  169. path, err := v.Mount(id)
  170. if err != nil {
  171. return err
  172. }
  173. defer func() {
  174. if err := v.Unmount(id); err != nil {
  175. logrus.Warnf("error while unmounting volume %s: %v", v.Name(), err)
  176. }
  177. }()
  178. if err := label.Relabel(path, container.MountLabel, true); err != nil && err != unix.ENOTSUP {
  179. return err
  180. }
  181. return copyExistingContents(rootfs, path)
  182. }
  183. // ShmResourcePath returns path to shm
  184. func (container *Container) ShmResourcePath() (string, error) {
  185. return container.GetRootResourcePath("shm")
  186. }
  187. // HasMountFor checks if path is a mountpoint
  188. func (container *Container) HasMountFor(path string) bool {
  189. _, exists := container.MountPoints[path]
  190. return exists
  191. }
  192. // UnmountIpcMounts uses the provided unmount function to unmount shm and mqueue if they were mounted
  193. func (container *Container) UnmountIpcMounts(unmount func(pth string) error) {
  194. if container.HostConfig.IpcMode.IsContainer() || container.HostConfig.IpcMode.IsHost() {
  195. return
  196. }
  197. var warnings []string
  198. if !container.HasMountFor("/dev/shm") {
  199. shmPath, err := container.ShmResourcePath()
  200. if err != nil {
  201. logrus.Error(err)
  202. warnings = append(warnings, err.Error())
  203. } else if shmPath != "" {
  204. if err := unmount(shmPath); err != nil && !os.IsNotExist(err) {
  205. warnings = append(warnings, fmt.Sprintf("failed to umount %s: %v", shmPath, err))
  206. }
  207. }
  208. }
  209. if len(warnings) > 0 {
  210. logrus.Warnf("failed to cleanup ipc mounts:\n%v", strings.Join(warnings, "\n"))
  211. }
  212. }
  213. // IpcMounts returns the list of IPC mounts
  214. func (container *Container) IpcMounts() []Mount {
  215. var mounts []Mount
  216. if !container.HasMountFor("/dev/shm") {
  217. label.SetFileLabel(container.ShmPath, container.MountLabel)
  218. mounts = append(mounts, Mount{
  219. Source: container.ShmPath,
  220. Destination: "/dev/shm",
  221. Writable: true,
  222. Propagation: string(volume.DefaultPropagationMode),
  223. })
  224. }
  225. return mounts
  226. }
  227. // SecretMount returns the mount for the secret path
  228. func (container *Container) SecretMount() *Mount {
  229. if len(container.SecretReferences) > 0 {
  230. return &Mount{
  231. Source: container.SecretMountPath(),
  232. Destination: containerSecretMountPath,
  233. Writable: false,
  234. }
  235. }
  236. return nil
  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. if resources.BlkioWeight != 0 {
  256. cResources.BlkioWeight = resources.BlkioWeight
  257. }
  258. if resources.CPUShares != 0 {
  259. cResources.CPUShares = resources.CPUShares
  260. }
  261. if resources.CPUPeriod != 0 {
  262. cResources.CPUPeriod = resources.CPUPeriod
  263. }
  264. if resources.CPUQuota != 0 {
  265. cResources.CPUQuota = resources.CPUQuota
  266. }
  267. if resources.CpusetCpus != "" {
  268. cResources.CpusetCpus = resources.CpusetCpus
  269. }
  270. if resources.CpusetMems != "" {
  271. cResources.CpusetMems = resources.CpusetMems
  272. }
  273. if resources.Memory != 0 {
  274. // if memory limit smaller than already set memoryswap limit and doesn't
  275. // update the memoryswap limit, then error out.
  276. if resources.Memory > cResources.MemorySwap && resources.MemorySwap == 0 {
  277. return fmt.Errorf("Memory limit should be smaller than already set memoryswap limit, update the memoryswap at the same time")
  278. }
  279. cResources.Memory = resources.Memory
  280. }
  281. if resources.MemorySwap != 0 {
  282. cResources.MemorySwap = resources.MemorySwap
  283. }
  284. if resources.MemoryReservation != 0 {
  285. cResources.MemoryReservation = resources.MemoryReservation
  286. }
  287. if resources.KernelMemory != 0 {
  288. cResources.KernelMemory = resources.KernelMemory
  289. }
  290. // update HostConfig of container
  291. if hostConfig.RestartPolicy.Name != "" {
  292. if container.HostConfig.AutoRemove && !hostConfig.RestartPolicy.IsNone() {
  293. return fmt.Errorf("Restart policy cannot be updated because AutoRemove is enabled for the container")
  294. }
  295. container.HostConfig.RestartPolicy = hostConfig.RestartPolicy
  296. }
  297. if err := container.ToDisk(); err != nil {
  298. logrus.Errorf("Error saving updated container: %v", err)
  299. return err
  300. }
  301. return nil
  302. }
  303. // DetachAndUnmount uses a detached mount on all mount destinations, then
  304. // unmounts each volume normally.
  305. // This is used from daemon/archive for `docker cp`
  306. func (container *Container) DetachAndUnmount(volumeEventLog func(name, action string, attributes map[string]string)) error {
  307. networkMounts := container.NetworkMounts()
  308. mountPaths := make([]string, 0, len(container.MountPoints)+len(networkMounts))
  309. for _, mntPoint := range container.MountPoints {
  310. dest, err := container.GetResourcePath(mntPoint.Destination)
  311. if err != nil {
  312. logrus.Warnf("Failed to get volume destination path for container '%s' at '%s' while lazily unmounting: %v", container.ID, mntPoint.Destination, err)
  313. continue
  314. }
  315. mountPaths = append(mountPaths, dest)
  316. }
  317. for _, m := range networkMounts {
  318. dest, err := container.GetResourcePath(m.Destination)
  319. if err != nil {
  320. logrus.Warnf("Failed to get volume destination path for container '%s' at '%s' while lazily unmounting: %v", container.ID, m.Destination, err)
  321. continue
  322. }
  323. mountPaths = append(mountPaths, dest)
  324. }
  325. for _, mountPath := range mountPaths {
  326. if err := detachMounted(mountPath); err != nil {
  327. logrus.Warnf("%s unmountVolumes: Failed to do lazy umount fo volume '%s': %v", container.ID, mountPath, err)
  328. }
  329. }
  330. return container.UnmountVolumes(volumeEventLog)
  331. }
  332. // copyExistingContents copies from the source to the destination and
  333. // ensures the ownership is appropriately set.
  334. func copyExistingContents(source, destination string) error {
  335. volList, err := ioutil.ReadDir(source)
  336. if err != nil {
  337. return err
  338. }
  339. if len(volList) > 0 {
  340. srcList, err := ioutil.ReadDir(destination)
  341. if err != nil {
  342. return err
  343. }
  344. if len(srcList) == 0 {
  345. // If the source volume is empty, copies files from the root into the volume
  346. if err := chrootarchive.CopyWithTar(source, destination); err != nil {
  347. return err
  348. }
  349. }
  350. }
  351. return copyOwnership(source, destination)
  352. }
  353. // copyOwnership copies the permissions and uid:gid of the source file
  354. // to the destination file
  355. func copyOwnership(source, destination string) error {
  356. stat, err := system.Stat(source)
  357. if err != nil {
  358. return err
  359. }
  360. if err := os.Chown(destination, int(stat.UID()), int(stat.GID())); err != nil {
  361. return err
  362. }
  363. return os.Chmod(destination, os.FileMode(stat.Mode()))
  364. }
  365. // TmpfsMounts returns the list of tmpfs mounts
  366. func (container *Container) TmpfsMounts() ([]Mount, error) {
  367. var mounts []Mount
  368. for dest, data := range container.HostConfig.Tmpfs {
  369. mounts = append(mounts, Mount{
  370. Source: "tmpfs",
  371. Destination: dest,
  372. Data: data,
  373. })
  374. }
  375. for dest, mnt := range container.MountPoints {
  376. if mnt.Type == mounttypes.TypeTmpfs {
  377. data, err := volume.ConvertTmpfsOptions(mnt.Spec.TmpfsOptions, mnt.Spec.ReadOnly)
  378. if err != nil {
  379. return nil, err
  380. }
  381. mounts = append(mounts, Mount{
  382. Source: "tmpfs",
  383. Destination: dest,
  384. Data: data,
  385. })
  386. }
  387. }
  388. return mounts, nil
  389. }
  390. // cleanResourcePath cleans a resource path and prepares to combine with mnt path
  391. func cleanResourcePath(path string) string {
  392. return filepath.Join(string(os.PathSeparator), path)
  393. }
  394. // EnableServiceDiscoveryOnDefaultNetwork Enable service discovery on default network
  395. func (container *Container) EnableServiceDiscoveryOnDefaultNetwork() bool {
  396. return false
  397. }