container_unix.go 40 KB

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