container_unix.go 41 KB

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