container_unix.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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. // appendNetworkMounts appends any network mounts to the array of mount points passed in
  93. func appendNetworkMounts(container *Container, volumeMounts []volume.MountPoint) ([]volume.MountPoint, error) {
  94. for _, mnt := range container.NetworkMounts() {
  95. dest, err := container.GetResourcePath(mnt.Destination)
  96. if err != nil {
  97. return nil, err
  98. }
  99. volumeMounts = append(volumeMounts, volume.MountPoint{Destination: dest})
  100. }
  101. return volumeMounts, nil
  102. }
  103. // NetworkMounts returns the list of network mounts.
  104. func (container *Container) NetworkMounts() []Mount {
  105. var mounts []Mount
  106. shared := container.HostConfig.NetworkMode.IsContainer()
  107. if container.ResolvConfPath != "" {
  108. if _, err := os.Stat(container.ResolvConfPath); err != nil {
  109. logrus.Warnf("ResolvConfPath set to %q, but can't stat this filename (err = %v); skipping", container.ResolvConfPath, err)
  110. } else {
  111. if !container.HasMountFor("/etc/resolv.conf") {
  112. label.Relabel(container.ResolvConfPath, container.MountLabel, shared)
  113. }
  114. writable := !container.HostConfig.ReadonlyRootfs
  115. if m, exists := container.MountPoints["/etc/resolv.conf"]; exists {
  116. writable = m.RW
  117. }
  118. mounts = append(mounts, Mount{
  119. Source: container.ResolvConfPath,
  120. Destination: "/etc/resolv.conf",
  121. Writable: writable,
  122. Propagation: string(volume.DefaultPropagationMode),
  123. })
  124. }
  125. }
  126. if container.HostnamePath != "" {
  127. if _, err := os.Stat(container.HostnamePath); err != nil {
  128. logrus.Warnf("HostnamePath set to %q, but can't stat this filename (err = %v); skipping", container.HostnamePath, err)
  129. } else {
  130. if !container.HasMountFor("/etc/hostname") {
  131. label.Relabel(container.HostnamePath, container.MountLabel, shared)
  132. }
  133. writable := !container.HostConfig.ReadonlyRootfs
  134. if m, exists := container.MountPoints["/etc/hostname"]; exists {
  135. writable = m.RW
  136. }
  137. mounts = append(mounts, Mount{
  138. Source: container.HostnamePath,
  139. Destination: "/etc/hostname",
  140. Writable: writable,
  141. Propagation: string(volume.DefaultPropagationMode),
  142. })
  143. }
  144. }
  145. if container.HostsPath != "" {
  146. if _, err := os.Stat(container.HostsPath); err != nil {
  147. logrus.Warnf("HostsPath set to %q, but can't stat this filename (err = %v); skipping", container.HostsPath, err)
  148. } else {
  149. if !container.HasMountFor("/etc/hosts") {
  150. label.Relabel(container.HostsPath, container.MountLabel, shared)
  151. }
  152. writable := !container.HostConfig.ReadonlyRootfs
  153. if m, exists := container.MountPoints["/etc/hosts"]; exists {
  154. writable = m.RW
  155. }
  156. mounts = append(mounts, Mount{
  157. Source: container.HostsPath,
  158. Destination: "/etc/hosts",
  159. Writable: writable,
  160. Propagation: string(volume.DefaultPropagationMode),
  161. })
  162. }
  163. }
  164. return mounts
  165. }
  166. // SecretMountPath returns the path of the secret mount for the container
  167. func (container *Container) SecretMountPath() string {
  168. return filepath.Join(container.Root, "secrets")
  169. }
  170. // CopyImagePathContent copies files in destination to the volume.
  171. func (container *Container) CopyImagePathContent(v volume.Volume, destination string) error {
  172. rootfs, err := symlink.FollowSymlinkInScope(filepath.Join(container.BaseFS, destination), container.BaseFS)
  173. if err != nil {
  174. return err
  175. }
  176. if _, err = ioutil.ReadDir(rootfs); err != nil {
  177. if os.IsNotExist(err) {
  178. return nil
  179. }
  180. return err
  181. }
  182. id := stringid.GenerateNonCryptoID()
  183. path, err := v.Mount(id)
  184. if err != nil {
  185. return err
  186. }
  187. defer func() {
  188. if err := v.Unmount(id); err != nil {
  189. logrus.Warnf("error while unmounting volume %s: %v", v.Name(), err)
  190. }
  191. }()
  192. if err := label.Relabel(path, container.MountLabel, true); err != nil && err != unix.ENOTSUP {
  193. return err
  194. }
  195. return copyExistingContents(rootfs, path)
  196. }
  197. // ShmResourcePath returns path to shm
  198. func (container *Container) ShmResourcePath() (string, error) {
  199. return container.GetRootResourcePath("shm")
  200. }
  201. // HasMountFor checks if path is a mountpoint
  202. func (container *Container) HasMountFor(path string) bool {
  203. _, exists := container.MountPoints[path]
  204. return exists
  205. }
  206. // UnmountIpcMounts uses the provided unmount function to unmount shm and mqueue if they were mounted
  207. func (container *Container) UnmountIpcMounts(unmount func(pth string) error) {
  208. if container.HostConfig.IpcMode.IsContainer() || container.HostConfig.IpcMode.IsHost() {
  209. return
  210. }
  211. var warnings []string
  212. if !container.HasMountFor("/dev/shm") {
  213. shmPath, err := container.ShmResourcePath()
  214. if err != nil {
  215. logrus.Error(err)
  216. warnings = append(warnings, err.Error())
  217. } else if shmPath != "" {
  218. if err := unmount(shmPath); err != nil && !os.IsNotExist(err) {
  219. warnings = append(warnings, fmt.Sprintf("failed to umount %s: %v", shmPath, err))
  220. }
  221. }
  222. }
  223. if len(warnings) > 0 {
  224. logrus.Warnf("failed to cleanup ipc mounts:\n%v", strings.Join(warnings, "\n"))
  225. }
  226. }
  227. // IpcMounts returns the list of IPC mounts
  228. func (container *Container) IpcMounts() []Mount {
  229. var mounts []Mount
  230. if !container.HasMountFor("/dev/shm") {
  231. label.SetFileLabel(container.ShmPath, container.MountLabel)
  232. mounts = append(mounts, Mount{
  233. Source: container.ShmPath,
  234. Destination: "/dev/shm",
  235. Writable: true,
  236. Propagation: string(volume.DefaultPropagationMode),
  237. })
  238. }
  239. return mounts
  240. }
  241. // SecretMount returns the list of Secret mounts
  242. func (container *Container) SecretMount() Mount {
  243. var mount Mount
  244. if len(container.Secrets) > 0 {
  245. mount = Mount{
  246. Source: container.SecretMountPath(),
  247. Destination: containerSecretMountPath,
  248. Writable: false,
  249. }
  250. }
  251. return mount
  252. }
  253. // UnmountSecrets unmounts the local tmpfs for secrets
  254. func (container *Container) UnmountSecrets() error {
  255. return detachMounted(container.SecretMountPath())
  256. }
  257. // UpdateContainer updates configuration of a container.
  258. func (container *Container) UpdateContainer(hostConfig *containertypes.HostConfig) error {
  259. container.Lock()
  260. defer container.Unlock()
  261. // update resources of container
  262. resources := hostConfig.Resources
  263. cResources := &container.HostConfig.Resources
  264. if resources.BlkioWeight != 0 {
  265. cResources.BlkioWeight = resources.BlkioWeight
  266. }
  267. if resources.CPUShares != 0 {
  268. cResources.CPUShares = resources.CPUShares
  269. }
  270. if resources.CPUPeriod != 0 {
  271. cResources.CPUPeriod = resources.CPUPeriod
  272. }
  273. if resources.CPUQuota != 0 {
  274. cResources.CPUQuota = resources.CPUQuota
  275. }
  276. if resources.CpusetCpus != "" {
  277. cResources.CpusetCpus = resources.CpusetCpus
  278. }
  279. if resources.CpusetMems != "" {
  280. cResources.CpusetMems = resources.CpusetMems
  281. }
  282. if resources.Memory != 0 {
  283. // if memory limit smaller than already set memoryswap limit and doesn't
  284. // update the memoryswap limit, then error out.
  285. if resources.Memory > cResources.MemorySwap && resources.MemorySwap == 0 {
  286. return fmt.Errorf("Memory limit should be smaller than already set memoryswap limit, update the memoryswap at the same time")
  287. }
  288. cResources.Memory = resources.Memory
  289. }
  290. if resources.MemorySwap != 0 {
  291. cResources.MemorySwap = resources.MemorySwap
  292. }
  293. if resources.MemoryReservation != 0 {
  294. cResources.MemoryReservation = resources.MemoryReservation
  295. }
  296. if resources.KernelMemory != 0 {
  297. cResources.KernelMemory = resources.KernelMemory
  298. }
  299. // update HostConfig of container
  300. if hostConfig.RestartPolicy.Name != "" {
  301. if container.HostConfig.AutoRemove && !hostConfig.RestartPolicy.IsNone() {
  302. return fmt.Errorf("Restart policy cannot be updated because AutoRemove is enabled for the container")
  303. }
  304. container.HostConfig.RestartPolicy = hostConfig.RestartPolicy
  305. }
  306. if err := container.ToDisk(); err != nil {
  307. logrus.Errorf("Error saving updated container: %v", err)
  308. return err
  309. }
  310. return nil
  311. }
  312. // UnmountVolumes unmounts all volumes
  313. func (container *Container) UnmountVolumes(forceSyscall bool, volumeEventLog func(name, action string, attributes map[string]string)) error {
  314. var (
  315. volumeMounts []volume.MountPoint
  316. err error
  317. )
  318. for _, mntPoint := range container.MountPoints {
  319. dest, err := container.GetResourcePath(mntPoint.Destination)
  320. if err != nil {
  321. return err
  322. }
  323. volumeMounts = append(volumeMounts, volume.MountPoint{Destination: dest, Volume: mntPoint.Volume, ID: mntPoint.ID})
  324. }
  325. // Append any network mounts to the list (this is a no-op on Windows)
  326. if volumeMounts, err = appendNetworkMounts(container, volumeMounts); err != nil {
  327. return err
  328. }
  329. for _, volumeMount := range volumeMounts {
  330. if forceSyscall {
  331. if err := detachMounted(volumeMount.Destination); err != nil {
  332. logrus.Warnf("%s unmountVolumes: Failed to do lazy umount %v", container.ID, err)
  333. }
  334. }
  335. if volumeMount.Volume != nil {
  336. if err := volumeMount.Volume.Unmount(volumeMount.ID); err != nil {
  337. return err
  338. }
  339. volumeMount.ID = ""
  340. attributes := map[string]string{
  341. "driver": volumeMount.Volume.DriverName(),
  342. "container": container.ID,
  343. }
  344. volumeEventLog(volumeMount.Volume.Name(), "unmount", attributes)
  345. }
  346. }
  347. return nil
  348. }
  349. // copyExistingContents copies from the source to the destination and
  350. // ensures the ownership is appropriately set.
  351. func copyExistingContents(source, destination string) error {
  352. volList, err := ioutil.ReadDir(source)
  353. if err != nil {
  354. return err
  355. }
  356. if len(volList) > 0 {
  357. srcList, err := ioutil.ReadDir(destination)
  358. if err != nil {
  359. return err
  360. }
  361. if len(srcList) == 0 {
  362. // If the source volume is empty, copies files from the root into the volume
  363. if err := chrootarchive.CopyWithTar(source, destination); err != nil {
  364. return err
  365. }
  366. }
  367. }
  368. return copyOwnership(source, destination)
  369. }
  370. // copyOwnership copies the permissions and uid:gid of the source file
  371. // to the destination file
  372. func copyOwnership(source, destination string) error {
  373. stat, err := system.Stat(source)
  374. if err != nil {
  375. return err
  376. }
  377. if err := os.Chown(destination, int(stat.UID()), int(stat.GID())); err != nil {
  378. return err
  379. }
  380. return os.Chmod(destination, os.FileMode(stat.Mode()))
  381. }
  382. // TmpfsMounts returns the list of tmpfs mounts
  383. func (container *Container) TmpfsMounts() ([]Mount, error) {
  384. var mounts []Mount
  385. for dest, data := range container.HostConfig.Tmpfs {
  386. mounts = append(mounts, Mount{
  387. Source: "tmpfs",
  388. Destination: dest,
  389. Data: data,
  390. })
  391. }
  392. for dest, mnt := range container.MountPoints {
  393. if mnt.Type == mounttypes.TypeTmpfs {
  394. data, err := volume.ConvertTmpfsOptions(mnt.Spec.TmpfsOptions, mnt.Spec.ReadOnly)
  395. if err != nil {
  396. return nil, err
  397. }
  398. mounts = append(mounts, Mount{
  399. Source: "tmpfs",
  400. Destination: dest,
  401. Data: data,
  402. })
  403. }
  404. }
  405. return mounts, nil
  406. }
  407. // cleanResourcePath cleans a resource path and prepares to combine with mnt path
  408. func cleanResourcePath(path string) string {
  409. return filepath.Join(string(os.PathSeparator), path)
  410. }
  411. // canMountFS determines if the file system for the container
  412. // can be mounted locally. A no-op on non-Windows platforms
  413. func (container *Container) canMountFS() bool {
  414. return true
  415. }
  416. // EnableServiceDiscoveryOnDefaultNetwork Enable service discovery on default network
  417. func (container *Container) EnableServiceDiscoveryOnDefaultNetwork() bool {
  418. return false
  419. }