container_unix.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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. if err := copyExistingContents(rootfs, path); err != nil {
  172. return err
  173. }
  174. return v.Unmount()
  175. }
  176. // ShmResourcePath returns path to shm
  177. func (container *Container) ShmResourcePath() (string, error) {
  178. return container.GetRootResourcePath("shm")
  179. }
  180. // HasMountFor checks if path is a mountpoint
  181. func (container *Container) HasMountFor(path string) bool {
  182. _, exists := container.MountPoints[path]
  183. return exists
  184. }
  185. // UnmountIpcMounts uses the provided unmount function to unmount shm and mqueue if they were mounted
  186. func (container *Container) UnmountIpcMounts(unmount func(pth string) error) {
  187. if container.HostConfig.IpcMode.IsContainer() || container.HostConfig.IpcMode.IsHost() {
  188. return
  189. }
  190. var warnings []string
  191. if !container.HasMountFor("/dev/shm") {
  192. shmPath, err := container.ShmResourcePath()
  193. if err != nil {
  194. logrus.Error(err)
  195. warnings = append(warnings, err.Error())
  196. } else if shmPath != "" {
  197. if err := unmount(shmPath); err != nil {
  198. warnings = append(warnings, fmt.Sprintf("failed to umount %s: %v", shmPath, err))
  199. }
  200. }
  201. }
  202. if len(warnings) > 0 {
  203. logrus.Warnf("failed to cleanup ipc mounts:\n%v", strings.Join(warnings, "\n"))
  204. }
  205. }
  206. // IpcMounts returns the list of IPC mounts
  207. func (container *Container) IpcMounts() []Mount {
  208. var mounts []Mount
  209. if !container.HasMountFor("/dev/shm") {
  210. label.SetFileLabel(container.ShmPath, container.MountLabel)
  211. mounts = append(mounts, Mount{
  212. Source: container.ShmPath,
  213. Destination: "/dev/shm",
  214. Writable: true,
  215. Propagation: volume.DefaultPropagationMode,
  216. })
  217. }
  218. return mounts
  219. }
  220. // UpdateContainer updates configuration of a container.
  221. func (container *Container) UpdateContainer(hostConfig *containertypes.HostConfig) error {
  222. container.Lock()
  223. defer container.Unlock()
  224. // update resources of container
  225. resources := hostConfig.Resources
  226. cResources := &container.HostConfig.Resources
  227. if resources.BlkioWeight != 0 {
  228. cResources.BlkioWeight = resources.BlkioWeight
  229. }
  230. if resources.CPUShares != 0 {
  231. cResources.CPUShares = resources.CPUShares
  232. }
  233. if resources.CPUPeriod != 0 {
  234. cResources.CPUPeriod = resources.CPUPeriod
  235. }
  236. if resources.CPUQuota != 0 {
  237. cResources.CPUQuota = resources.CPUQuota
  238. }
  239. if resources.CpusetCpus != "" {
  240. cResources.CpusetCpus = resources.CpusetCpus
  241. }
  242. if resources.CpusetMems != "" {
  243. cResources.CpusetMems = resources.CpusetMems
  244. }
  245. if resources.Memory != 0 {
  246. cResources.Memory = resources.Memory
  247. }
  248. if resources.MemorySwap != 0 {
  249. cResources.MemorySwap = resources.MemorySwap
  250. }
  251. if resources.MemoryReservation != 0 {
  252. cResources.MemoryReservation = resources.MemoryReservation
  253. }
  254. if resources.KernelMemory != 0 {
  255. cResources.KernelMemory = resources.KernelMemory
  256. }
  257. // update HostConfig of container
  258. if hostConfig.RestartPolicy.Name != "" {
  259. container.HostConfig.RestartPolicy = hostConfig.RestartPolicy
  260. }
  261. if err := container.ToDisk(); err != nil {
  262. logrus.Errorf("Error saving updated container: %v", err)
  263. return err
  264. }
  265. return nil
  266. }
  267. func detachMounted(path string) error {
  268. return syscall.Unmount(path, syscall.MNT_DETACH)
  269. }
  270. // UnmountVolumes unmounts all volumes
  271. func (container *Container) UnmountVolumes(forceSyscall bool, volumeEventLog func(name, action string, attributes map[string]string)) error {
  272. var (
  273. volumeMounts []volume.MountPoint
  274. err error
  275. )
  276. for _, mntPoint := range container.MountPoints {
  277. dest, err := container.GetResourcePath(mntPoint.Destination)
  278. if err != nil {
  279. return err
  280. }
  281. volumeMounts = append(volumeMounts, volume.MountPoint{Destination: dest, Volume: mntPoint.Volume})
  282. }
  283. // Append any network mounts to the list (this is a no-op on Windows)
  284. if volumeMounts, err = appendNetworkMounts(container, volumeMounts); err != nil {
  285. return err
  286. }
  287. for _, volumeMount := range volumeMounts {
  288. if forceSyscall {
  289. if err := detachMounted(volumeMount.Destination); err != nil {
  290. logrus.Warnf("%s unmountVolumes: Failed to do lazy umount %v", container.ID, err)
  291. }
  292. }
  293. if volumeMount.Volume != nil {
  294. if err := volumeMount.Volume.Unmount(); err != nil {
  295. return err
  296. }
  297. attributes := map[string]string{
  298. "driver": volumeMount.Volume.DriverName(),
  299. "container": container.ID,
  300. }
  301. volumeEventLog(volumeMount.Volume.Name(), "unmount", attributes)
  302. }
  303. }
  304. return nil
  305. }
  306. // copyExistingContents copies from the source to the destination and
  307. // ensures the ownership is appropriately set.
  308. func copyExistingContents(source, destination string) error {
  309. volList, err := ioutil.ReadDir(source)
  310. if err != nil {
  311. return err
  312. }
  313. if len(volList) > 0 {
  314. srcList, err := ioutil.ReadDir(destination)
  315. if err != nil {
  316. return err
  317. }
  318. if len(srcList) == 0 {
  319. // If the source volume is empty, copies files from the root into the volume
  320. if err := chrootarchive.CopyWithTar(source, destination); err != nil {
  321. return err
  322. }
  323. }
  324. }
  325. return copyOwnership(source, destination)
  326. }
  327. // copyOwnership copies the permissions and uid:gid of the source file
  328. // to the destination file
  329. func copyOwnership(source, destination string) error {
  330. stat, err := system.Stat(source)
  331. if err != nil {
  332. return err
  333. }
  334. if err := os.Chown(destination, int(stat.UID()), int(stat.GID())); err != nil {
  335. return err
  336. }
  337. return os.Chmod(destination, os.FileMode(stat.Mode()))
  338. }
  339. // TmpfsMounts returns the list of tmpfs mounts
  340. func (container *Container) TmpfsMounts() []Mount {
  341. var mounts []Mount
  342. for dest, data := range container.HostConfig.Tmpfs {
  343. mounts = append(mounts, Mount{
  344. Source: "tmpfs",
  345. Destination: dest,
  346. Data: data,
  347. })
  348. }
  349. return mounts
  350. }
  351. // cleanResourcePath cleans a resource path and prepares to combine with mnt path
  352. func cleanResourcePath(path string) string {
  353. return filepath.Join(string(os.PathSeparator), path)
  354. }
  355. // canMountFS determines if the file system for the container
  356. // can be mounted locally. A no-op on non-Windows platforms
  357. func (container *Container) canMountFS() bool {
  358. return true
  359. }