container_unix.go 22 KB

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