container_unix.go 13 KB

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