PageRenderTime 41ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/container/container_unix.go

https://gitlab.com/vectorci/docker-1
Go | 424 lines | 333 code | 49 blank | 42 comment | 111 complexity | 9af5404528d65bd712e5695456f663a4 MD5 | raw file
  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. "github.com/docker/docker/pkg/chrootarchive"
  12. "github.com/docker/docker/pkg/stringid"
  13. "github.com/docker/docker/pkg/symlink"
  14. "github.com/docker/docker/pkg/system"
  15. "github.com/docker/docker/utils"
  16. "github.com/docker/docker/volume"
  17. containertypes "github.com/docker/engine-api/types/container"
  18. "github.com/opencontainers/runc/libcontainer/label"
  19. )
  20. // DefaultSHMSize is the default size (64MB) of the SHM which will be mounted in the container
  21. const DefaultSHMSize int64 = 67108864
  22. // Container holds the fields specific to unixen implementations.
  23. // See CommonContainer for standard fields common to all containers.
  24. type Container struct {
  25. CommonContainer
  26. // Fields below here are platform specific.
  27. AppArmorProfile string
  28. HostnamePath string
  29. HostsPath string
  30. ShmPath string
  31. ResolvConfPath string
  32. SeccompProfile string
  33. NoNewPrivileges bool
  34. }
  35. // ExitStatus provides exit reasons for a container.
  36. type ExitStatus struct {
  37. // The exit code with which the container exited.
  38. ExitCode int
  39. // Whether the container encountered an OOM.
  40. OOMKilled bool
  41. }
  42. // CreateDaemonEnvironment returns the list of all environment variables given the list of
  43. // environment variables related to links.
  44. // Sets PATH, HOSTNAME and if container.Config.Tty is set: TERM.
  45. // The defaults set here do not override the values in container.Config.Env
  46. func (container *Container) CreateDaemonEnvironment(linkedEnv []string) []string {
  47. // Setup environment
  48. env := []string{
  49. "PATH=" + system.DefaultPathEnv,
  50. "HOSTNAME=" + container.Config.Hostname,
  51. }
  52. if container.Config.Tty {
  53. env = append(env, "TERM=xterm")
  54. }
  55. env = append(env, linkedEnv...)
  56. // because the env on the container can override certain default values
  57. // we need to replace the 'env' keys where they match and append anything
  58. // else.
  59. env = utils.ReplaceOrAppendEnvValues(env, container.Config.Env)
  60. return env
  61. }
  62. // TrySetNetworkMount attempts to set the network mounts given a provided destination and
  63. // the path to use for it; return true if the given destination was a network mount file
  64. func (container *Container) TrySetNetworkMount(destination string, path string) bool {
  65. if destination == "/etc/resolv.conf" {
  66. container.ResolvConfPath = path
  67. return true
  68. }
  69. if destination == "/etc/hostname" {
  70. container.HostnamePath = path
  71. return true
  72. }
  73. if destination == "/etc/hosts" {
  74. container.HostsPath = path
  75. return true
  76. }
  77. return false
  78. }
  79. // BuildHostnameFile writes the container's hostname file.
  80. func (container *Container) BuildHostnameFile() error {
  81. hostnamePath, err := container.GetRootResourcePath("hostname")
  82. if err != nil {
  83. return err
  84. }
  85. container.HostnamePath = hostnamePath
  86. return ioutil.WriteFile(container.HostnamePath, []byte(container.Config.Hostname+"\n"), 0644)
  87. }
  88. // appendNetworkMounts appends any network mounts to the array of mount points passed in
  89. func appendNetworkMounts(container *Container, volumeMounts []volume.MountPoint) ([]volume.MountPoint, error) {
  90. for _, mnt := range container.NetworkMounts() {
  91. dest, err := container.GetResourcePath(mnt.Destination)
  92. if err != nil {
  93. return nil, err
  94. }
  95. volumeMounts = append(volumeMounts, volume.MountPoint{Destination: dest})
  96. }
  97. return volumeMounts, nil
  98. }
  99. // NetworkMounts returns the list of network mounts.
  100. func (container *Container) NetworkMounts() []Mount {
  101. var mounts []Mount
  102. shared := container.HostConfig.NetworkMode.IsContainer()
  103. if container.ResolvConfPath != "" {
  104. if _, err := os.Stat(container.ResolvConfPath); err != nil {
  105. logrus.Warnf("ResolvConfPath set to %q, but can't stat this filename (err = %v); skipping", container.ResolvConfPath, err)
  106. } else {
  107. if !container.HasMountFor("/etc/resolv.conf") {
  108. label.Relabel(container.ResolvConfPath, container.MountLabel, shared)
  109. }
  110. writable := !container.HostConfig.ReadonlyRootfs
  111. if m, exists := container.MountPoints["/etc/resolv.conf"]; exists {
  112. writable = m.RW
  113. }
  114. mounts = append(mounts, Mount{
  115. Source: container.ResolvConfPath,
  116. Destination: "/etc/resolv.conf",
  117. Writable: writable,
  118. Propagation: volume.DefaultPropagationMode,
  119. })
  120. }
  121. }
  122. if container.HostnamePath != "" {
  123. if _, err := os.Stat(container.HostnamePath); err != nil {
  124. logrus.Warnf("HostnamePath set to %q, but can't stat this filename (err = %v); skipping", container.HostnamePath, err)
  125. } else {
  126. if !container.HasMountFor("/etc/hostname") {
  127. label.Relabel(container.HostnamePath, container.MountLabel, shared)
  128. }
  129. writable := !container.HostConfig.ReadonlyRootfs
  130. if m, exists := container.MountPoints["/etc/hostname"]; exists {
  131. writable = m.RW
  132. }
  133. mounts = append(mounts, Mount{
  134. Source: container.HostnamePath,
  135. Destination: "/etc/hostname",
  136. Writable: writable,
  137. Propagation: volume.DefaultPropagationMode,
  138. })
  139. }
  140. }
  141. if container.HostsPath != "" {
  142. if _, err := os.Stat(container.HostsPath); err != nil {
  143. logrus.Warnf("HostsPath set to %q, but can't stat this filename (err = %v); skipping", container.HostsPath, err)
  144. } else {
  145. if !container.HasMountFor("/etc/hosts") {
  146. label.Relabel(container.HostsPath, container.MountLabel, shared)
  147. }
  148. writable := !container.HostConfig.ReadonlyRootfs
  149. if m, exists := container.MountPoints["/etc/hosts"]; exists {
  150. writable = m.RW
  151. }
  152. mounts = append(mounts, Mount{
  153. Source: container.HostsPath,
  154. Destination: "/etc/hosts",
  155. Writable: writable,
  156. Propagation: volume.DefaultPropagationMode,
  157. })
  158. }
  159. }
  160. return mounts
  161. }
  162. // CopyImagePathContent copies files in destination to the volume.
  163. func (container *Container) CopyImagePathContent(v volume.Volume, destination string) error {
  164. rootfs, err := symlink.FollowSymlinkInScope(filepath.Join(container.BaseFS, destination), container.BaseFS)
  165. if err != nil {
  166. return err
  167. }
  168. if _, err = ioutil.ReadDir(rootfs); err != nil {
  169. if os.IsNotExist(err) {
  170. return nil
  171. }
  172. return err
  173. }
  174. id := stringid.GenerateNonCryptoID()
  175. path, err := v.Mount(id)
  176. if err != nil {
  177. return err
  178. }
  179. defer func() {
  180. if err := v.Unmount(id); err != nil {
  181. logrus.Warnf("error while unmounting volume %s: %v", v.Name(), err)
  182. }
  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: volume.DefaultPropagationMode,
  226. })
  227. }
  228. return mounts
  229. }
  230. // UpdateContainer updates configuration of a container.
  231. func (container *Container) UpdateContainer(hostConfig *containertypes.HostConfig) error {
  232. container.Lock()
  233. defer container.Unlock()
  234. // update resources of container
  235. resources := hostConfig.Resources
  236. cResources := &container.HostConfig.Resources
  237. if resources.BlkioWeight != 0 {
  238. cResources.BlkioWeight = resources.BlkioWeight
  239. }
  240. if resources.CPUShares != 0 {
  241. cResources.CPUShares = resources.CPUShares
  242. }
  243. if resources.CPUPeriod != 0 {
  244. cResources.CPUPeriod = resources.CPUPeriod
  245. }
  246. if resources.CPUQuota != 0 {
  247. cResources.CPUQuota = resources.CPUQuota
  248. }
  249. if resources.CpusetCpus != "" {
  250. cResources.CpusetCpus = resources.CpusetCpus
  251. }
  252. if resources.CpusetMems != "" {
  253. cResources.CpusetMems = resources.CpusetMems
  254. }
  255. if resources.Memory != 0 {
  256. // if memory limit smaller than already set memoryswap limit and doesn't
  257. // update the memoryswap limit, then error out.
  258. if resources.Memory > cResources.MemorySwap && resources.MemorySwap == 0 {
  259. return fmt.Errorf("Memory limit should be smaller than already set memoryswap limit, update the memoryswap at the same time")
  260. }
  261. cResources.Memory = resources.Memory
  262. }
  263. if resources.MemorySwap != 0 {
  264. cResources.MemorySwap = resources.MemorySwap
  265. }
  266. if resources.MemoryReservation != 0 {
  267. cResources.MemoryReservation = resources.MemoryReservation
  268. }
  269. if resources.KernelMemory != 0 {
  270. cResources.KernelMemory = resources.KernelMemory
  271. }
  272. // update HostConfig of container
  273. if hostConfig.RestartPolicy.Name != "" {
  274. container.HostConfig.RestartPolicy = hostConfig.RestartPolicy
  275. }
  276. if err := container.ToDisk(); err != nil {
  277. logrus.Errorf("Error saving updated container: %v", err)
  278. return err
  279. }
  280. return nil
  281. }
  282. func detachMounted(path string) error {
  283. return syscall.Unmount(path, syscall.MNT_DETACH)
  284. }
  285. // UnmountVolumes unmounts all volumes
  286. func (container *Container) UnmountVolumes(forceSyscall bool, volumeEventLog func(name, action string, attributes map[string]string)) error {
  287. var (
  288. volumeMounts []volume.MountPoint
  289. err error
  290. )
  291. for _, mntPoint := range container.MountPoints {
  292. dest, err := container.GetResourcePath(mntPoint.Destination)
  293. if err != nil {
  294. return err
  295. }
  296. volumeMounts = append(volumeMounts, volume.MountPoint{Destination: dest, Volume: mntPoint.Volume, ID: mntPoint.ID})
  297. }
  298. // Append any network mounts to the list (this is a no-op on Windows)
  299. if volumeMounts, err = appendNetworkMounts(container, volumeMounts); err != nil {
  300. return err
  301. }
  302. for _, volumeMount := range volumeMounts {
  303. if forceSyscall {
  304. if err := detachMounted(volumeMount.Destination); err != nil {
  305. logrus.Warnf("%s unmountVolumes: Failed to do lazy umount %v", container.ID, err)
  306. }
  307. }
  308. if volumeMount.Volume != nil {
  309. if err := volumeMount.Volume.Unmount(volumeMount.ID); err != nil {
  310. return err
  311. }
  312. volumeMount.ID = ""
  313. attributes := map[string]string{
  314. "driver": volumeMount.Volume.DriverName(),
  315. "container": container.ID,
  316. }
  317. volumeEventLog(volumeMount.Volume.Name(), "unmount", attributes)
  318. }
  319. }
  320. return nil
  321. }
  322. // copyExistingContents copies from the source to the destination and
  323. // ensures the ownership is appropriately set.
  324. func copyExistingContents(source, destination string) error {
  325. volList, err := ioutil.ReadDir(source)
  326. if err != nil {
  327. return err
  328. }
  329. if len(volList) > 0 {
  330. srcList, err := ioutil.ReadDir(destination)
  331. if err != nil {
  332. return err
  333. }
  334. if len(srcList) == 0 {
  335. // If the source volume is empty, copies files from the root into the volume
  336. if err := chrootarchive.CopyWithTar(source, destination); err != nil {
  337. return err
  338. }
  339. }
  340. }
  341. return copyOwnership(source, destination)
  342. }
  343. // copyOwnership copies the permissions and uid:gid of the source file
  344. // to the destination file
  345. func copyOwnership(source, destination string) error {
  346. stat, err := system.Stat(source)
  347. if err != nil {
  348. return err
  349. }
  350. if err := os.Chown(destination, int(stat.UID()), int(stat.GID())); err != nil {
  351. return err
  352. }
  353. return os.Chmod(destination, os.FileMode(stat.Mode()))
  354. }
  355. // TmpfsMounts returns the list of tmpfs mounts
  356. func (container *Container) TmpfsMounts() []Mount {
  357. var mounts []Mount
  358. for dest, data := range container.HostConfig.Tmpfs {
  359. mounts = append(mounts, Mount{
  360. Source: "tmpfs",
  361. Destination: dest,
  362. Data: data,
  363. })
  364. }
  365. return mounts
  366. }
  367. // cleanResourcePath cleans a resource path and prepares to combine with mnt path
  368. func cleanResourcePath(path string) string {
  369. return filepath.Join(string(os.PathSeparator), path)
  370. }
  371. // canMountFS determines if the file system for the container
  372. // can be mounted locally. A no-op on non-Windows platforms
  373. func (container *Container) canMountFS() bool {
  374. return true
  375. }