container_unix.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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/daemon/execdriver"
  12. "github.com/docker/docker/pkg/chrootarchive"
  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. // CreateDaemonEnvironment returns the list of all environment variables given the list of
  36. // environment variables related to links.
  37. // Sets PATH, HOSTNAME and if container.Config.Tty is set: TERM.
  38. // The defaults set here do not override the values in container.Config.Env
  39. func (container *Container) CreateDaemonEnvironment(linkedEnv []string) []string {
  40. // Setup environment
  41. env := []string{
  42. "PATH=" + system.DefaultPathEnv,
  43. "HOSTNAME=" + container.Config.Hostname,
  44. }
  45. if container.Config.Tty {
  46. env = append(env, "TERM=xterm")
  47. }
  48. env = append(env, linkedEnv...)
  49. // because the env on the container can override certain default values
  50. // we need to replace the 'env' keys where they match and append anything
  51. // else.
  52. env = utils.ReplaceOrAppendEnvValues(env, container.Config.Env)
  53. return env
  54. }
  55. // TrySetNetworkMount attempts to set the network mounts given a provided destination and
  56. // the path to use for it; return true if the given destination was a network mount file
  57. func (container *Container) TrySetNetworkMount(destination string, path string) bool {
  58. if destination == "/etc/resolv.conf" {
  59. container.ResolvConfPath = path
  60. return true
  61. }
  62. if destination == "/etc/hostname" {
  63. container.HostnamePath = path
  64. return true
  65. }
  66. if destination == "/etc/hosts" {
  67. container.HostsPath = path
  68. return true
  69. }
  70. return false
  71. }
  72. // BuildHostnameFile writes the container's hostname file.
  73. func (container *Container) BuildHostnameFile() error {
  74. hostnamePath, err := container.GetRootResourcePath("hostname")
  75. if err != nil {
  76. return err
  77. }
  78. container.HostnamePath = hostnamePath
  79. return ioutil.WriteFile(container.HostnamePath, []byte(container.Config.Hostname+"\n"), 0644)
  80. }
  81. // appendNetworkMounts appends any network mounts to the array of mount points passed in
  82. func appendNetworkMounts(container *Container, volumeMounts []volume.MountPoint) ([]volume.MountPoint, error) {
  83. for _, mnt := range container.NetworkMounts() {
  84. dest, err := container.GetResourcePath(mnt.Destination)
  85. if err != nil {
  86. return nil, err
  87. }
  88. volumeMounts = append(volumeMounts, volume.MountPoint{Destination: dest})
  89. }
  90. return volumeMounts, nil
  91. }
  92. // NetworkMounts returns the list of network mounts.
  93. func (container *Container) NetworkMounts() []execdriver.Mount {
  94. var mounts []execdriver.Mount
  95. shared := container.HostConfig.NetworkMode.IsContainer()
  96. if container.ResolvConfPath != "" {
  97. if _, err := os.Stat(container.ResolvConfPath); err != nil {
  98. logrus.Warnf("ResolvConfPath set to %q, but can't stat this filename (err = %v); skipping", container.ResolvConfPath, err)
  99. } else {
  100. label.Relabel(container.ResolvConfPath, container.MountLabel, shared)
  101. writable := !container.HostConfig.ReadonlyRootfs
  102. if m, exists := container.MountPoints["/etc/resolv.conf"]; exists {
  103. writable = m.RW
  104. }
  105. mounts = append(mounts, execdriver.Mount{
  106. Source: container.ResolvConfPath,
  107. Destination: "/etc/resolv.conf",
  108. Writable: writable,
  109. Propagation: volume.DefaultPropagationMode,
  110. })
  111. }
  112. }
  113. if container.HostnamePath != "" {
  114. if _, err := os.Stat(container.HostnamePath); err != nil {
  115. logrus.Warnf("HostnamePath set to %q, but can't stat this filename (err = %v); skipping", container.HostnamePath, err)
  116. } else {
  117. label.Relabel(container.HostnamePath, container.MountLabel, shared)
  118. writable := !container.HostConfig.ReadonlyRootfs
  119. if m, exists := container.MountPoints["/etc/hostname"]; exists {
  120. writable = m.RW
  121. }
  122. mounts = append(mounts, execdriver.Mount{
  123. Source: container.HostnamePath,
  124. Destination: "/etc/hostname",
  125. Writable: writable,
  126. Propagation: volume.DefaultPropagationMode,
  127. })
  128. }
  129. }
  130. if container.HostsPath != "" {
  131. if _, err := os.Stat(container.HostsPath); err != nil {
  132. logrus.Warnf("HostsPath set to %q, but can't stat this filename (err = %v); skipping", container.HostsPath, err)
  133. } else {
  134. label.Relabel(container.HostsPath, container.MountLabel, shared)
  135. writable := !container.HostConfig.ReadonlyRootfs
  136. if m, exists := container.MountPoints["/etc/hosts"]; exists {
  137. writable = m.RW
  138. }
  139. mounts = append(mounts, execdriver.Mount{
  140. Source: container.HostsPath,
  141. Destination: "/etc/hosts",
  142. Writable: writable,
  143. Propagation: volume.DefaultPropagationMode,
  144. })
  145. }
  146. }
  147. return mounts
  148. }
  149. // CopyImagePathContent copies files in destination to the volume.
  150. func (container *Container) CopyImagePathContent(v volume.Volume, destination string) error {
  151. rootfs, err := symlink.FollowSymlinkInScope(filepath.Join(container.BaseFS, destination), container.BaseFS)
  152. if err != nil {
  153. return err
  154. }
  155. if _, err = ioutil.ReadDir(rootfs); err != nil {
  156. if os.IsNotExist(err) {
  157. return nil
  158. }
  159. return err
  160. }
  161. path, err := v.Mount()
  162. if err != nil {
  163. return err
  164. }
  165. if err := copyExistingContents(rootfs, path); err != nil {
  166. return err
  167. }
  168. return v.Unmount()
  169. }
  170. // ShmResourcePath returns path to shm
  171. func (container *Container) ShmResourcePath() (string, error) {
  172. return container.GetRootResourcePath("shm")
  173. }
  174. // HasMountFor checks if path is a mountpoint
  175. func (container *Container) HasMountFor(path string) bool {
  176. _, exists := container.MountPoints[path]
  177. return exists
  178. }
  179. // UnmountIpcMounts uses the provided unmount function to unmount shm and mqueue if they were mounted
  180. func (container *Container) UnmountIpcMounts(unmount func(pth string) error) {
  181. if container.HostConfig.IpcMode.IsContainer() || container.HostConfig.IpcMode.IsHost() {
  182. return
  183. }
  184. var warnings []string
  185. if !container.HasMountFor("/dev/shm") {
  186. shmPath, err := container.ShmResourcePath()
  187. if err != nil {
  188. logrus.Error(err)
  189. warnings = append(warnings, err.Error())
  190. } else if shmPath != "" {
  191. if err := unmount(shmPath); err != nil {
  192. warnings = append(warnings, fmt.Sprintf("failed to umount %s: %v", shmPath, err))
  193. }
  194. }
  195. }
  196. if len(warnings) > 0 {
  197. logrus.Warnf("failed to cleanup ipc mounts:\n%v", strings.Join(warnings, "\n"))
  198. }
  199. }
  200. // IpcMounts returns the list of IPC mounts
  201. func (container *Container) IpcMounts() []execdriver.Mount {
  202. var mounts []execdriver.Mount
  203. if !container.HasMountFor("/dev/shm") {
  204. label.SetFileLabel(container.ShmPath, container.MountLabel)
  205. mounts = append(mounts, execdriver.Mount{
  206. Source: container.ShmPath,
  207. Destination: "/dev/shm",
  208. Writable: true,
  209. Propagation: volume.DefaultPropagationMode,
  210. })
  211. }
  212. return mounts
  213. }
  214. func updateCommand(c *execdriver.Command, resources containertypes.Resources) {
  215. c.Resources.BlkioWeight = resources.BlkioWeight
  216. c.Resources.CPUShares = resources.CPUShares
  217. c.Resources.CPUPeriod = resources.CPUPeriod
  218. c.Resources.CPUQuota = resources.CPUQuota
  219. c.Resources.CpusetCpus = resources.CpusetCpus
  220. c.Resources.CpusetMems = resources.CpusetMems
  221. c.Resources.Memory = resources.Memory
  222. c.Resources.MemorySwap = resources.MemorySwap
  223. c.Resources.MemoryReservation = resources.MemoryReservation
  224. c.Resources.KernelMemory = resources.KernelMemory
  225. }
  226. // UpdateContainer updates configuration of a container.
  227. func (container *Container) UpdateContainer(hostConfig *containertypes.HostConfig) error {
  228. container.Lock()
  229. // update resources of container
  230. resources := hostConfig.Resources
  231. cResources := &container.HostConfig.Resources
  232. if resources.BlkioWeight != 0 {
  233. cResources.BlkioWeight = resources.BlkioWeight
  234. }
  235. if resources.CPUShares != 0 {
  236. cResources.CPUShares = resources.CPUShares
  237. }
  238. if resources.CPUPeriod != 0 {
  239. cResources.CPUPeriod = resources.CPUPeriod
  240. }
  241. if resources.CPUQuota != 0 {
  242. cResources.CPUQuota = resources.CPUQuota
  243. }
  244. if resources.CpusetCpus != "" {
  245. cResources.CpusetCpus = resources.CpusetCpus
  246. }
  247. if resources.CpusetMems != "" {
  248. cResources.CpusetMems = resources.CpusetMems
  249. }
  250. if resources.Memory != 0 {
  251. cResources.Memory = resources.Memory
  252. }
  253. if resources.MemorySwap != 0 {
  254. cResources.MemorySwap = resources.MemorySwap
  255. }
  256. if resources.MemoryReservation != 0 {
  257. cResources.MemoryReservation = resources.MemoryReservation
  258. }
  259. if resources.KernelMemory != 0 {
  260. cResources.KernelMemory = resources.KernelMemory
  261. }
  262. // update HostConfig of container
  263. if hostConfig.RestartPolicy.Name != "" {
  264. container.HostConfig.RestartPolicy = hostConfig.RestartPolicy
  265. }
  266. container.Unlock()
  267. // If container is not running, update hostConfig struct is enough,
  268. // resources will be updated when the container is started again.
  269. // If container is running (including paused), we need to update
  270. // the command so we can update configs to the real world.
  271. if container.IsRunning() {
  272. container.Lock()
  273. updateCommand(container.Command, *cResources)
  274. container.Unlock()
  275. }
  276. if err := container.ToDiskLocking(); 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})
  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(); err != nil {
  310. return err
  311. }
  312. attributes := map[string]string{
  313. "driver": volumeMount.Volume.DriverName(),
  314. "container": container.ID,
  315. }
  316. volumeEventLog(volumeMount.Volume.Name(), "unmount", attributes)
  317. }
  318. }
  319. return nil
  320. }
  321. // copyExistingContents copies from the source to the destination and
  322. // ensures the ownership is appropriately set.
  323. func copyExistingContents(source, destination string) error {
  324. volList, err := ioutil.ReadDir(source)
  325. if err != nil {
  326. return err
  327. }
  328. if len(volList) > 0 {
  329. srcList, err := ioutil.ReadDir(destination)
  330. if err != nil {
  331. return err
  332. }
  333. if len(srcList) == 0 {
  334. // If the source volume is empty, copies files from the root into the volume
  335. if err := chrootarchive.CopyWithTar(source, destination); err != nil {
  336. return err
  337. }
  338. }
  339. }
  340. return copyOwnership(source, destination)
  341. }
  342. // copyOwnership copies the permissions and uid:gid of the source file
  343. // to the destination file
  344. func copyOwnership(source, destination string) error {
  345. stat, err := system.Stat(source)
  346. if err != nil {
  347. return err
  348. }
  349. if err := os.Chown(destination, int(stat.UID()), int(stat.GID())); err != nil {
  350. return err
  351. }
  352. return os.Chmod(destination, os.FileMode(stat.Mode()))
  353. }
  354. // TmpfsMounts returns the list of tmpfs mounts
  355. func (container *Container) TmpfsMounts() []execdriver.Mount {
  356. var mounts []execdriver.Mount
  357. for dest, data := range container.HostConfig.Tmpfs {
  358. mounts = append(mounts, execdriver.Mount{
  359. Source: "tmpfs",
  360. Destination: dest,
  361. Data: data,
  362. })
  363. }
  364. return mounts
  365. }
  366. // cleanResourcePath cleans a resource path and prepares to combine with mnt path
  367. func cleanResourcePath(path string) string {
  368. return filepath.Join(string(os.PathSeparator), path)
  369. }
  370. // canMountFS determines if the file system for the container
  371. // can be mounted locally. A no-op on non-Windows platforms
  372. func (container *Container) canMountFS() bool {
  373. return true
  374. }