container_unix.go 21 KB

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