container_unix.go 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433
  1. // +build linux freebsd
  2. package daemon
  3. import (
  4. "fmt"
  5. "io/ioutil"
  6. "net"
  7. "os"
  8. "path"
  9. "path/filepath"
  10. "strconv"
  11. "strings"
  12. "syscall"
  13. "time"
  14. "github.com/Sirupsen/logrus"
  15. "github.com/docker/docker/daemon/execdriver"
  16. "github.com/docker/docker/daemon/links"
  17. "github.com/docker/docker/daemon/network"
  18. derr "github.com/docker/docker/errors"
  19. "github.com/docker/docker/pkg/directory"
  20. "github.com/docker/docker/pkg/idtools"
  21. "github.com/docker/docker/pkg/nat"
  22. "github.com/docker/docker/pkg/stringid"
  23. "github.com/docker/docker/pkg/symlink"
  24. "github.com/docker/docker/pkg/system"
  25. "github.com/docker/docker/pkg/ulimit"
  26. "github.com/docker/docker/runconfig"
  27. "github.com/docker/docker/utils"
  28. "github.com/docker/docker/volume"
  29. "github.com/docker/libnetwork"
  30. "github.com/docker/libnetwork/drivers/bridge"
  31. "github.com/docker/libnetwork/netlabel"
  32. "github.com/docker/libnetwork/options"
  33. "github.com/docker/libnetwork/types"
  34. "github.com/opencontainers/runc/libcontainer/configs"
  35. "github.com/opencontainers/runc/libcontainer/devices"
  36. "github.com/opencontainers/runc/libcontainer/label"
  37. )
  38. // DefaultPathEnv is unix style list of directories to search for
  39. // executables. Each directory is separated from the next by a colon
  40. // ':' character .
  41. const DefaultPathEnv = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
  42. // Container holds the fields specific to unixen implementations. See
  43. // CommonContainer for standard fields common to all containers.
  44. type Container struct {
  45. CommonContainer
  46. // Fields below here are platform specific.
  47. activeLinks map[string]*links.Link
  48. AppArmorProfile string
  49. HostnamePath string
  50. HostsPath string
  51. ShmPath string // TODO Windows - Factor this out (GH15862)
  52. MqueuePath string // TODO Windows - Factor this out (GH15862)
  53. ResolvConfPath string
  54. Volumes map[string]string // Deprecated since 1.7, kept for backwards compatibility
  55. VolumesRW map[string]bool // Deprecated since 1.7, kept for backwards compatibility
  56. }
  57. func killProcessDirectly(container *Container) error {
  58. if _, err := container.WaitStop(10 * time.Second); err != nil {
  59. // Ensure that we don't kill ourselves
  60. if pid := container.getPID(); pid != 0 {
  61. logrus.Infof("Container %s failed to exit within 10 seconds of kill - trying direct SIGKILL", stringid.TruncateID(container.ID))
  62. if err := syscall.Kill(pid, 9); err != nil {
  63. if err != syscall.ESRCH {
  64. return err
  65. }
  66. logrus.Debugf("Cannot kill process (pid=%d) with signal 9: no such process.", pid)
  67. }
  68. }
  69. }
  70. return nil
  71. }
  72. func (container *Container) setupLinkedContainers() ([]string, error) {
  73. var (
  74. env []string
  75. daemon = container.daemon
  76. )
  77. children, err := daemon.children(container.Name)
  78. if err != nil {
  79. return nil, err
  80. }
  81. if len(children) > 0 {
  82. for linkAlias, child := range children {
  83. if !child.IsRunning() {
  84. return nil, derr.ErrorCodeLinkNotRunning.WithArgs(child.Name, linkAlias)
  85. }
  86. link := links.NewLink(
  87. container.NetworkSettings.IPAddress,
  88. child.NetworkSettings.IPAddress,
  89. linkAlias,
  90. child.Config.Env,
  91. child.Config.ExposedPorts,
  92. )
  93. for _, envVar := range link.ToEnv() {
  94. env = append(env, envVar)
  95. }
  96. }
  97. }
  98. return env, nil
  99. }
  100. func (container *Container) createDaemonEnvironment(linkedEnv []string) []string {
  101. // if a domain name was specified, append it to the hostname (see #7851)
  102. fullHostname := container.Config.Hostname
  103. if container.Config.Domainname != "" {
  104. fullHostname = fmt.Sprintf("%s.%s", fullHostname, container.Config.Domainname)
  105. }
  106. // Setup environment
  107. env := []string{
  108. "PATH=" + DefaultPathEnv,
  109. "HOSTNAME=" + fullHostname,
  110. // Note: we don't set HOME here because it'll get autoset intelligently
  111. // based on the value of USER inside dockerinit, but only if it isn't
  112. // set already (ie, that can be overridden by setting HOME via -e or ENV
  113. // in a Dockerfile).
  114. }
  115. if container.Config.Tty {
  116. env = append(env, "TERM=xterm")
  117. }
  118. env = append(env, linkedEnv...)
  119. // because the env on the container can override certain default values
  120. // we need to replace the 'env' keys where they match and append anything
  121. // else.
  122. env = utils.ReplaceOrAppendEnvValues(env, container.Config.Env)
  123. return env
  124. }
  125. func getDevicesFromPath(deviceMapping runconfig.DeviceMapping) (devs []*configs.Device, err error) {
  126. device, err := devices.DeviceFromPath(deviceMapping.PathOnHost, deviceMapping.CgroupPermissions)
  127. // if there was no error, return the device
  128. if err == nil {
  129. device.Path = deviceMapping.PathInContainer
  130. return append(devs, device), nil
  131. }
  132. // if the device is not a device node
  133. // try to see if it's a directory holding many devices
  134. if err == devices.ErrNotADevice {
  135. // check if it is a directory
  136. if src, e := os.Stat(deviceMapping.PathOnHost); e == nil && src.IsDir() {
  137. // mount the internal devices recursively
  138. filepath.Walk(deviceMapping.PathOnHost, func(dpath string, f os.FileInfo, e error) error {
  139. childDevice, e := devices.DeviceFromPath(dpath, deviceMapping.CgroupPermissions)
  140. if e != nil {
  141. // ignore the device
  142. return nil
  143. }
  144. // add the device to userSpecified devices
  145. childDevice.Path = strings.Replace(dpath, deviceMapping.PathOnHost, deviceMapping.PathInContainer, 1)
  146. devs = append(devs, childDevice)
  147. return nil
  148. })
  149. }
  150. }
  151. if len(devs) > 0 {
  152. return devs, nil
  153. }
  154. return devs, derr.ErrorCodeDeviceInfo.WithArgs(deviceMapping.PathOnHost, err)
  155. }
  156. func populateCommand(c *Container, env []string) error {
  157. var en *execdriver.Network
  158. if !c.Config.NetworkDisabled {
  159. en = &execdriver.Network{}
  160. if !c.daemon.execDriver.SupportsHooks() || c.hostConfig.NetworkMode.IsHost() {
  161. en.NamespacePath = c.NetworkSettings.SandboxKey
  162. }
  163. parts := strings.SplitN(string(c.hostConfig.NetworkMode), ":", 2)
  164. if parts[0] == "container" {
  165. nc, err := c.getNetworkedContainer()
  166. if err != nil {
  167. return err
  168. }
  169. en.ContainerID = nc.ID
  170. }
  171. }
  172. ipc := &execdriver.Ipc{}
  173. var err error
  174. c.ShmPath, err = c.shmPath()
  175. if err != nil {
  176. return err
  177. }
  178. c.MqueuePath, err = c.mqueuePath()
  179. if err != nil {
  180. return err
  181. }
  182. if c.hostConfig.IpcMode.IsContainer() {
  183. ic, err := c.getIpcContainer()
  184. if err != nil {
  185. return err
  186. }
  187. ipc.ContainerID = ic.ID
  188. c.ShmPath = ic.ShmPath
  189. c.MqueuePath = ic.MqueuePath
  190. } else {
  191. ipc.HostIpc = c.hostConfig.IpcMode.IsHost()
  192. if ipc.HostIpc {
  193. if _, err := os.Stat("/dev/shm"); err != nil {
  194. return fmt.Errorf("/dev/shm is not mounted, but must be for --host=ipc")
  195. }
  196. if _, err := os.Stat("/dev/mqueue"); err != nil {
  197. return fmt.Errorf("/dev/mqueue is not mounted, but must be for --host=ipc")
  198. }
  199. c.ShmPath = "/dev/shm"
  200. c.MqueuePath = "/dev/mqueue"
  201. }
  202. }
  203. pid := &execdriver.Pid{}
  204. pid.HostPid = c.hostConfig.PidMode.IsHost()
  205. uts := &execdriver.UTS{
  206. HostUTS: c.hostConfig.UTSMode.IsHost(),
  207. }
  208. // Build lists of devices allowed and created within the container.
  209. var userSpecifiedDevices []*configs.Device
  210. for _, deviceMapping := range c.hostConfig.Devices {
  211. devs, err := getDevicesFromPath(deviceMapping)
  212. if err != nil {
  213. return err
  214. }
  215. userSpecifiedDevices = append(userSpecifiedDevices, devs...)
  216. }
  217. allowedDevices := mergeDevices(configs.DefaultAllowedDevices, userSpecifiedDevices)
  218. autoCreatedDevices := mergeDevices(configs.DefaultAutoCreatedDevices, userSpecifiedDevices)
  219. // TODO: this can be removed after lxc-conf is fully deprecated
  220. lxcConfig, err := mergeLxcConfIntoOptions(c.hostConfig)
  221. if err != nil {
  222. return err
  223. }
  224. var rlimits []*ulimit.Rlimit
  225. ulimits := c.hostConfig.Ulimits
  226. // Merge ulimits with daemon defaults
  227. ulIdx := make(map[string]*ulimit.Ulimit)
  228. for _, ul := range ulimits {
  229. ulIdx[ul.Name] = ul
  230. }
  231. for name, ul := range c.daemon.configStore.Ulimits {
  232. if _, exists := ulIdx[name]; !exists {
  233. ulimits = append(ulimits, ul)
  234. }
  235. }
  236. for _, limit := range ulimits {
  237. rl, err := limit.GetRlimit()
  238. if err != nil {
  239. return err
  240. }
  241. rlimits = append(rlimits, rl)
  242. }
  243. resources := &execdriver.Resources{
  244. CommonResources: execdriver.CommonResources{
  245. Memory: c.hostConfig.Memory,
  246. MemoryReservation: c.hostConfig.MemoryReservation,
  247. CPUShares: c.hostConfig.CPUShares,
  248. BlkioWeight: c.hostConfig.BlkioWeight,
  249. },
  250. MemorySwap: c.hostConfig.MemorySwap,
  251. KernelMemory: c.hostConfig.KernelMemory,
  252. CpusetCpus: c.hostConfig.CpusetCpus,
  253. CpusetMems: c.hostConfig.CpusetMems,
  254. CPUPeriod: c.hostConfig.CPUPeriod,
  255. CPUQuota: c.hostConfig.CPUQuota,
  256. Rlimits: rlimits,
  257. OomKillDisable: c.hostConfig.OomKillDisable,
  258. MemorySwappiness: -1,
  259. }
  260. if c.hostConfig.MemorySwappiness != nil {
  261. resources.MemorySwappiness = *c.hostConfig.MemorySwappiness
  262. }
  263. processConfig := execdriver.ProcessConfig{
  264. Privileged: c.hostConfig.Privileged,
  265. Entrypoint: c.Path,
  266. Arguments: c.Args,
  267. Tty: c.Config.Tty,
  268. User: c.Config.User,
  269. }
  270. processConfig.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
  271. processConfig.Env = env
  272. remappedRoot := &execdriver.User{}
  273. rootUID, rootGID := c.daemon.GetRemappedUIDGID()
  274. if rootUID != 0 {
  275. remappedRoot.UID = rootUID
  276. remappedRoot.GID = rootGID
  277. }
  278. uidMap, gidMap := c.daemon.GetUIDGIDMaps()
  279. c.command = &execdriver.Command{
  280. ID: c.ID,
  281. Rootfs: c.rootfsPath(),
  282. ReadonlyRootfs: c.hostConfig.ReadonlyRootfs,
  283. InitPath: "/.dockerinit",
  284. WorkingDir: c.Config.WorkingDir,
  285. Network: en,
  286. Ipc: ipc,
  287. UIDMapping: uidMap,
  288. GIDMapping: gidMap,
  289. RemappedRoot: remappedRoot,
  290. Pid: pid,
  291. UTS: uts,
  292. Resources: resources,
  293. AllowedDevices: allowedDevices,
  294. AutoCreatedDevices: autoCreatedDevices,
  295. CapAdd: c.hostConfig.CapAdd.Slice(),
  296. CapDrop: c.hostConfig.CapDrop.Slice(),
  297. GroupAdd: c.hostConfig.GroupAdd,
  298. ProcessConfig: processConfig,
  299. ProcessLabel: c.getProcessLabel(),
  300. MountLabel: c.getMountLabel(),
  301. LxcConfig: lxcConfig,
  302. AppArmorProfile: c.AppArmorProfile,
  303. CgroupParent: c.hostConfig.CgroupParent,
  304. }
  305. return nil
  306. }
  307. func mergeDevices(defaultDevices, userDevices []*configs.Device) []*configs.Device {
  308. if len(userDevices) == 0 {
  309. return defaultDevices
  310. }
  311. paths := map[string]*configs.Device{}
  312. for _, d := range userDevices {
  313. paths[d.Path] = d
  314. }
  315. var devs []*configs.Device
  316. for _, d := range defaultDevices {
  317. if _, defined := paths[d.Path]; !defined {
  318. devs = append(devs, d)
  319. }
  320. }
  321. return append(devs, userDevices...)
  322. }
  323. // GetSize returns the real size & virtual size of the container.
  324. func (container *Container) getSize() (int64, int64) {
  325. var (
  326. sizeRw, sizeRootfs int64
  327. err error
  328. driver = container.daemon.driver
  329. )
  330. if err := container.Mount(); err != nil {
  331. logrus.Errorf("Failed to compute size of container rootfs %s: %s", container.ID, err)
  332. return sizeRw, sizeRootfs
  333. }
  334. defer container.Unmount()
  335. initID := fmt.Sprintf("%s-init", container.ID)
  336. sizeRw, err = driver.DiffSize(container.ID, initID)
  337. if err != nil {
  338. logrus.Errorf("Driver %s couldn't return diff size of container %s: %s", driver, container.ID, err)
  339. // FIXME: GetSize should return an error. Not changing it now in case
  340. // there is a side-effect.
  341. sizeRw = -1
  342. }
  343. if _, err = os.Stat(container.basefs); err == nil {
  344. if sizeRootfs, err = directory.Size(container.basefs); err != nil {
  345. sizeRootfs = -1
  346. }
  347. }
  348. return sizeRw, sizeRootfs
  349. }
  350. // Attempt to set the network mounts given a provided destination and
  351. // the path to use for it; return true if the given destination was a
  352. // network mount file
  353. func (container *Container) trySetNetworkMount(destination string, path string) bool {
  354. if destination == "/etc/resolv.conf" {
  355. container.ResolvConfPath = path
  356. return true
  357. }
  358. if destination == "/etc/hostname" {
  359. container.HostnamePath = path
  360. return true
  361. }
  362. if destination == "/etc/hosts" {
  363. container.HostsPath = path
  364. return true
  365. }
  366. return false
  367. }
  368. func (container *Container) buildHostnameFile() error {
  369. hostnamePath, err := container.getRootResourcePath("hostname")
  370. if err != nil {
  371. return err
  372. }
  373. container.HostnamePath = hostnamePath
  374. if container.Config.Domainname != "" {
  375. return ioutil.WriteFile(container.HostnamePath, []byte(fmt.Sprintf("%s.%s\n", container.Config.Hostname, container.Config.Domainname)), 0644)
  376. }
  377. return ioutil.WriteFile(container.HostnamePath, []byte(container.Config.Hostname+"\n"), 0644)
  378. }
  379. func (container *Container) buildSandboxOptions(n libnetwork.Network) ([]libnetwork.SandboxOption, error) {
  380. var (
  381. sboxOptions []libnetwork.SandboxOption
  382. err error
  383. dns []string
  384. dnsSearch []string
  385. dnsOptions []string
  386. )
  387. sboxOptions = append(sboxOptions, libnetwork.OptionHostname(container.Config.Hostname),
  388. libnetwork.OptionDomainname(container.Config.Domainname))
  389. if container.hostConfig.NetworkMode.IsHost() {
  390. sboxOptions = append(sboxOptions, libnetwork.OptionUseDefaultSandbox())
  391. sboxOptions = append(sboxOptions, libnetwork.OptionOriginHostsPath("/etc/hosts"))
  392. sboxOptions = append(sboxOptions, libnetwork.OptionOriginResolvConfPath("/etc/resolv.conf"))
  393. } else if container.daemon.execDriver.SupportsHooks() {
  394. // OptionUseExternalKey is mandatory for userns support.
  395. // But optional for non-userns support
  396. sboxOptions = append(sboxOptions, libnetwork.OptionUseExternalKey())
  397. }
  398. container.HostsPath, err = container.getRootResourcePath("hosts")
  399. if err != nil {
  400. return nil, err
  401. }
  402. sboxOptions = append(sboxOptions, libnetwork.OptionHostsPath(container.HostsPath))
  403. container.ResolvConfPath, err = container.getRootResourcePath("resolv.conf")
  404. if err != nil {
  405. return nil, err
  406. }
  407. sboxOptions = append(sboxOptions, libnetwork.OptionResolvConfPath(container.ResolvConfPath))
  408. if len(container.hostConfig.DNS) > 0 {
  409. dns = container.hostConfig.DNS
  410. } else if len(container.daemon.configStore.DNS) > 0 {
  411. dns = container.daemon.configStore.DNS
  412. }
  413. for _, d := range dns {
  414. sboxOptions = append(sboxOptions, libnetwork.OptionDNS(d))
  415. }
  416. if len(container.hostConfig.DNSSearch) > 0 {
  417. dnsSearch = container.hostConfig.DNSSearch
  418. } else if len(container.daemon.configStore.DNSSearch) > 0 {
  419. dnsSearch = container.daemon.configStore.DNSSearch
  420. }
  421. for _, ds := range dnsSearch {
  422. sboxOptions = append(sboxOptions, libnetwork.OptionDNSSearch(ds))
  423. }
  424. if len(container.hostConfig.DNSOptions) > 0 {
  425. dnsOptions = container.hostConfig.DNSOptions
  426. } else if len(container.daemon.configStore.DNSOptions) > 0 {
  427. dnsOptions = container.daemon.configStore.DNSOptions
  428. }
  429. for _, ds := range dnsOptions {
  430. sboxOptions = append(sboxOptions, libnetwork.OptionDNSOptions(ds))
  431. }
  432. if container.NetworkSettings.SecondaryIPAddresses != nil {
  433. name := container.Config.Hostname
  434. if container.Config.Domainname != "" {
  435. name = name + "." + container.Config.Domainname
  436. }
  437. for _, a := range container.NetworkSettings.SecondaryIPAddresses {
  438. sboxOptions = append(sboxOptions, libnetwork.OptionExtraHost(name, a.Addr))
  439. }
  440. }
  441. for _, extraHost := range container.hostConfig.ExtraHosts {
  442. // allow IPv6 addresses in extra hosts; only split on first ":"
  443. parts := strings.SplitN(extraHost, ":", 2)
  444. sboxOptions = append(sboxOptions, libnetwork.OptionExtraHost(parts[0], parts[1]))
  445. }
  446. // Link feature is supported only for the default bridge network.
  447. // return if this call to build join options is not for default bridge network
  448. if n.Name() != "bridge" {
  449. return sboxOptions, nil
  450. }
  451. ep, _ := container.getEndpointInNetwork(n)
  452. if ep == nil {
  453. return sboxOptions, nil
  454. }
  455. var childEndpoints, parentEndpoints []string
  456. children, err := container.daemon.children(container.Name)
  457. if err != nil {
  458. return nil, err
  459. }
  460. for linkAlias, child := range children {
  461. if !isLinkable(child) {
  462. return nil, fmt.Errorf("Cannot link to %s, as it does not belong to the default network", child.Name)
  463. }
  464. _, alias := path.Split(linkAlias)
  465. // allow access to the linked container via the alias, real name, and container hostname
  466. aliasList := alias + " " + child.Config.Hostname
  467. // only add the name if alias isn't equal to the name
  468. if alias != child.Name[1:] {
  469. aliasList = aliasList + " " + child.Name[1:]
  470. }
  471. sboxOptions = append(sboxOptions, libnetwork.OptionExtraHost(aliasList, child.NetworkSettings.IPAddress))
  472. cEndpoint, _ := child.getEndpointInNetwork(n)
  473. if cEndpoint != nil && cEndpoint.ID() != "" {
  474. childEndpoints = append(childEndpoints, cEndpoint.ID())
  475. }
  476. }
  477. refs := container.daemon.containerGraph().RefPaths(container.ID)
  478. for _, ref := range refs {
  479. if ref.ParentID == "0" {
  480. continue
  481. }
  482. c, err := container.daemon.Get(ref.ParentID)
  483. if err != nil {
  484. logrus.Error(err)
  485. }
  486. if c != nil && !container.daemon.configStore.DisableBridge && container.hostConfig.NetworkMode.IsPrivate() {
  487. logrus.Debugf("Update /etc/hosts of %s for alias %s with ip %s", c.ID, ref.Name, container.NetworkSettings.IPAddress)
  488. sboxOptions = append(sboxOptions, libnetwork.OptionParentUpdate(c.ID, ref.Name, container.NetworkSettings.IPAddress))
  489. if ep.ID() != "" {
  490. parentEndpoints = append(parentEndpoints, ep.ID())
  491. }
  492. }
  493. }
  494. linkOptions := options.Generic{
  495. netlabel.GenericData: options.Generic{
  496. "ParentEndpoints": parentEndpoints,
  497. "ChildEndpoints": childEndpoints,
  498. },
  499. }
  500. sboxOptions = append(sboxOptions, libnetwork.OptionGeneric(linkOptions))
  501. return sboxOptions, nil
  502. }
  503. func isLinkable(child *Container) bool {
  504. // A container is linkable only if it belongs to the default network
  505. for _, nw := range child.NetworkSettings.Networks {
  506. if nw == "bridge" {
  507. return true
  508. }
  509. }
  510. return false
  511. }
  512. func (container *Container) getEndpointInNetwork(n libnetwork.Network) (libnetwork.Endpoint, error) {
  513. endpointName := strings.TrimPrefix(container.Name, "/")
  514. return n.EndpointByName(endpointName)
  515. }
  516. func (container *Container) buildPortMapInfo(ep libnetwork.Endpoint, networkSettings *network.Settings) (*network.Settings, error) {
  517. if ep == nil {
  518. return nil, derr.ErrorCodeEmptyEndpoint
  519. }
  520. if networkSettings == nil {
  521. return nil, derr.ErrorCodeEmptyNetwork
  522. }
  523. driverInfo, err := ep.DriverInfo()
  524. if err != nil {
  525. return nil, err
  526. }
  527. if driverInfo == nil {
  528. // It is not an error for epInfo to be nil
  529. return networkSettings, nil
  530. }
  531. if mac, ok := driverInfo[netlabel.MacAddress]; ok {
  532. networkSettings.MacAddress = mac.(net.HardwareAddr).String()
  533. }
  534. networkSettings.Ports = nat.PortMap{}
  535. if expData, ok := driverInfo[netlabel.ExposedPorts]; ok {
  536. if exposedPorts, ok := expData.([]types.TransportPort); ok {
  537. for _, tp := range exposedPorts {
  538. natPort, err := nat.NewPort(tp.Proto.String(), strconv.Itoa(int(tp.Port)))
  539. if err != nil {
  540. return nil, derr.ErrorCodeParsingPort.WithArgs(tp.Port, err)
  541. }
  542. networkSettings.Ports[natPort] = nil
  543. }
  544. }
  545. }
  546. mapData, ok := driverInfo[netlabel.PortMap]
  547. if !ok {
  548. return networkSettings, nil
  549. }
  550. if portMapping, ok := mapData.([]types.PortBinding); ok {
  551. for _, pp := range portMapping {
  552. natPort, err := nat.NewPort(pp.Proto.String(), strconv.Itoa(int(pp.Port)))
  553. if err != nil {
  554. return nil, err
  555. }
  556. natBndg := nat.PortBinding{HostIP: pp.HostIP.String(), HostPort: strconv.Itoa(int(pp.HostPort))}
  557. networkSettings.Ports[natPort] = append(networkSettings.Ports[natPort], natBndg)
  558. }
  559. }
  560. return networkSettings, nil
  561. }
  562. func (container *Container) buildEndpointInfo(ep libnetwork.Endpoint, networkSettings *network.Settings) (*network.Settings, error) {
  563. if ep == nil {
  564. return nil, derr.ErrorCodeEmptyEndpoint
  565. }
  566. if networkSettings == nil {
  567. return nil, derr.ErrorCodeEmptyNetwork
  568. }
  569. epInfo := ep.Info()
  570. if epInfo == nil {
  571. // It is not an error to get an empty endpoint info
  572. return networkSettings, nil
  573. }
  574. iface := epInfo.Iface()
  575. if iface == nil {
  576. return networkSettings, nil
  577. }
  578. if iface.Address() != nil {
  579. ones, _ := iface.Address().Mask.Size()
  580. networkSettings.IPAddress = iface.Address().IP.String()
  581. networkSettings.IPPrefixLen = ones
  582. }
  583. if iface.AddressIPv6() != nil && iface.AddressIPv6().IP.To16() != nil {
  584. onesv6, _ := iface.AddressIPv6().Mask.Size()
  585. networkSettings.GlobalIPv6Address = iface.AddressIPv6().IP.String()
  586. networkSettings.GlobalIPv6PrefixLen = onesv6
  587. }
  588. return networkSettings, nil
  589. }
  590. func (container *Container) updateJoinInfo(ep libnetwork.Endpoint) error {
  591. epInfo := ep.Info()
  592. if epInfo == nil {
  593. // It is not an error to get an empty endpoint info
  594. return nil
  595. }
  596. container.NetworkSettings.Gateway = epInfo.Gateway().String()
  597. if epInfo.GatewayIPv6().To16() != nil {
  598. container.NetworkSettings.IPv6Gateway = epInfo.GatewayIPv6().String()
  599. }
  600. return nil
  601. }
  602. func (container *Container) updateNetworkSettings(n libnetwork.Network) error {
  603. if container.NetworkSettings == nil {
  604. container.NetworkSettings = &network.Settings{Networks: []string{}}
  605. }
  606. settings := container.NetworkSettings
  607. for _, s := range settings.Networks {
  608. sn, err := container.daemon.FindNetwork(s)
  609. if err != nil {
  610. continue
  611. }
  612. if sn.Name() == n.Name() {
  613. // Avoid duplicate config
  614. return nil
  615. }
  616. if !runconfig.NetworkMode(sn.Type()).IsPrivate() ||
  617. !runconfig.NetworkMode(n.Type()).IsPrivate() {
  618. return runconfig.ErrConflictSharedNetwork
  619. }
  620. if runconfig.NetworkMode(sn.Name()).IsNone() ||
  621. runconfig.NetworkMode(n.Name()).IsNone() {
  622. return runconfig.ErrConflictNoNetwork
  623. }
  624. }
  625. settings.Networks = append(settings.Networks, n.Name())
  626. return nil
  627. }
  628. func (container *Container) updateEndpointNetworkSettings(n libnetwork.Network, ep libnetwork.Endpoint) error {
  629. networkSettings, err := container.buildPortMapInfo(ep, container.NetworkSettings)
  630. if err != nil {
  631. return err
  632. }
  633. networkSettings, err = container.buildEndpointInfo(ep, networkSettings)
  634. if err != nil {
  635. return err
  636. }
  637. if container.hostConfig.NetworkMode == runconfig.NetworkMode("bridge") {
  638. networkSettings.Bridge = container.daemon.configStore.Bridge.Iface
  639. }
  640. return nil
  641. }
  642. func (container *Container) updateSandboxNetworkSettings(sb libnetwork.Sandbox) error {
  643. container.NetworkSettings.SandboxID = sb.ID()
  644. container.NetworkSettings.SandboxKey = sb.Key()
  645. return nil
  646. }
  647. // UpdateNetwork is used to update the container's network (e.g. when linked containers
  648. // get removed/unlinked).
  649. func (container *Container) updateNetwork() error {
  650. ctrl := container.daemon.netController
  651. sid := container.NetworkSettings.SandboxID
  652. sb, err := ctrl.SandboxByID(sid)
  653. if err != nil {
  654. return derr.ErrorCodeNoSandbox.WithArgs(sid, err)
  655. }
  656. // Find if container is connected to the default bridge network
  657. var n libnetwork.Network
  658. for _, name := range container.NetworkSettings.Networks {
  659. sn, err := container.daemon.FindNetwork(name)
  660. if err != nil {
  661. continue
  662. }
  663. if sn.Name() == "bridge" {
  664. n = sn
  665. break
  666. }
  667. }
  668. if n == nil {
  669. // Not connected to the default bridge network; Nothing to do
  670. return nil
  671. }
  672. options, err := container.buildSandboxOptions(n)
  673. if err != nil {
  674. return derr.ErrorCodeNetworkUpdate.WithArgs(err)
  675. }
  676. if err := sb.Refresh(options...); err != nil {
  677. return derr.ErrorCodeNetworkRefresh.WithArgs(sid, err)
  678. }
  679. return nil
  680. }
  681. func (container *Container) buildCreateEndpointOptions(n libnetwork.Network) ([]libnetwork.EndpointOption, error) {
  682. var (
  683. portSpecs = make(nat.PortSet)
  684. bindings = make(nat.PortMap)
  685. pbList []types.PortBinding
  686. exposeList []types.TransportPort
  687. createOptions []libnetwork.EndpointOption
  688. )
  689. if container.Config.ExposedPorts != nil {
  690. portSpecs = container.Config.ExposedPorts
  691. }
  692. if container.hostConfig.PortBindings != nil {
  693. for p, b := range container.hostConfig.PortBindings {
  694. bindings[p] = []nat.PortBinding{}
  695. for _, bb := range b {
  696. bindings[p] = append(bindings[p], nat.PortBinding{
  697. HostIP: bb.HostIP,
  698. HostPort: bb.HostPort,
  699. })
  700. }
  701. }
  702. }
  703. ports := make([]nat.Port, len(portSpecs))
  704. var i int
  705. for p := range portSpecs {
  706. ports[i] = p
  707. i++
  708. }
  709. nat.SortPortMap(ports, bindings)
  710. for _, port := range ports {
  711. expose := types.TransportPort{}
  712. expose.Proto = types.ParseProtocol(port.Proto())
  713. expose.Port = uint16(port.Int())
  714. exposeList = append(exposeList, expose)
  715. pb := types.PortBinding{Port: expose.Port, Proto: expose.Proto}
  716. binding := bindings[port]
  717. for i := 0; i < len(binding); i++ {
  718. pbCopy := pb.GetCopy()
  719. newP, err := nat.NewPort(nat.SplitProtoPort(binding[i].HostPort))
  720. var portStart, portEnd int
  721. if err == nil {
  722. portStart, portEnd, err = newP.Range()
  723. }
  724. if err != nil {
  725. return nil, derr.ErrorCodeHostPort.WithArgs(binding[i].HostPort, err)
  726. }
  727. pbCopy.HostPort = uint16(portStart)
  728. pbCopy.HostPortEnd = uint16(portEnd)
  729. pbCopy.HostIP = net.ParseIP(binding[i].HostIP)
  730. pbList = append(pbList, pbCopy)
  731. }
  732. if container.hostConfig.PublishAllPorts && len(binding) == 0 {
  733. pbList = append(pbList, pb)
  734. }
  735. }
  736. createOptions = append(createOptions,
  737. libnetwork.CreateOptionPortMapping(pbList),
  738. libnetwork.CreateOptionExposedPorts(exposeList))
  739. if container.Config.MacAddress != "" {
  740. mac, err := net.ParseMAC(container.Config.MacAddress)
  741. if err != nil {
  742. return nil, err
  743. }
  744. genericOption := options.Generic{
  745. netlabel.MacAddress: mac,
  746. }
  747. createOptions = append(createOptions, libnetwork.EndpointOptionGeneric(genericOption))
  748. }
  749. if n.Name() == "bridge" || container.NetworkSettings.IsAnonymousEndpoint {
  750. createOptions = append(createOptions, libnetwork.CreateOptionAnonymous())
  751. }
  752. return createOptions, nil
  753. }
  754. func createNetwork(controller libnetwork.NetworkController, dnet string, driver string) (libnetwork.Network, error) {
  755. createOptions := []libnetwork.NetworkOption{}
  756. genericOption := options.Generic{}
  757. // Bridge driver is special due to legacy reasons
  758. if runconfig.NetworkMode(driver).IsBridge() {
  759. genericOption[netlabel.GenericData] = map[string]string{
  760. bridge.BridgeName: dnet,
  761. }
  762. networkOption := libnetwork.NetworkOptionGeneric(genericOption)
  763. createOptions = append(createOptions, networkOption)
  764. }
  765. return controller.NewNetwork(driver, dnet, createOptions...)
  766. }
  767. func (container *Container) allocateNetwork() error {
  768. settings := container.NetworkSettings.Networks
  769. updateSettings := false
  770. if settings == nil {
  771. mode := container.hostConfig.NetworkMode
  772. controller := container.daemon.netController
  773. if container.Config.NetworkDisabled || mode.IsContainer() {
  774. return nil
  775. }
  776. networkName := mode.NetworkName()
  777. if mode.IsDefault() {
  778. networkName = controller.Config().Daemon.DefaultNetwork
  779. }
  780. settings = []string{networkName}
  781. updateSettings = true
  782. }
  783. for _, n := range settings {
  784. if err := container.connectToNetwork(n, updateSettings); err != nil {
  785. return err
  786. }
  787. }
  788. return container.writeHostConfig()
  789. }
  790. // ConnectToNetwork connects a container to a netork
  791. func (container *Container) ConnectToNetwork(idOrName string) error {
  792. if !container.Running {
  793. return derr.ErrorCodeNotRunning.WithArgs(container.ID)
  794. }
  795. return container.connectToNetwork(idOrName, true)
  796. }
  797. func (container *Container) connectToNetwork(idOrName string, updateSettings bool) error {
  798. var err error
  799. if container.hostConfig.NetworkMode.IsContainer() {
  800. return runconfig.ErrConflictSharedNetwork
  801. }
  802. if runconfig.NetworkMode(idOrName).IsBridge() &&
  803. container.daemon.configStore.DisableBridge {
  804. container.Config.NetworkDisabled = true
  805. return nil
  806. }
  807. controller := container.daemon.netController
  808. n, err := container.daemon.FindNetwork(idOrName)
  809. if err != nil {
  810. return err
  811. }
  812. if updateSettings {
  813. if err := container.updateNetworkSettings(n); err != nil {
  814. return err
  815. }
  816. }
  817. ep, err := container.getEndpointInNetwork(n)
  818. if err == nil {
  819. return fmt.Errorf("container already connected to network %s", idOrName)
  820. }
  821. if _, ok := err.(libnetwork.ErrNoSuchEndpoint); !ok {
  822. return err
  823. }
  824. createOptions, err := container.buildCreateEndpointOptions(n)
  825. if err != nil {
  826. return err
  827. }
  828. endpointName := strings.TrimPrefix(container.Name, "/")
  829. ep, err = n.CreateEndpoint(endpointName, createOptions...)
  830. if err != nil {
  831. return err
  832. }
  833. defer func() {
  834. if err != nil {
  835. if e := ep.Delete(); e != nil {
  836. logrus.Warnf("Could not rollback container connection to network %s", idOrName)
  837. }
  838. }
  839. }()
  840. if err := container.updateEndpointNetworkSettings(n, ep); err != nil {
  841. return err
  842. }
  843. var sb libnetwork.Sandbox
  844. controller.WalkSandboxes(func(s libnetwork.Sandbox) bool {
  845. if s.ContainerID() == container.ID {
  846. sb = s
  847. return true
  848. }
  849. return false
  850. })
  851. if sb == nil {
  852. options, err := container.buildSandboxOptions(n)
  853. if err != nil {
  854. return err
  855. }
  856. sb, err = controller.NewSandbox(container.ID, options...)
  857. if err != nil {
  858. return err
  859. }
  860. container.updateSandboxNetworkSettings(sb)
  861. }
  862. if err := ep.Join(sb); err != nil {
  863. return err
  864. }
  865. if err := container.updateJoinInfo(ep); err != nil {
  866. return derr.ErrorCodeJoinInfo.WithArgs(err)
  867. }
  868. return nil
  869. }
  870. func (container *Container) initializeNetworking() error {
  871. var err error
  872. if container.hostConfig.NetworkMode.IsContainer() {
  873. // we need to get the hosts files from the container to join
  874. nc, err := container.getNetworkedContainer()
  875. if err != nil {
  876. return err
  877. }
  878. container.HostnamePath = nc.HostnamePath
  879. container.HostsPath = nc.HostsPath
  880. container.ResolvConfPath = nc.ResolvConfPath
  881. container.Config.Hostname = nc.Config.Hostname
  882. container.Config.Domainname = nc.Config.Domainname
  883. return nil
  884. }
  885. if container.hostConfig.NetworkMode.IsHost() {
  886. container.Config.Hostname, err = os.Hostname()
  887. if err != nil {
  888. return err
  889. }
  890. parts := strings.SplitN(container.Config.Hostname, ".", 2)
  891. if len(parts) > 1 {
  892. container.Config.Hostname = parts[0]
  893. container.Config.Domainname = parts[1]
  894. }
  895. }
  896. if err := container.allocateNetwork(); err != nil {
  897. return err
  898. }
  899. return container.buildHostnameFile()
  900. }
  901. // called from the libcontainer pre-start hook to set the network
  902. // namespace configuration linkage to the libnetwork "sandbox" entity
  903. func (container *Container) setNetworkNamespaceKey(pid int) error {
  904. path := fmt.Sprintf("/proc/%d/ns/net", pid)
  905. var sandbox libnetwork.Sandbox
  906. search := libnetwork.SandboxContainerWalker(&sandbox, container.ID)
  907. container.daemon.netController.WalkSandboxes(search)
  908. if sandbox == nil {
  909. return derr.ErrorCodeNoSandbox.WithArgs(container.ID)
  910. }
  911. return sandbox.SetKey(path)
  912. }
  913. func (container *Container) getIpcContainer() (*Container, error) {
  914. containerID := container.hostConfig.IpcMode.Container()
  915. c, err := container.daemon.Get(containerID)
  916. if err != nil {
  917. return nil, err
  918. }
  919. if !c.IsRunning() {
  920. return nil, derr.ErrorCodeIPCRunning
  921. }
  922. return c, nil
  923. }
  924. func (container *Container) setupWorkingDirectory() error {
  925. if container.Config.WorkingDir != "" {
  926. container.Config.WorkingDir = filepath.Clean(container.Config.WorkingDir)
  927. pth, err := container.GetResourcePath(container.Config.WorkingDir)
  928. if err != nil {
  929. return err
  930. }
  931. pthInfo, err := os.Stat(pth)
  932. if err != nil {
  933. if !os.IsNotExist(err) {
  934. return err
  935. }
  936. if err := system.MkdirAll(pth, 0755); err != nil {
  937. return err
  938. }
  939. }
  940. if pthInfo != nil && !pthInfo.IsDir() {
  941. return derr.ErrorCodeNotADir.WithArgs(container.Config.WorkingDir)
  942. }
  943. }
  944. return nil
  945. }
  946. func (container *Container) getNetworkedContainer() (*Container, error) {
  947. parts := strings.SplitN(string(container.hostConfig.NetworkMode), ":", 2)
  948. switch parts[0] {
  949. case "container":
  950. if len(parts) != 2 {
  951. return nil, derr.ErrorCodeParseContainer
  952. }
  953. nc, err := container.daemon.Get(parts[1])
  954. if err != nil {
  955. return nil, err
  956. }
  957. if container == nc {
  958. return nil, derr.ErrorCodeJoinSelf
  959. }
  960. if !nc.IsRunning() {
  961. return nil, derr.ErrorCodeJoinRunning.WithArgs(parts[1])
  962. }
  963. return nc, nil
  964. default:
  965. return nil, derr.ErrorCodeModeNotContainer
  966. }
  967. }
  968. func (container *Container) releaseNetwork() {
  969. if container.hostConfig.NetworkMode.IsContainer() || container.Config.NetworkDisabled {
  970. return
  971. }
  972. sid := container.NetworkSettings.SandboxID
  973. networks := container.NetworkSettings.Networks
  974. container.NetworkSettings = &network.Settings{Networks: networks}
  975. if sid == "" || len(networks) == 0 {
  976. return
  977. }
  978. sb, err := container.daemon.netController.SandboxByID(sid)
  979. if err != nil {
  980. logrus.Errorf("error locating sandbox id %s: %v", sid, err)
  981. return
  982. }
  983. if err := sb.Delete(); err != nil {
  984. logrus.Errorf("Error deleting sandbox id %s for container %s: %v", sid, container.ID, err)
  985. }
  986. }
  987. // DisconnectFromNetwork disconnects a container from a network
  988. func (container *Container) DisconnectFromNetwork(n libnetwork.Network) error {
  989. if !container.Running {
  990. return derr.ErrorCodeNotRunning.WithArgs(container.ID)
  991. }
  992. return container.disconnectFromNetwork(n)
  993. }
  994. func (container *Container) disconnectFromNetwork(n libnetwork.Network) error {
  995. var (
  996. ep libnetwork.Endpoint
  997. sbox libnetwork.Sandbox
  998. )
  999. s := func(current libnetwork.Endpoint) bool {
  1000. if sb := current.Info().Sandbox(); sb != nil {
  1001. if sb.ContainerID() == container.ID {
  1002. ep = current
  1003. sbox = sb
  1004. return true
  1005. }
  1006. }
  1007. return false
  1008. }
  1009. n.WalkEndpoints(s)
  1010. if ep == nil {
  1011. return fmt.Errorf("container %s is not connected to the network", container.ID)
  1012. }
  1013. if err := ep.Leave(sbox); err != nil {
  1014. return fmt.Errorf("container %s failed to leave network %s: %v", container.ID, n.Name(), err)
  1015. }
  1016. if err := ep.Delete(); err != nil {
  1017. return fmt.Errorf("endpoint delete failed for container %s on network %s: %v", container.ID, n.Name(), err)
  1018. }
  1019. networks := container.NetworkSettings.Networks
  1020. for i, s := range networks {
  1021. sn, err := container.daemon.FindNetwork(s)
  1022. if err != nil {
  1023. continue
  1024. }
  1025. if sn.Name() == n.Name() {
  1026. networks = append(networks[:i], networks[i+1:]...)
  1027. container.NetworkSettings.Networks = networks
  1028. break
  1029. }
  1030. }
  1031. return nil
  1032. }
  1033. // appendNetworkMounts appends any network mounts to the array of mount points passed in
  1034. func appendNetworkMounts(container *Container, volumeMounts []volume.MountPoint) ([]volume.MountPoint, error) {
  1035. for _, mnt := range container.networkMounts() {
  1036. dest, err := container.GetResourcePath(mnt.Destination)
  1037. if err != nil {
  1038. return nil, err
  1039. }
  1040. volumeMounts = append(volumeMounts, volume.MountPoint{Destination: dest})
  1041. }
  1042. return volumeMounts, nil
  1043. }
  1044. func (container *Container) networkMounts() []execdriver.Mount {
  1045. var mounts []execdriver.Mount
  1046. shared := container.hostConfig.NetworkMode.IsContainer()
  1047. if container.ResolvConfPath != "" {
  1048. if _, err := os.Stat(container.ResolvConfPath); err != nil {
  1049. logrus.Warnf("ResolvConfPath set to %q, but can't stat this filename (err = %v); skipping", container.ResolvConfPath, err)
  1050. } else {
  1051. label.Relabel(container.ResolvConfPath, container.MountLabel, shared)
  1052. writable := !container.hostConfig.ReadonlyRootfs
  1053. if m, exists := container.MountPoints["/etc/resolv.conf"]; exists {
  1054. writable = m.RW
  1055. }
  1056. mounts = append(mounts, execdriver.Mount{
  1057. Source: container.ResolvConfPath,
  1058. Destination: "/etc/resolv.conf",
  1059. Writable: writable,
  1060. Private: true,
  1061. })
  1062. }
  1063. }
  1064. if container.HostnamePath != "" {
  1065. if _, err := os.Stat(container.HostnamePath); err != nil {
  1066. logrus.Warnf("HostnamePath set to %q, but can't stat this filename (err = %v); skipping", container.HostnamePath, err)
  1067. } else {
  1068. label.Relabel(container.HostnamePath, container.MountLabel, shared)
  1069. writable := !container.hostConfig.ReadonlyRootfs
  1070. if m, exists := container.MountPoints["/etc/hostname"]; exists {
  1071. writable = m.RW
  1072. }
  1073. mounts = append(mounts, execdriver.Mount{
  1074. Source: container.HostnamePath,
  1075. Destination: "/etc/hostname",
  1076. Writable: writable,
  1077. Private: true,
  1078. })
  1079. }
  1080. }
  1081. if container.HostsPath != "" {
  1082. if _, err := os.Stat(container.HostsPath); err != nil {
  1083. logrus.Warnf("HostsPath set to %q, but can't stat this filename (err = %v); skipping", container.HostsPath, err)
  1084. } else {
  1085. label.Relabel(container.HostsPath, container.MountLabel, shared)
  1086. writable := !container.hostConfig.ReadonlyRootfs
  1087. if m, exists := container.MountPoints["/etc/hosts"]; exists {
  1088. writable = m.RW
  1089. }
  1090. mounts = append(mounts, execdriver.Mount{
  1091. Source: container.HostsPath,
  1092. Destination: "/etc/hosts",
  1093. Writable: writable,
  1094. Private: true,
  1095. })
  1096. }
  1097. }
  1098. return mounts
  1099. }
  1100. func (container *Container) copyImagePathContent(v volume.Volume, destination string) error {
  1101. rootfs, err := symlink.FollowSymlinkInScope(filepath.Join(container.basefs, destination), container.basefs)
  1102. if err != nil {
  1103. return err
  1104. }
  1105. if _, err = ioutil.ReadDir(rootfs); err != nil {
  1106. if os.IsNotExist(err) {
  1107. return nil
  1108. }
  1109. return err
  1110. }
  1111. path, err := v.Mount()
  1112. if err != nil {
  1113. return err
  1114. }
  1115. if err := copyExistingContents(rootfs, path); err != nil {
  1116. return err
  1117. }
  1118. return v.Unmount()
  1119. }
  1120. func (container *Container) shmPath() (string, error) {
  1121. return container.getRootResourcePath("shm")
  1122. }
  1123. func (container *Container) mqueuePath() (string, error) {
  1124. return container.getRootResourcePath("mqueue")
  1125. }
  1126. func (container *Container) hasMountFor(path string) bool {
  1127. _, exists := container.MountPoints[path]
  1128. return exists
  1129. }
  1130. func (container *Container) setupIpcDirs() error {
  1131. rootUID, rootGID := container.daemon.GetRemappedUIDGID()
  1132. if !container.hasMountFor("/dev/shm") {
  1133. shmPath, err := container.shmPath()
  1134. if err != nil {
  1135. return err
  1136. }
  1137. if err := idtools.MkdirAllAs(shmPath, 0700, rootUID, rootGID); err != nil {
  1138. return err
  1139. }
  1140. if err := syscall.Mount("shm", shmPath, "tmpfs", uintptr(syscall.MS_NOEXEC|syscall.MS_NOSUID|syscall.MS_NODEV), label.FormatMountLabel("mode=1777,size=65536k", container.getMountLabel())); err != nil {
  1141. return fmt.Errorf("mounting shm tmpfs: %s", err)
  1142. }
  1143. if err := os.Chown(shmPath, rootUID, rootGID); err != nil {
  1144. return err
  1145. }
  1146. }
  1147. if !container.hasMountFor("/dev/mqueue") {
  1148. mqueuePath, err := container.mqueuePath()
  1149. if err != nil {
  1150. return err
  1151. }
  1152. if err := idtools.MkdirAllAs(mqueuePath, 0700, rootUID, rootGID); err != nil {
  1153. return err
  1154. }
  1155. if err := syscall.Mount("mqueue", mqueuePath, "mqueue", uintptr(syscall.MS_NOEXEC|syscall.MS_NOSUID|syscall.MS_NODEV), ""); err != nil {
  1156. return fmt.Errorf("mounting mqueue mqueue : %s", err)
  1157. }
  1158. if err := os.Chown(mqueuePath, rootUID, rootGID); err != nil {
  1159. return err
  1160. }
  1161. }
  1162. return nil
  1163. }
  1164. func (container *Container) unmountIpcMounts() error {
  1165. if container.hostConfig.IpcMode.IsContainer() || container.hostConfig.IpcMode.IsHost() {
  1166. return nil
  1167. }
  1168. var errors []string
  1169. if !container.hasMountFor("/dev/shm") {
  1170. shmPath, err := container.shmPath()
  1171. if err != nil {
  1172. logrus.Error(err)
  1173. errors = append(errors, err.Error())
  1174. } else {
  1175. if err := detachMounted(shmPath); err != nil {
  1176. logrus.Errorf("failed to umount %s: %v", shmPath, err)
  1177. errors = append(errors, err.Error())
  1178. }
  1179. }
  1180. }
  1181. if !container.hasMountFor("/dev/mqueue") {
  1182. mqueuePath, err := container.mqueuePath()
  1183. if err != nil {
  1184. logrus.Error(err)
  1185. errors = append(errors, err.Error())
  1186. } else {
  1187. if err := detachMounted(mqueuePath); err != nil {
  1188. logrus.Errorf("failed to umount %s: %v", mqueuePath, err)
  1189. errors = append(errors, err.Error())
  1190. }
  1191. }
  1192. }
  1193. if len(errors) > 0 {
  1194. return fmt.Errorf("failed to cleanup ipc mounts:\n%v", strings.Join(errors, "\n"))
  1195. }
  1196. return nil
  1197. }
  1198. func (container *Container) ipcMounts() []execdriver.Mount {
  1199. var mounts []execdriver.Mount
  1200. if !container.hasMountFor("/dev/shm") {
  1201. label.SetFileLabel(container.ShmPath, container.MountLabel)
  1202. mounts = append(mounts, execdriver.Mount{
  1203. Source: container.ShmPath,
  1204. Destination: "/dev/shm",
  1205. Writable: true,
  1206. Private: true,
  1207. })
  1208. }
  1209. if !container.hasMountFor("/dev/mqueue") {
  1210. label.SetFileLabel(container.MqueuePath, container.MountLabel)
  1211. mounts = append(mounts, execdriver.Mount{
  1212. Source: container.MqueuePath,
  1213. Destination: "/dev/mqueue",
  1214. Writable: true,
  1215. Private: true,
  1216. })
  1217. }
  1218. return mounts
  1219. }
  1220. func detachMounted(path string) error {
  1221. return syscall.Unmount(path, syscall.MNT_DETACH)
  1222. }