container_unix.go 12 KB

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