container_unix.go 22 KB

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