container_unix.go 40 KB

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