container_unix.go 40 KB

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