container_unix.go 22 KB

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