container_unix.go 12 KB

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