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