container_unix.go 13 KB

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