container_unix.go 41 KB

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