container_unix.go 22 KB

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