container_unix.go 22 KB

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