container_unix.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  1. // +build linux freebsd
  2. package container
  3. import (
  4. "fmt"
  5. "io/ioutil"
  6. "net"
  7. "os"
  8. "path/filepath"
  9. "strconv"
  10. "strings"
  11. "syscall"
  12. "github.com/Sirupsen/logrus"
  13. "github.com/docker/docker/api/types/container"
  14. "github.com/docker/docker/api/types/network"
  15. "github.com/docker/docker/daemon/execdriver"
  16. derr "github.com/docker/docker/errors"
  17. "github.com/docker/docker/pkg/chrootarchive"
  18. "github.com/docker/docker/pkg/symlink"
  19. "github.com/docker/docker/pkg/system"
  20. "github.com/docker/docker/utils"
  21. "github.com/docker/docker/volume"
  22. "github.com/docker/go-connections/nat"
  23. "github.com/docker/libnetwork"
  24. "github.com/docker/libnetwork/netlabel"
  25. "github.com/docker/libnetwork/options"
  26. "github.com/docker/libnetwork/types"
  27. "github.com/opencontainers/runc/libcontainer/label"
  28. )
  29. // DefaultSHMSize is the default size (64MB) of the SHM which will be mounted in the container
  30. const DefaultSHMSize int64 = 67108864
  31. // Container holds the fields specific to unixen implementations. See
  32. // CommonContainer for standard fields common to all containers.
  33. type Container struct {
  34. CommonContainer
  35. // Fields below here are platform specific.
  36. AppArmorProfile string
  37. HostnamePath string
  38. HostsPath string
  39. ShmPath string
  40. MqueuePath string
  41. ResolvConfPath string
  42. SeccompProfile string
  43. }
  44. // CreateDaemonEnvironment returns the list of all environment variables given the list of
  45. // environment variables related to links.
  46. // Sets PATH, HOSTNAME and if container.Config.Tty is set: TERM.
  47. // The defaults set here do not override the values in container.Config.Env
  48. func (container *Container) CreateDaemonEnvironment(linkedEnv []string) []string {
  49. // if a domain name was specified, append it to the hostname (see #7851)
  50. fullHostname := container.Config.Hostname
  51. if container.Config.Domainname != "" {
  52. fullHostname = fmt.Sprintf("%s.%s", fullHostname, container.Config.Domainname)
  53. }
  54. // Setup environment
  55. env := []string{
  56. "PATH=" + system.DefaultPathEnv,
  57. "HOSTNAME=" + fullHostname,
  58. // Note: we don't set HOME here because it'll get autoset intelligently
  59. // based on the value of USER inside dockerinit, but only if it isn't
  60. // set already (ie, that can be overridden by setting HOME via -e or ENV
  61. // in a Dockerfile).
  62. }
  63. if container.Config.Tty {
  64. env = append(env, "TERM=xterm")
  65. }
  66. env = append(env, linkedEnv...)
  67. // because the env on the container can override certain default values
  68. // we need to replace the 'env' keys where they match and append anything
  69. // else.
  70. env = utils.ReplaceOrAppendEnvValues(env, container.Config.Env)
  71. return env
  72. }
  73. // TrySetNetworkMount attempts to set the network mounts given a provided destination and
  74. // the path to use for it; return true if the given destination was a network mount file
  75. func (container *Container) TrySetNetworkMount(destination string, path string) bool {
  76. if destination == "/etc/resolv.conf" {
  77. container.ResolvConfPath = path
  78. return true
  79. }
  80. if destination == "/etc/hostname" {
  81. container.HostnamePath = path
  82. return true
  83. }
  84. if destination == "/etc/hosts" {
  85. container.HostsPath = path
  86. return true
  87. }
  88. return false
  89. }
  90. // BuildHostnameFile writes the container's hostname file.
  91. func (container *Container) BuildHostnameFile() error {
  92. hostnamePath, err := container.GetRootResourcePath("hostname")
  93. if err != nil {
  94. return err
  95. }
  96. container.HostnamePath = hostnamePath
  97. if container.Config.Domainname != "" {
  98. return ioutil.WriteFile(container.HostnamePath, []byte(fmt.Sprintf("%s.%s\n", container.Config.Hostname, container.Config.Domainname)), 0644)
  99. }
  100. return ioutil.WriteFile(container.HostnamePath, []byte(container.Config.Hostname+"\n"), 0644)
  101. }
  102. // GetEndpointInNetwork returns the container's endpoint to the provided network.
  103. func (container *Container) GetEndpointInNetwork(n libnetwork.Network) (libnetwork.Endpoint, error) {
  104. endpointName := strings.TrimPrefix(container.Name, "/")
  105. return n.EndpointByName(endpointName)
  106. }
  107. func (container *Container) buildPortMapInfo(ep libnetwork.Endpoint) error {
  108. if ep == nil {
  109. return derr.ErrorCodeEmptyEndpoint
  110. }
  111. networkSettings := container.NetworkSettings
  112. if networkSettings == nil {
  113. return derr.ErrorCodeEmptyNetwork
  114. }
  115. driverInfo, err := ep.DriverInfo()
  116. if err != nil {
  117. return err
  118. }
  119. if driverInfo == nil {
  120. // It is not an error for epInfo to be nil
  121. return nil
  122. }
  123. if networkSettings.Ports == nil {
  124. networkSettings.Ports = nat.PortMap{}
  125. }
  126. if expData, ok := driverInfo[netlabel.ExposedPorts]; ok {
  127. if exposedPorts, ok := expData.([]types.TransportPort); ok {
  128. for _, tp := range exposedPorts {
  129. natPort, err := nat.NewPort(tp.Proto.String(), strconv.Itoa(int(tp.Port)))
  130. if err != nil {
  131. return derr.ErrorCodeParsingPort.WithArgs(tp.Port, err)
  132. }
  133. networkSettings.Ports[natPort] = nil
  134. }
  135. }
  136. }
  137. mapData, ok := driverInfo[netlabel.PortMap]
  138. if !ok {
  139. return nil
  140. }
  141. if portMapping, ok := mapData.([]types.PortBinding); ok {
  142. for _, pp := range portMapping {
  143. natPort, err := nat.NewPort(pp.Proto.String(), strconv.Itoa(int(pp.Port)))
  144. if err != nil {
  145. return err
  146. }
  147. natBndg := nat.PortBinding{HostIP: pp.HostIP.String(), HostPort: strconv.Itoa(int(pp.HostPort))}
  148. networkSettings.Ports[natPort] = append(networkSettings.Ports[natPort], natBndg)
  149. }
  150. }
  151. return nil
  152. }
  153. // BuildEndpointInfo sets endpoint-related fields on container.NetworkSettings based on the provided network and endpoint.
  154. func (container *Container) BuildEndpointInfo(n libnetwork.Network, ep libnetwork.Endpoint) error {
  155. if ep == nil {
  156. return derr.ErrorCodeEmptyEndpoint
  157. }
  158. networkSettings := container.NetworkSettings
  159. if networkSettings == nil {
  160. return derr.ErrorCodeEmptyNetwork
  161. }
  162. epInfo := ep.Info()
  163. if epInfo == nil {
  164. // It is not an error to get an empty endpoint info
  165. return nil
  166. }
  167. if _, ok := networkSettings.Networks[n.Name()]; !ok {
  168. networkSettings.Networks[n.Name()] = new(network.EndpointSettings)
  169. }
  170. networkSettings.Networks[n.Name()].EndpointID = ep.ID()
  171. iface := epInfo.Iface()
  172. if iface == nil {
  173. return nil
  174. }
  175. if iface.MacAddress() != nil {
  176. networkSettings.Networks[n.Name()].MacAddress = iface.MacAddress().String()
  177. }
  178. if iface.Address() != nil {
  179. ones, _ := iface.Address().Mask.Size()
  180. networkSettings.Networks[n.Name()].IPAddress = iface.Address().IP.String()
  181. networkSettings.Networks[n.Name()].IPPrefixLen = ones
  182. }
  183. if iface.AddressIPv6() != nil && iface.AddressIPv6().IP.To16() != nil {
  184. onesv6, _ := iface.AddressIPv6().Mask.Size()
  185. networkSettings.Networks[n.Name()].GlobalIPv6Address = iface.AddressIPv6().IP.String()
  186. networkSettings.Networks[n.Name()].GlobalIPv6PrefixLen = onesv6
  187. }
  188. return nil
  189. }
  190. // UpdateJoinInfo updates network settings when container joins network n with endpoint ep.
  191. func (container *Container) UpdateJoinInfo(n libnetwork.Network, ep libnetwork.Endpoint) error {
  192. if err := container.buildPortMapInfo(ep); err != nil {
  193. return err
  194. }
  195. epInfo := ep.Info()
  196. if epInfo == nil {
  197. // It is not an error to get an empty endpoint info
  198. return nil
  199. }
  200. if epInfo.Gateway() != nil {
  201. container.NetworkSettings.Networks[n.Name()].Gateway = epInfo.Gateway().String()
  202. }
  203. if epInfo.GatewayIPv6().To16() != nil {
  204. container.NetworkSettings.Networks[n.Name()].IPv6Gateway = epInfo.GatewayIPv6().String()
  205. }
  206. return nil
  207. }
  208. // UpdateSandboxNetworkSettings updates the sandbox ID and Key.
  209. func (container *Container) UpdateSandboxNetworkSettings(sb libnetwork.Sandbox) error {
  210. container.NetworkSettings.SandboxID = sb.ID()
  211. container.NetworkSettings.SandboxKey = sb.Key()
  212. return nil
  213. }
  214. // BuildCreateEndpointOptions builds endpoint options from a given network.
  215. func (container *Container) BuildCreateEndpointOptions(n libnetwork.Network) ([]libnetwork.EndpointOption, error) {
  216. var (
  217. portSpecs = make(nat.PortSet)
  218. bindings = make(nat.PortMap)
  219. pbList []types.PortBinding
  220. exposeList []types.TransportPort
  221. createOptions []libnetwork.EndpointOption
  222. )
  223. if n.Name() == "bridge" || container.NetworkSettings.IsAnonymousEndpoint {
  224. createOptions = append(createOptions, libnetwork.CreateOptionAnonymous())
  225. }
  226. // Other configs are applicable only for the endpoint in the network
  227. // to which container was connected to on docker run.
  228. if n.Name() != container.HostConfig.NetworkMode.NetworkName() &&
  229. !(n.Name() == "bridge" && container.HostConfig.NetworkMode.IsDefault()) {
  230. return createOptions, nil
  231. }
  232. if container.Config.ExposedPorts != nil {
  233. portSpecs = container.Config.ExposedPorts
  234. }
  235. if container.HostConfig.PortBindings != nil {
  236. for p, b := range container.HostConfig.PortBindings {
  237. bindings[p] = []nat.PortBinding{}
  238. for _, bb := range b {
  239. bindings[p] = append(bindings[p], nat.PortBinding{
  240. HostIP: bb.HostIP,
  241. HostPort: bb.HostPort,
  242. })
  243. }
  244. }
  245. }
  246. ports := make([]nat.Port, len(portSpecs))
  247. var i int
  248. for p := range portSpecs {
  249. ports[i] = p
  250. i++
  251. }
  252. nat.SortPortMap(ports, bindings)
  253. for _, port := range ports {
  254. expose := types.TransportPort{}
  255. expose.Proto = types.ParseProtocol(port.Proto())
  256. expose.Port = uint16(port.Int())
  257. exposeList = append(exposeList, expose)
  258. pb := types.PortBinding{Port: expose.Port, Proto: expose.Proto}
  259. binding := bindings[port]
  260. for i := 0; i < len(binding); i++ {
  261. pbCopy := pb.GetCopy()
  262. newP, err := nat.NewPort(nat.SplitProtoPort(binding[i].HostPort))
  263. var portStart, portEnd int
  264. if err == nil {
  265. portStart, portEnd, err = newP.Range()
  266. }
  267. if err != nil {
  268. return nil, derr.ErrorCodeHostPort.WithArgs(binding[i].HostPort, err)
  269. }
  270. pbCopy.HostPort = uint16(portStart)
  271. pbCopy.HostPortEnd = uint16(portEnd)
  272. pbCopy.HostIP = net.ParseIP(binding[i].HostIP)
  273. pbList = append(pbList, pbCopy)
  274. }
  275. if container.HostConfig.PublishAllPorts && len(binding) == 0 {
  276. pbList = append(pbList, pb)
  277. }
  278. }
  279. createOptions = append(createOptions,
  280. libnetwork.CreateOptionPortMapping(pbList),
  281. libnetwork.CreateOptionExposedPorts(exposeList))
  282. if container.Config.MacAddress != "" {
  283. mac, err := net.ParseMAC(container.Config.MacAddress)
  284. if err != nil {
  285. return nil, err
  286. }
  287. genericOption := options.Generic{
  288. netlabel.MacAddress: mac,
  289. }
  290. createOptions = append(createOptions, libnetwork.EndpointOptionGeneric(genericOption))
  291. }
  292. return createOptions, nil
  293. }
  294. // SetupWorkingDirectory sets up the container's working directory as set in container.Config.WorkingDir
  295. func (container *Container) SetupWorkingDirectory() error {
  296. if container.Config.WorkingDir == "" {
  297. return nil
  298. }
  299. container.Config.WorkingDir = filepath.Clean(container.Config.WorkingDir)
  300. pth, err := container.GetResourcePath(container.Config.WorkingDir)
  301. if err != nil {
  302. return err
  303. }
  304. pthInfo, err := os.Stat(pth)
  305. if err != nil {
  306. if !os.IsNotExist(err) {
  307. return err
  308. }
  309. if err := system.MkdirAll(pth, 0755); err != nil {
  310. return err
  311. }
  312. }
  313. if pthInfo != nil && !pthInfo.IsDir() {
  314. return derr.ErrorCodeNotADir.WithArgs(container.Config.WorkingDir)
  315. }
  316. return nil
  317. }
  318. // appendNetworkMounts appends any network mounts to the array of mount points passed in
  319. func appendNetworkMounts(container *Container, volumeMounts []volume.MountPoint) ([]volume.MountPoint, error) {
  320. for _, mnt := range container.NetworkMounts() {
  321. dest, err := container.GetResourcePath(mnt.Destination)
  322. if err != nil {
  323. return nil, err
  324. }
  325. volumeMounts = append(volumeMounts, volume.MountPoint{Destination: dest})
  326. }
  327. return volumeMounts, nil
  328. }
  329. // NetworkMounts returns the list of network mounts.
  330. func (container *Container) NetworkMounts() []execdriver.Mount {
  331. var mounts []execdriver.Mount
  332. shared := container.HostConfig.NetworkMode.IsContainer()
  333. if container.ResolvConfPath != "" {
  334. if _, err := os.Stat(container.ResolvConfPath); err != nil {
  335. logrus.Warnf("ResolvConfPath set to %q, but can't stat this filename (err = %v); skipping", container.ResolvConfPath, err)
  336. } else {
  337. label.Relabel(container.ResolvConfPath, container.MountLabel, shared)
  338. writable := !container.HostConfig.ReadonlyRootfs
  339. if m, exists := container.MountPoints["/etc/resolv.conf"]; exists {
  340. writable = m.RW
  341. }
  342. mounts = append(mounts, execdriver.Mount{
  343. Source: container.ResolvConfPath,
  344. Destination: "/etc/resolv.conf",
  345. Writable: writable,
  346. Propagation: volume.DefaultPropagationMode,
  347. })
  348. }
  349. }
  350. if container.HostnamePath != "" {
  351. if _, err := os.Stat(container.HostnamePath); err != nil {
  352. logrus.Warnf("HostnamePath set to %q, but can't stat this filename (err = %v); skipping", container.HostnamePath, err)
  353. } else {
  354. label.Relabel(container.HostnamePath, container.MountLabel, shared)
  355. writable := !container.HostConfig.ReadonlyRootfs
  356. if m, exists := container.MountPoints["/etc/hostname"]; exists {
  357. writable = m.RW
  358. }
  359. mounts = append(mounts, execdriver.Mount{
  360. Source: container.HostnamePath,
  361. Destination: "/etc/hostname",
  362. Writable: writable,
  363. Propagation: volume.DefaultPropagationMode,
  364. })
  365. }
  366. }
  367. if container.HostsPath != "" {
  368. if _, err := os.Stat(container.HostsPath); err != nil {
  369. logrus.Warnf("HostsPath set to %q, but can't stat this filename (err = %v); skipping", container.HostsPath, err)
  370. } else {
  371. label.Relabel(container.HostsPath, container.MountLabel, shared)
  372. writable := !container.HostConfig.ReadonlyRootfs
  373. if m, exists := container.MountPoints["/etc/hosts"]; exists {
  374. writable = m.RW
  375. }
  376. mounts = append(mounts, execdriver.Mount{
  377. Source: container.HostsPath,
  378. Destination: "/etc/hosts",
  379. Writable: writable,
  380. Propagation: volume.DefaultPropagationMode,
  381. })
  382. }
  383. }
  384. return mounts
  385. }
  386. // CopyImagePathContent copies files in destination to the volume.
  387. func (container *Container) CopyImagePathContent(v volume.Volume, destination string) error {
  388. rootfs, err := symlink.FollowSymlinkInScope(filepath.Join(container.BaseFS, destination), container.BaseFS)
  389. if err != nil {
  390. return err
  391. }
  392. if _, err = ioutil.ReadDir(rootfs); err != nil {
  393. if os.IsNotExist(err) {
  394. return nil
  395. }
  396. return err
  397. }
  398. path, err := v.Mount()
  399. if err != nil {
  400. return err
  401. }
  402. if err := copyExistingContents(rootfs, path); err != nil {
  403. return err
  404. }
  405. return v.Unmount()
  406. }
  407. // ShmResourcePath returns path to shm
  408. func (container *Container) ShmResourcePath() (string, error) {
  409. return container.GetRootResourcePath("shm")
  410. }
  411. // MqueueResourcePath returns path to mqueue
  412. func (container *Container) MqueueResourcePath() (string, error) {
  413. return container.GetRootResourcePath("mqueue")
  414. }
  415. // HasMountFor checks if path is a mountpoint
  416. func (container *Container) HasMountFor(path string) bool {
  417. _, exists := container.MountPoints[path]
  418. return exists
  419. }
  420. // UnmountIpcMounts uses the provided unmount function to unmount shm and mqueue if they were mounted
  421. func (container *Container) UnmountIpcMounts(unmount func(pth string) error) {
  422. if container.HostConfig.IpcMode.IsContainer() || container.HostConfig.IpcMode.IsHost() {
  423. return
  424. }
  425. var warnings []string
  426. if !container.HasMountFor("/dev/shm") {
  427. shmPath, err := container.ShmResourcePath()
  428. if err != nil {
  429. logrus.Error(err)
  430. warnings = append(warnings, err.Error())
  431. } else if shmPath != "" {
  432. if err := unmount(shmPath); err != nil {
  433. warnings = append(warnings, fmt.Sprintf("failed to umount %s: %v", shmPath, err))
  434. }
  435. }
  436. }
  437. if !container.HasMountFor("/dev/mqueue") {
  438. mqueuePath, err := container.MqueueResourcePath()
  439. if err != nil {
  440. logrus.Error(err)
  441. warnings = append(warnings, err.Error())
  442. } else if mqueuePath != "" {
  443. if err := unmount(mqueuePath); err != nil {
  444. warnings = append(warnings, fmt.Sprintf("failed to umount %s: %v", mqueuePath, err))
  445. }
  446. }
  447. }
  448. if len(warnings) > 0 {
  449. logrus.Warnf("failed to cleanup ipc mounts:\n%v", strings.Join(warnings, "\n"))
  450. }
  451. }
  452. // IpcMounts returns the list of IPC mounts
  453. func (container *Container) IpcMounts() []execdriver.Mount {
  454. var mounts []execdriver.Mount
  455. if !container.HasMountFor("/dev/shm") {
  456. label.SetFileLabel(container.ShmPath, container.MountLabel)
  457. mounts = append(mounts, execdriver.Mount{
  458. Source: container.ShmPath,
  459. Destination: "/dev/shm",
  460. Writable: true,
  461. Propagation: volume.DefaultPropagationMode,
  462. })
  463. }
  464. if !container.HasMountFor("/dev/mqueue") {
  465. label.SetFileLabel(container.MqueuePath, container.MountLabel)
  466. mounts = append(mounts, execdriver.Mount{
  467. Source: container.MqueuePath,
  468. Destination: "/dev/mqueue",
  469. Writable: true,
  470. Propagation: volume.DefaultPropagationMode,
  471. })
  472. }
  473. return mounts
  474. }
  475. func updateCommand(c *execdriver.Command, resources container.Resources) {
  476. c.Resources.BlkioWeight = resources.BlkioWeight
  477. c.Resources.CPUShares = resources.CPUShares
  478. c.Resources.CPUPeriod = resources.CPUPeriod
  479. c.Resources.CPUQuota = resources.CPUQuota
  480. c.Resources.CpusetCpus = resources.CpusetCpus
  481. c.Resources.CpusetMems = resources.CpusetMems
  482. c.Resources.Memory = resources.Memory
  483. c.Resources.MemorySwap = resources.MemorySwap
  484. c.Resources.MemoryReservation = resources.MemoryReservation
  485. c.Resources.KernelMemory = resources.KernelMemory
  486. }
  487. // UpdateContainer updates resources of a container.
  488. func (container *Container) UpdateContainer(hostConfig *container.HostConfig) error {
  489. container.Lock()
  490. resources := hostConfig.Resources
  491. cResources := &container.HostConfig.Resources
  492. if resources.BlkioWeight != 0 {
  493. cResources.BlkioWeight = resources.BlkioWeight
  494. }
  495. if resources.CPUShares != 0 {
  496. cResources.CPUShares = resources.CPUShares
  497. }
  498. if resources.CPUPeriod != 0 {
  499. cResources.CPUPeriod = resources.CPUPeriod
  500. }
  501. if resources.CPUQuota != 0 {
  502. cResources.CPUQuota = resources.CPUQuota
  503. }
  504. if resources.CpusetCpus != "" {
  505. cResources.CpusetCpus = resources.CpusetCpus
  506. }
  507. if resources.CpusetMems != "" {
  508. cResources.CpusetMems = resources.CpusetMems
  509. }
  510. if resources.Memory != 0 {
  511. cResources.Memory = resources.Memory
  512. }
  513. if resources.MemorySwap != 0 {
  514. cResources.MemorySwap = resources.MemorySwap
  515. }
  516. if resources.MemoryReservation != 0 {
  517. cResources.MemoryReservation = resources.MemoryReservation
  518. }
  519. if resources.KernelMemory != 0 {
  520. cResources.KernelMemory = resources.KernelMemory
  521. }
  522. container.Unlock()
  523. // If container is not running, update hostConfig struct is enough,
  524. // resources will be updated when the container is started again.
  525. // If container is running (including paused), we need to update
  526. // the command so we can update configs to the real world.
  527. if container.IsRunning() {
  528. container.Lock()
  529. updateCommand(container.Command, resources)
  530. container.Unlock()
  531. }
  532. if err := container.ToDiskLocking(); err != nil {
  533. logrus.Errorf("Error saving updated container: %v", err)
  534. return err
  535. }
  536. return nil
  537. }
  538. func detachMounted(path string) error {
  539. return syscall.Unmount(path, syscall.MNT_DETACH)
  540. }
  541. // UnmountVolumes unmounts all volumes
  542. func (container *Container) UnmountVolumes(forceSyscall bool) error {
  543. var (
  544. volumeMounts []volume.MountPoint
  545. err error
  546. )
  547. for _, mntPoint := range container.MountPoints {
  548. dest, err := container.GetResourcePath(mntPoint.Destination)
  549. if err != nil {
  550. return err
  551. }
  552. volumeMounts = append(volumeMounts, volume.MountPoint{Destination: dest, Volume: mntPoint.Volume})
  553. }
  554. // Append any network mounts to the list (this is a no-op on Windows)
  555. if volumeMounts, err = appendNetworkMounts(container, volumeMounts); err != nil {
  556. return err
  557. }
  558. for _, volumeMount := range volumeMounts {
  559. if forceSyscall {
  560. if err := detachMounted(volumeMount.Destination); err != nil {
  561. logrus.Warnf("%s unmountVolumes: Failed to do lazy umount %v", container.ID, err)
  562. }
  563. }
  564. if volumeMount.Volume != nil {
  565. if err := volumeMount.Volume.Unmount(); err != nil {
  566. return err
  567. }
  568. }
  569. }
  570. return nil
  571. }
  572. // copyExistingContents copies from the source to the destination and
  573. // ensures the ownership is appropriately set.
  574. func copyExistingContents(source, destination string) error {
  575. volList, err := ioutil.ReadDir(source)
  576. if err != nil {
  577. return err
  578. }
  579. if len(volList) > 0 {
  580. srcList, err := ioutil.ReadDir(destination)
  581. if err != nil {
  582. return err
  583. }
  584. if len(srcList) == 0 {
  585. // If the source volume is empty copy files from the root into the volume
  586. if err := chrootarchive.CopyWithTar(source, destination); err != nil {
  587. return err
  588. }
  589. }
  590. }
  591. return copyOwnership(source, destination)
  592. }
  593. // copyOwnership copies the permissions and uid:gid of the source file
  594. // to the destination file
  595. func copyOwnership(source, destination string) error {
  596. stat, err := system.Stat(source)
  597. if err != nil {
  598. return err
  599. }
  600. if err := os.Chown(destination, int(stat.UID()), int(stat.GID())); err != nil {
  601. return err
  602. }
  603. return os.Chmod(destination, os.FileMode(stat.Mode()))
  604. }
  605. // TmpfsMounts returns the list of tmpfs mounts
  606. func (container *Container) TmpfsMounts() []execdriver.Mount {
  607. var mounts []execdriver.Mount
  608. for dest, data := range container.HostConfig.Tmpfs {
  609. mounts = append(mounts, execdriver.Mount{
  610. Source: "tmpfs",
  611. Destination: dest,
  612. Data: data,
  613. })
  614. }
  615. return mounts
  616. }