container_unix.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  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/daemon/execdriver"
  14. derr "github.com/docker/docker/errors"
  15. "github.com/docker/docker/pkg/chrootarchive"
  16. "github.com/docker/docker/pkg/symlink"
  17. "github.com/docker/docker/pkg/system"
  18. "github.com/docker/docker/utils"
  19. "github.com/docker/docker/volume"
  20. "github.com/docker/engine-api/types/container"
  21. "github.com/docker/engine-api/types/network"
  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. if epConfig, ok := container.NetworkSettings.Networks[n.Name()]; ok {
  227. ipam := epConfig.IPAMConfig
  228. if ipam != nil && (ipam.IPv4Address != "" || ipam.IPv6Address != "") {
  229. createOptions = append(createOptions,
  230. libnetwork.CreateOptionIpam(net.ParseIP(ipam.IPv4Address), net.ParseIP(ipam.IPv6Address), nil))
  231. }
  232. }
  233. // Other configs are applicable only for the endpoint in the network
  234. // to which container was connected to on docker run.
  235. if n.Name() != container.HostConfig.NetworkMode.NetworkName() &&
  236. !(n.Name() == "bridge" && container.HostConfig.NetworkMode.IsDefault()) {
  237. return createOptions, nil
  238. }
  239. if container.Config.ExposedPorts != nil {
  240. portSpecs = container.Config.ExposedPorts
  241. }
  242. if container.HostConfig.PortBindings != nil {
  243. for p, b := range container.HostConfig.PortBindings {
  244. bindings[p] = []nat.PortBinding{}
  245. for _, bb := range b {
  246. bindings[p] = append(bindings[p], nat.PortBinding{
  247. HostIP: bb.HostIP,
  248. HostPort: bb.HostPort,
  249. })
  250. }
  251. }
  252. }
  253. ports := make([]nat.Port, len(portSpecs))
  254. var i int
  255. for p := range portSpecs {
  256. ports[i] = p
  257. i++
  258. }
  259. nat.SortPortMap(ports, bindings)
  260. for _, port := range ports {
  261. expose := types.TransportPort{}
  262. expose.Proto = types.ParseProtocol(port.Proto())
  263. expose.Port = uint16(port.Int())
  264. exposeList = append(exposeList, expose)
  265. pb := types.PortBinding{Port: expose.Port, Proto: expose.Proto}
  266. binding := bindings[port]
  267. for i := 0; i < len(binding); i++ {
  268. pbCopy := pb.GetCopy()
  269. newP, err := nat.NewPort(nat.SplitProtoPort(binding[i].HostPort))
  270. var portStart, portEnd int
  271. if err == nil {
  272. portStart, portEnd, err = newP.Range()
  273. }
  274. if err != nil {
  275. return nil, derr.ErrorCodeHostPort.WithArgs(binding[i].HostPort, err)
  276. }
  277. pbCopy.HostPort = uint16(portStart)
  278. pbCopy.HostPortEnd = uint16(portEnd)
  279. pbCopy.HostIP = net.ParseIP(binding[i].HostIP)
  280. pbList = append(pbList, pbCopy)
  281. }
  282. if container.HostConfig.PublishAllPorts && len(binding) == 0 {
  283. pbList = append(pbList, pb)
  284. }
  285. }
  286. createOptions = append(createOptions,
  287. libnetwork.CreateOptionPortMapping(pbList),
  288. libnetwork.CreateOptionExposedPorts(exposeList))
  289. if container.Config.MacAddress != "" {
  290. mac, err := net.ParseMAC(container.Config.MacAddress)
  291. if err != nil {
  292. return nil, err
  293. }
  294. genericOption := options.Generic{
  295. netlabel.MacAddress: mac,
  296. }
  297. createOptions = append(createOptions, libnetwork.EndpointOptionGeneric(genericOption))
  298. }
  299. return createOptions, nil
  300. }
  301. // SetupWorkingDirectory sets up the container's working directory as set in container.Config.WorkingDir
  302. func (container *Container) SetupWorkingDirectory() error {
  303. if container.Config.WorkingDir == "" {
  304. return nil
  305. }
  306. container.Config.WorkingDir = filepath.Clean(container.Config.WorkingDir)
  307. pth, err := container.GetResourcePath(container.Config.WorkingDir)
  308. if err != nil {
  309. return err
  310. }
  311. pthInfo, err := os.Stat(pth)
  312. if err != nil {
  313. if !os.IsNotExist(err) {
  314. return err
  315. }
  316. if err := system.MkdirAll(pth, 0755); err != nil {
  317. return err
  318. }
  319. }
  320. if pthInfo != nil && !pthInfo.IsDir() {
  321. return derr.ErrorCodeNotADir.WithArgs(container.Config.WorkingDir)
  322. }
  323. return nil
  324. }
  325. // appendNetworkMounts appends any network mounts to the array of mount points passed in
  326. func appendNetworkMounts(container *Container, volumeMounts []volume.MountPoint) ([]volume.MountPoint, error) {
  327. for _, mnt := range container.NetworkMounts() {
  328. dest, err := container.GetResourcePath(mnt.Destination)
  329. if err != nil {
  330. return nil, err
  331. }
  332. volumeMounts = append(volumeMounts, volume.MountPoint{Destination: dest})
  333. }
  334. return volumeMounts, nil
  335. }
  336. // NetworkMounts returns the list of network mounts.
  337. func (container *Container) NetworkMounts() []execdriver.Mount {
  338. var mounts []execdriver.Mount
  339. shared := container.HostConfig.NetworkMode.IsContainer()
  340. if container.ResolvConfPath != "" {
  341. if _, err := os.Stat(container.ResolvConfPath); err != nil {
  342. logrus.Warnf("ResolvConfPath set to %q, but can't stat this filename (err = %v); skipping", container.ResolvConfPath, err)
  343. } else {
  344. label.Relabel(container.ResolvConfPath, container.MountLabel, shared)
  345. writable := !container.HostConfig.ReadonlyRootfs
  346. if m, exists := container.MountPoints["/etc/resolv.conf"]; exists {
  347. writable = m.RW
  348. }
  349. mounts = append(mounts, execdriver.Mount{
  350. Source: container.ResolvConfPath,
  351. Destination: "/etc/resolv.conf",
  352. Writable: writable,
  353. Propagation: volume.DefaultPropagationMode,
  354. })
  355. }
  356. }
  357. if container.HostnamePath != "" {
  358. if _, err := os.Stat(container.HostnamePath); err != nil {
  359. logrus.Warnf("HostnamePath set to %q, but can't stat this filename (err = %v); skipping", container.HostnamePath, err)
  360. } else {
  361. label.Relabel(container.HostnamePath, container.MountLabel, shared)
  362. writable := !container.HostConfig.ReadonlyRootfs
  363. if m, exists := container.MountPoints["/etc/hostname"]; exists {
  364. writable = m.RW
  365. }
  366. mounts = append(mounts, execdriver.Mount{
  367. Source: container.HostnamePath,
  368. Destination: "/etc/hostname",
  369. Writable: writable,
  370. Propagation: volume.DefaultPropagationMode,
  371. })
  372. }
  373. }
  374. if container.HostsPath != "" {
  375. if _, err := os.Stat(container.HostsPath); err != nil {
  376. logrus.Warnf("HostsPath set to %q, but can't stat this filename (err = %v); skipping", container.HostsPath, err)
  377. } else {
  378. label.Relabel(container.HostsPath, container.MountLabel, shared)
  379. writable := !container.HostConfig.ReadonlyRootfs
  380. if m, exists := container.MountPoints["/etc/hosts"]; exists {
  381. writable = m.RW
  382. }
  383. mounts = append(mounts, execdriver.Mount{
  384. Source: container.HostsPath,
  385. Destination: "/etc/hosts",
  386. Writable: writable,
  387. Propagation: volume.DefaultPropagationMode,
  388. })
  389. }
  390. }
  391. return mounts
  392. }
  393. // CopyImagePathContent copies files in destination to the volume.
  394. func (container *Container) CopyImagePathContent(v volume.Volume, destination string) error {
  395. rootfs, err := symlink.FollowSymlinkInScope(filepath.Join(container.BaseFS, destination), container.BaseFS)
  396. if err != nil {
  397. return err
  398. }
  399. if _, err = ioutil.ReadDir(rootfs); err != nil {
  400. if os.IsNotExist(err) {
  401. return nil
  402. }
  403. return err
  404. }
  405. path, err := v.Mount()
  406. if err != nil {
  407. return err
  408. }
  409. if err := copyExistingContents(rootfs, path); err != nil {
  410. return err
  411. }
  412. return v.Unmount()
  413. }
  414. // ShmResourcePath returns path to shm
  415. func (container *Container) ShmResourcePath() (string, error) {
  416. return container.GetRootResourcePath("shm")
  417. }
  418. // MqueueResourcePath returns path to mqueue
  419. func (container *Container) MqueueResourcePath() (string, error) {
  420. return container.GetRootResourcePath("mqueue")
  421. }
  422. // HasMountFor checks if path is a mountpoint
  423. func (container *Container) HasMountFor(path string) bool {
  424. _, exists := container.MountPoints[path]
  425. return exists
  426. }
  427. // UnmountIpcMounts uses the provided unmount function to unmount shm and mqueue if they were mounted
  428. func (container *Container) UnmountIpcMounts(unmount func(pth string) error) {
  429. if container.HostConfig.IpcMode.IsContainer() || container.HostConfig.IpcMode.IsHost() {
  430. return
  431. }
  432. var warnings []string
  433. if !container.HasMountFor("/dev/shm") {
  434. shmPath, err := container.ShmResourcePath()
  435. if err != nil {
  436. logrus.Error(err)
  437. warnings = append(warnings, err.Error())
  438. } else if shmPath != "" {
  439. if err := unmount(shmPath); err != nil {
  440. warnings = append(warnings, fmt.Sprintf("failed to umount %s: %v", shmPath, err))
  441. }
  442. }
  443. }
  444. if !container.HasMountFor("/dev/mqueue") {
  445. mqueuePath, err := container.MqueueResourcePath()
  446. if err != nil {
  447. logrus.Error(err)
  448. warnings = append(warnings, err.Error())
  449. } else if mqueuePath != "" {
  450. if err := unmount(mqueuePath); err != nil {
  451. warnings = append(warnings, fmt.Sprintf("failed to umount %s: %v", mqueuePath, err))
  452. }
  453. }
  454. }
  455. if len(warnings) > 0 {
  456. logrus.Warnf("failed to cleanup ipc mounts:\n%v", strings.Join(warnings, "\n"))
  457. }
  458. }
  459. // IpcMounts returns the list of IPC mounts
  460. func (container *Container) IpcMounts() []execdriver.Mount {
  461. var mounts []execdriver.Mount
  462. if !container.HasMountFor("/dev/shm") {
  463. label.SetFileLabel(container.ShmPath, container.MountLabel)
  464. mounts = append(mounts, execdriver.Mount{
  465. Source: container.ShmPath,
  466. Destination: "/dev/shm",
  467. Writable: true,
  468. Propagation: volume.DefaultPropagationMode,
  469. })
  470. }
  471. if !container.HasMountFor("/dev/mqueue") {
  472. label.SetFileLabel(container.MqueuePath, container.MountLabel)
  473. mounts = append(mounts, execdriver.Mount{
  474. Source: container.MqueuePath,
  475. Destination: "/dev/mqueue",
  476. Writable: true,
  477. Propagation: volume.DefaultPropagationMode,
  478. })
  479. }
  480. return mounts
  481. }
  482. func updateCommand(c *execdriver.Command, resources container.Resources) {
  483. c.Resources.BlkioWeight = resources.BlkioWeight
  484. c.Resources.CPUShares = resources.CPUShares
  485. c.Resources.CPUPeriod = resources.CPUPeriod
  486. c.Resources.CPUQuota = resources.CPUQuota
  487. c.Resources.CpusetCpus = resources.CpusetCpus
  488. c.Resources.CpusetMems = resources.CpusetMems
  489. c.Resources.Memory = resources.Memory
  490. c.Resources.MemorySwap = resources.MemorySwap
  491. c.Resources.MemoryReservation = resources.MemoryReservation
  492. c.Resources.KernelMemory = resources.KernelMemory
  493. }
  494. // UpdateContainer updates resources of a container.
  495. func (container *Container) UpdateContainer(hostConfig *container.HostConfig) error {
  496. container.Lock()
  497. resources := hostConfig.Resources
  498. cResources := &container.HostConfig.Resources
  499. if resources.BlkioWeight != 0 {
  500. cResources.BlkioWeight = resources.BlkioWeight
  501. }
  502. if resources.CPUShares != 0 {
  503. cResources.CPUShares = resources.CPUShares
  504. }
  505. if resources.CPUPeriod != 0 {
  506. cResources.CPUPeriod = resources.CPUPeriod
  507. }
  508. if resources.CPUQuota != 0 {
  509. cResources.CPUQuota = resources.CPUQuota
  510. }
  511. if resources.CpusetCpus != "" {
  512. cResources.CpusetCpus = resources.CpusetCpus
  513. }
  514. if resources.CpusetMems != "" {
  515. cResources.CpusetMems = resources.CpusetMems
  516. }
  517. if resources.Memory != 0 {
  518. cResources.Memory = resources.Memory
  519. }
  520. if resources.MemorySwap != 0 {
  521. cResources.MemorySwap = resources.MemorySwap
  522. }
  523. if resources.MemoryReservation != 0 {
  524. cResources.MemoryReservation = resources.MemoryReservation
  525. }
  526. if resources.KernelMemory != 0 {
  527. cResources.KernelMemory = resources.KernelMemory
  528. }
  529. container.Unlock()
  530. // If container is not running, update hostConfig struct is enough,
  531. // resources will be updated when the container is started again.
  532. // If container is running (including paused), we need to update
  533. // the command so we can update configs to the real world.
  534. if container.IsRunning() {
  535. container.Lock()
  536. updateCommand(container.Command, *cResources)
  537. container.Unlock()
  538. }
  539. if err := container.ToDiskLocking(); err != nil {
  540. logrus.Errorf("Error saving updated container: %v", err)
  541. return err
  542. }
  543. return nil
  544. }
  545. func detachMounted(path string) error {
  546. return syscall.Unmount(path, syscall.MNT_DETACH)
  547. }
  548. // UnmountVolumes unmounts all volumes
  549. func (container *Container) UnmountVolumes(forceSyscall bool, volumeEventLog func(name, action string, attributes map[string]string)) error {
  550. var (
  551. volumeMounts []volume.MountPoint
  552. err error
  553. )
  554. for _, mntPoint := range container.MountPoints {
  555. dest, err := container.GetResourcePath(mntPoint.Destination)
  556. if err != nil {
  557. return err
  558. }
  559. volumeMounts = append(volumeMounts, volume.MountPoint{Destination: dest, Volume: mntPoint.Volume})
  560. }
  561. // Append any network mounts to the list (this is a no-op on Windows)
  562. if volumeMounts, err = appendNetworkMounts(container, volumeMounts); err != nil {
  563. return err
  564. }
  565. for _, volumeMount := range volumeMounts {
  566. if forceSyscall {
  567. if err := detachMounted(volumeMount.Destination); err != nil {
  568. logrus.Warnf("%s unmountVolumes: Failed to do lazy umount %v", container.ID, err)
  569. }
  570. }
  571. if volumeMount.Volume != nil {
  572. if err := volumeMount.Volume.Unmount(); err != nil {
  573. return err
  574. }
  575. attributes := map[string]string{
  576. "driver": volumeMount.Volume.DriverName(),
  577. "container": container.ID,
  578. }
  579. volumeEventLog(volumeMount.Volume.Name(), "unmount", attributes)
  580. }
  581. }
  582. return nil
  583. }
  584. // copyExistingContents copies from the source to the destination and
  585. // ensures the ownership is appropriately set.
  586. func copyExistingContents(source, destination string) error {
  587. volList, err := ioutil.ReadDir(source)
  588. if err != nil {
  589. return err
  590. }
  591. if len(volList) > 0 {
  592. srcList, err := ioutil.ReadDir(destination)
  593. if err != nil {
  594. return err
  595. }
  596. if len(srcList) == 0 {
  597. // If the source volume is empty copy files from the root into the volume
  598. if err := chrootarchive.CopyWithTar(source, destination); err != nil {
  599. return err
  600. }
  601. }
  602. }
  603. return copyOwnership(source, destination)
  604. }
  605. // copyOwnership copies the permissions and uid:gid of the source file
  606. // to the destination file
  607. func copyOwnership(source, destination string) error {
  608. stat, err := system.Stat(source)
  609. if err != nil {
  610. return err
  611. }
  612. if err := os.Chown(destination, int(stat.UID()), int(stat.GID())); err != nil {
  613. return err
  614. }
  615. return os.Chmod(destination, os.FileMode(stat.Mode()))
  616. }
  617. // TmpfsMounts returns the list of tmpfs mounts
  618. func (container *Container) TmpfsMounts() []execdriver.Mount {
  619. var mounts []execdriver.Mount
  620. for dest, data := range container.HostConfig.Tmpfs {
  621. mounts = append(mounts, execdriver.Mount{
  622. Source: "tmpfs",
  623. Destination: dest,
  624. Data: data,
  625. })
  626. }
  627. return mounts
  628. }