container_unix.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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. // if a domain name was specified, append it to the hostname (see #7851)
  41. fullHostname := container.Config.Hostname
  42. if container.Config.Domainname != "" {
  43. fullHostname = fmt.Sprintf("%s.%s", fullHostname, container.Config.Domainname)
  44. }
  45. // Setup environment
  46. env := []string{
  47. "PATH=" + system.DefaultPathEnv,
  48. "HOSTNAME=" + fullHostname,
  49. }
  50. if container.Config.Tty {
  51. env = append(env, "TERM=xterm")
  52. }
  53. env = append(env, linkedEnv...)
  54. // because the env on the container can override certain default values
  55. // we need to replace the 'env' keys where they match and append anything
  56. // else.
  57. env = utils.ReplaceOrAppendEnvValues(env, container.Config.Env)
  58. return env
  59. }
  60. // TrySetNetworkMount attempts to set the network mounts given a provided destination and
  61. // the path to use for it; return true if the given destination was a network mount file
  62. func (container *Container) TrySetNetworkMount(destination string, path string) bool {
  63. if destination == "/etc/resolv.conf" {
  64. container.ResolvConfPath = path
  65. return true
  66. }
  67. if destination == "/etc/hostname" {
  68. container.HostnamePath = path
  69. return true
  70. }
  71. if destination == "/etc/hosts" {
  72. container.HostsPath = path
  73. return true
  74. }
  75. return false
  76. }
  77. // BuildHostnameFile writes the container's hostname file.
  78. func (container *Container) BuildHostnameFile() error {
  79. hostnamePath, err := container.GetRootResourcePath("hostname")
  80. if err != nil {
  81. return err
  82. }
  83. container.HostnamePath = hostnamePath
  84. if container.Config.Domainname != "" {
  85. return ioutil.WriteFile(container.HostnamePath, []byte(fmt.Sprintf("%s.%s\n", container.Config.Hostname, container.Config.Domainname)), 0644)
  86. }
  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() []execdriver.Mount {
  102. var mounts []execdriver.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. label.Relabel(container.ResolvConfPath, container.MountLabel, shared)
  109. writable := !container.HostConfig.ReadonlyRootfs
  110. if m, exists := container.MountPoints["/etc/resolv.conf"]; exists {
  111. writable = m.RW
  112. }
  113. mounts = append(mounts, execdriver.Mount{
  114. Source: container.ResolvConfPath,
  115. Destination: "/etc/resolv.conf",
  116. Writable: writable,
  117. Propagation: volume.DefaultPropagationMode,
  118. })
  119. }
  120. }
  121. if container.HostnamePath != "" {
  122. if _, err := os.Stat(container.HostnamePath); err != nil {
  123. logrus.Warnf("HostnamePath set to %q, but can't stat this filename (err = %v); skipping", container.HostnamePath, err)
  124. } else {
  125. label.Relabel(container.HostnamePath, container.MountLabel, shared)
  126. writable := !container.HostConfig.ReadonlyRootfs
  127. if m, exists := container.MountPoints["/etc/hostname"]; exists {
  128. writable = m.RW
  129. }
  130. mounts = append(mounts, execdriver.Mount{
  131. Source: container.HostnamePath,
  132. Destination: "/etc/hostname",
  133. Writable: writable,
  134. Propagation: volume.DefaultPropagationMode,
  135. })
  136. }
  137. }
  138. if container.HostsPath != "" {
  139. if _, err := os.Stat(container.HostsPath); err != nil {
  140. logrus.Warnf("HostsPath set to %q, but can't stat this filename (err = %v); skipping", container.HostsPath, err)
  141. } else {
  142. label.Relabel(container.HostsPath, container.MountLabel, shared)
  143. writable := !container.HostConfig.ReadonlyRootfs
  144. if m, exists := container.MountPoints["/etc/hosts"]; exists {
  145. writable = m.RW
  146. }
  147. mounts = append(mounts, execdriver.Mount{
  148. Source: container.HostsPath,
  149. Destination: "/etc/hosts",
  150. Writable: writable,
  151. Propagation: volume.DefaultPropagationMode,
  152. })
  153. }
  154. }
  155. return mounts
  156. }
  157. // CopyImagePathContent copies files in destination to the volume.
  158. func (container *Container) CopyImagePathContent(v volume.Volume, destination string) error {
  159. rootfs, err := symlink.FollowSymlinkInScope(filepath.Join(container.BaseFS, destination), container.BaseFS)
  160. if err != nil {
  161. return err
  162. }
  163. if _, err = ioutil.ReadDir(rootfs); err != nil {
  164. if os.IsNotExist(err) {
  165. return nil
  166. }
  167. return err
  168. }
  169. path, err := v.Mount()
  170. if err != nil {
  171. return err
  172. }
  173. if err := copyExistingContents(rootfs, path); err != nil {
  174. return err
  175. }
  176. return v.Unmount()
  177. }
  178. // ShmResourcePath returns path to shm
  179. func (container *Container) ShmResourcePath() (string, error) {
  180. return container.GetRootResourcePath("shm")
  181. }
  182. // HasMountFor checks if path is a mountpoint
  183. func (container *Container) HasMountFor(path string) bool {
  184. _, exists := container.MountPoints[path]
  185. return exists
  186. }
  187. // UnmountIpcMounts uses the provided unmount function to unmount shm and mqueue if they were mounted
  188. func (container *Container) UnmountIpcMounts(unmount func(pth string) error) {
  189. if container.HostConfig.IpcMode.IsContainer() || container.HostConfig.IpcMode.IsHost() {
  190. return
  191. }
  192. var warnings []string
  193. if !container.HasMountFor("/dev/shm") {
  194. shmPath, err := container.ShmResourcePath()
  195. if err != nil {
  196. logrus.Error(err)
  197. warnings = append(warnings, err.Error())
  198. } else if shmPath != "" {
  199. if err := unmount(shmPath); err != nil {
  200. warnings = append(warnings, fmt.Sprintf("failed to umount %s: %v", shmPath, err))
  201. }
  202. }
  203. }
  204. if len(warnings) > 0 {
  205. logrus.Warnf("failed to cleanup ipc mounts:\n%v", strings.Join(warnings, "\n"))
  206. }
  207. }
  208. // IpcMounts returns the list of IPC mounts
  209. func (container *Container) IpcMounts() []execdriver.Mount {
  210. var mounts []execdriver.Mount
  211. if !container.HasMountFor("/dev/shm") {
  212. label.SetFileLabel(container.ShmPath, container.MountLabel)
  213. mounts = append(mounts, execdriver.Mount{
  214. Source: container.ShmPath,
  215. Destination: "/dev/shm",
  216. Writable: true,
  217. Propagation: volume.DefaultPropagationMode,
  218. })
  219. }
  220. return mounts
  221. }
  222. func updateCommand(c *execdriver.Command, resources containertypes.Resources) {
  223. c.Resources.BlkioWeight = resources.BlkioWeight
  224. c.Resources.CPUShares = resources.CPUShares
  225. c.Resources.CPUPeriod = resources.CPUPeriod
  226. c.Resources.CPUQuota = resources.CPUQuota
  227. c.Resources.CpusetCpus = resources.CpusetCpus
  228. c.Resources.CpusetMems = resources.CpusetMems
  229. c.Resources.Memory = resources.Memory
  230. c.Resources.MemorySwap = resources.MemorySwap
  231. c.Resources.MemoryReservation = resources.MemoryReservation
  232. c.Resources.KernelMemory = resources.KernelMemory
  233. }
  234. // UpdateContainer updates configuration of a container.
  235. func (container *Container) UpdateContainer(hostConfig *containertypes.HostConfig) error {
  236. container.Lock()
  237. // update resources of container
  238. resources := hostConfig.Resources
  239. cResources := &container.HostConfig.Resources
  240. if resources.BlkioWeight != 0 {
  241. cResources.BlkioWeight = resources.BlkioWeight
  242. }
  243. if resources.CPUShares != 0 {
  244. cResources.CPUShares = resources.CPUShares
  245. }
  246. if resources.CPUPeriod != 0 {
  247. cResources.CPUPeriod = resources.CPUPeriod
  248. }
  249. if resources.CPUQuota != 0 {
  250. cResources.CPUQuota = resources.CPUQuota
  251. }
  252. if resources.CpusetCpus != "" {
  253. cResources.CpusetCpus = resources.CpusetCpus
  254. }
  255. if resources.CpusetMems != "" {
  256. cResources.CpusetMems = resources.CpusetMems
  257. }
  258. if resources.Memory != 0 {
  259. cResources.Memory = resources.Memory
  260. }
  261. if resources.MemorySwap != 0 {
  262. cResources.MemorySwap = resources.MemorySwap
  263. }
  264. if resources.MemoryReservation != 0 {
  265. cResources.MemoryReservation = resources.MemoryReservation
  266. }
  267. if resources.KernelMemory != 0 {
  268. cResources.KernelMemory = resources.KernelMemory
  269. }
  270. // update HostConfig of container
  271. if hostConfig.RestartPolicy.Name != "" {
  272. container.HostConfig.RestartPolicy = hostConfig.RestartPolicy
  273. }
  274. container.Unlock()
  275. // If container is not running, update hostConfig struct is enough,
  276. // resources will be updated when the container is started again.
  277. // If container is running (including paused), we need to update
  278. // the command so we can update configs to the real world.
  279. if container.IsRunning() {
  280. container.Lock()
  281. updateCommand(container.Command, *cResources)
  282. container.Unlock()
  283. }
  284. if err := container.ToDiskLocking(); err != nil {
  285. logrus.Errorf("Error saving updated container: %v", err)
  286. return err
  287. }
  288. return nil
  289. }
  290. func detachMounted(path string) error {
  291. return syscall.Unmount(path, syscall.MNT_DETACH)
  292. }
  293. // UnmountVolumes unmounts all volumes
  294. func (container *Container) UnmountVolumes(forceSyscall bool, volumeEventLog func(name, action string, attributes map[string]string)) error {
  295. var (
  296. volumeMounts []volume.MountPoint
  297. err error
  298. )
  299. for _, mntPoint := range container.MountPoints {
  300. dest, err := container.GetResourcePath(mntPoint.Destination)
  301. if err != nil {
  302. return err
  303. }
  304. volumeMounts = append(volumeMounts, volume.MountPoint{Destination: dest, Volume: mntPoint.Volume})
  305. }
  306. // Append any network mounts to the list (this is a no-op on Windows)
  307. if volumeMounts, err = appendNetworkMounts(container, volumeMounts); err != nil {
  308. return err
  309. }
  310. for _, volumeMount := range volumeMounts {
  311. if forceSyscall {
  312. if err := detachMounted(volumeMount.Destination); err != nil {
  313. logrus.Warnf("%s unmountVolumes: Failed to do lazy umount %v", container.ID, err)
  314. }
  315. }
  316. if volumeMount.Volume != nil {
  317. if err := volumeMount.Volume.Unmount(); err != nil {
  318. return err
  319. }
  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() []execdriver.Mount {
  364. var mounts []execdriver.Mount
  365. for dest, data := range container.HostConfig.Tmpfs {
  366. mounts = append(mounts, execdriver.Mount{
  367. Source: "tmpfs",
  368. Destination: dest,
  369. Data: data,
  370. })
  371. }
  372. return mounts
  373. }
  374. // cleanResourcePath cleans a resource path and prepares to combine with mnt path
  375. func cleanResourcePath(path string) string {
  376. return filepath.Join(string(os.PathSeparator), path)
  377. }
  378. // canMountFS determines if the file system for the container
  379. // can be mounted locally. A no-op on non-Windows platforms
  380. func (container *Container) canMountFS() bool {
  381. return true
  382. }