container_unix.go 22 KB

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