container_unix.go 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328
  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/context"
  16. "github.com/docker/docker/daemon/execdriver"
  17. "github.com/docker/docker/daemon/links"
  18. "github.com/docker/docker/daemon/network"
  19. derr "github.com/docker/docker/errors"
  20. "github.com/docker/docker/pkg/directory"
  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(ctx context.Context) ([]string, error) {
  73. var (
  74. env []string
  75. daemon = container.daemon
  76. )
  77. children, err := daemon.children(ctx, 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(ctx context.Context, 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(ctx)
  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(ctx)
  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. c.command = &execdriver.Command{
  265. ID: c.ID,
  266. Rootfs: c.rootfsPath(),
  267. ReadonlyRootfs: c.hostConfig.ReadonlyRootfs,
  268. InitPath: "/.dockerinit",
  269. WorkingDir: c.Config.WorkingDir,
  270. Network: en,
  271. Ipc: ipc,
  272. Pid: pid,
  273. UTS: uts,
  274. Resources: resources,
  275. AllowedDevices: allowedDevices,
  276. AutoCreatedDevices: autoCreatedDevices,
  277. CapAdd: c.hostConfig.CapAdd.Slice(),
  278. CapDrop: c.hostConfig.CapDrop.Slice(),
  279. GroupAdd: c.hostConfig.GroupAdd,
  280. ProcessConfig: processConfig,
  281. ProcessLabel: c.getProcessLabel(),
  282. MountLabel: c.getMountLabel(),
  283. LxcConfig: lxcConfig,
  284. AppArmorProfile: c.AppArmorProfile,
  285. CgroupParent: c.hostConfig.CgroupParent,
  286. }
  287. return nil
  288. }
  289. func mergeDevices(defaultDevices, userDevices []*configs.Device) []*configs.Device {
  290. if len(userDevices) == 0 {
  291. return defaultDevices
  292. }
  293. paths := map[string]*configs.Device{}
  294. for _, d := range userDevices {
  295. paths[d.Path] = d
  296. }
  297. var devs []*configs.Device
  298. for _, d := range defaultDevices {
  299. if _, defined := paths[d.Path]; !defined {
  300. devs = append(devs, d)
  301. }
  302. }
  303. return append(devs, userDevices...)
  304. }
  305. // GetSize returns the real size & virtual size of the container.
  306. func (container *Container) getSize(ctx context.Context) (int64, int64) {
  307. var (
  308. sizeRw, sizeRootfs int64
  309. err error
  310. driver = container.daemon.driver
  311. )
  312. if err := container.Mount(ctx); err != nil {
  313. logrus.Errorf("Failed to compute size of container rootfs %s: %s", container.ID, err)
  314. return sizeRw, sizeRootfs
  315. }
  316. defer container.Unmount(ctx)
  317. initID := fmt.Sprintf("%s-init", container.ID)
  318. sizeRw, err = driver.DiffSize(container.ID, initID)
  319. if err != nil {
  320. logrus.Errorf("Driver %s couldn't return diff size of container %s: %s", driver, container.ID, err)
  321. // FIXME: GetSize should return an error. Not changing it now in case
  322. // there is a side-effect.
  323. sizeRw = -1
  324. }
  325. if _, err = os.Stat(container.basefs); err == nil {
  326. if sizeRootfs, err = directory.Size(container.basefs); err != nil {
  327. sizeRootfs = -1
  328. }
  329. }
  330. return sizeRw, sizeRootfs
  331. }
  332. // Attempt to set the network mounts given a provided destination and
  333. // the path to use for it; return true if the given destination was a
  334. // network mount file
  335. func (container *Container) trySetNetworkMount(destination string, path string) bool {
  336. if destination == "/etc/resolv.conf" {
  337. container.ResolvConfPath = path
  338. return true
  339. }
  340. if destination == "/etc/hostname" {
  341. container.HostnamePath = path
  342. return true
  343. }
  344. if destination == "/etc/hosts" {
  345. container.HostsPath = path
  346. return true
  347. }
  348. return false
  349. }
  350. func (container *Container) buildHostnameFile() error {
  351. hostnamePath, err := container.getRootResourcePath("hostname")
  352. if err != nil {
  353. return err
  354. }
  355. container.HostnamePath = hostnamePath
  356. if container.Config.Domainname != "" {
  357. return ioutil.WriteFile(container.HostnamePath, []byte(fmt.Sprintf("%s.%s\n", container.Config.Hostname, container.Config.Domainname)), 0644)
  358. }
  359. return ioutil.WriteFile(container.HostnamePath, []byte(container.Config.Hostname+"\n"), 0644)
  360. }
  361. func (container *Container) buildSandboxOptions(ctx context.Context) ([]libnetwork.SandboxOption, error) {
  362. var (
  363. sboxOptions []libnetwork.SandboxOption
  364. err error
  365. dns []string
  366. dnsSearch []string
  367. dnsOptions []string
  368. )
  369. sboxOptions = append(sboxOptions, libnetwork.OptionHostname(container.Config.Hostname),
  370. libnetwork.OptionDomainname(container.Config.Domainname))
  371. if container.hostConfig.NetworkMode.IsHost() {
  372. sboxOptions = append(sboxOptions, libnetwork.OptionUseDefaultSandbox())
  373. sboxOptions = append(sboxOptions, libnetwork.OptionOriginHostsPath("/etc/hosts"))
  374. sboxOptions = append(sboxOptions, libnetwork.OptionOriginResolvConfPath("/etc/resolv.conf"))
  375. } else if container.daemon.execDriver.SupportsHooks() {
  376. // OptionUseExternalKey is mandatory for userns support.
  377. // But optional for non-userns support
  378. sboxOptions = append(sboxOptions, libnetwork.OptionUseExternalKey())
  379. }
  380. container.HostsPath, err = container.getRootResourcePath("hosts")
  381. if err != nil {
  382. return nil, err
  383. }
  384. sboxOptions = append(sboxOptions, libnetwork.OptionHostsPath(container.HostsPath))
  385. container.ResolvConfPath, err = container.getRootResourcePath("resolv.conf")
  386. if err != nil {
  387. return nil, err
  388. }
  389. sboxOptions = append(sboxOptions, libnetwork.OptionResolvConfPath(container.ResolvConfPath))
  390. if len(container.hostConfig.DNS) > 0 {
  391. dns = container.hostConfig.DNS
  392. } else if len(container.daemon.configStore.DNS) > 0 {
  393. dns = container.daemon.configStore.DNS
  394. }
  395. for _, d := range dns {
  396. sboxOptions = append(sboxOptions, libnetwork.OptionDNS(d))
  397. }
  398. if len(container.hostConfig.DNSSearch) > 0 {
  399. dnsSearch = container.hostConfig.DNSSearch
  400. } else if len(container.daemon.configStore.DNSSearch) > 0 {
  401. dnsSearch = container.daemon.configStore.DNSSearch
  402. }
  403. for _, ds := range dnsSearch {
  404. sboxOptions = append(sboxOptions, libnetwork.OptionDNSSearch(ds))
  405. }
  406. if len(container.hostConfig.DNSOptions) > 0 {
  407. dnsOptions = container.hostConfig.DNSOptions
  408. } else if len(container.daemon.configStore.DNSOptions) > 0 {
  409. dnsOptions = container.daemon.configStore.DNSOptions
  410. }
  411. for _, ds := range dnsOptions {
  412. sboxOptions = append(sboxOptions, libnetwork.OptionDNSOptions(ds))
  413. }
  414. if container.NetworkSettings.SecondaryIPAddresses != nil {
  415. name := container.Config.Hostname
  416. if container.Config.Domainname != "" {
  417. name = name + "." + container.Config.Domainname
  418. }
  419. for _, a := range container.NetworkSettings.SecondaryIPAddresses {
  420. sboxOptions = append(sboxOptions, libnetwork.OptionExtraHost(name, a.Addr))
  421. }
  422. }
  423. var childEndpoints, parentEndpoints []string
  424. children, err := container.daemon.children(ctx, container.Name)
  425. if err != nil {
  426. return nil, err
  427. }
  428. for linkAlias, child := range children {
  429. _, alias := path.Split(linkAlias)
  430. // allow access to the linked container via the alias, real name, and container hostname
  431. aliasList := alias + " " + child.Config.Hostname
  432. // only add the name if alias isn't equal to the name
  433. if alias != child.Name[1:] {
  434. aliasList = aliasList + " " + child.Name[1:]
  435. }
  436. sboxOptions = append(sboxOptions, libnetwork.OptionExtraHost(aliasList, child.NetworkSettings.IPAddress))
  437. if child.NetworkSettings.EndpointID != "" {
  438. childEndpoints = append(childEndpoints, child.NetworkSettings.EndpointID)
  439. }
  440. }
  441. for _, extraHost := range container.hostConfig.ExtraHosts {
  442. // allow IPv6 addresses in extra hosts; only split on first ":"
  443. parts := strings.SplitN(extraHost, ":", 2)
  444. sboxOptions = append(sboxOptions, libnetwork.OptionExtraHost(parts[0], parts[1]))
  445. }
  446. refs := container.daemon.containerGraph().RefPaths(container.ID)
  447. for _, ref := range refs {
  448. if ref.ParentID == "0" {
  449. continue
  450. }
  451. c, err := container.daemon.Get(ctx, ref.ParentID)
  452. if err != nil {
  453. logrus.Error(err)
  454. }
  455. if c != nil && !container.daemon.configStore.DisableBridge && container.hostConfig.NetworkMode.IsPrivate() {
  456. logrus.Debugf("Update /etc/hosts of %s for alias %s with ip %s", c.ID, ref.Name, container.NetworkSettings.IPAddress)
  457. sboxOptions = append(sboxOptions, libnetwork.OptionParentUpdate(c.ID, ref.Name, container.NetworkSettings.IPAddress))
  458. if c.NetworkSettings.EndpointID != "" {
  459. parentEndpoints = append(parentEndpoints, c.NetworkSettings.EndpointID)
  460. }
  461. }
  462. }
  463. linkOptions := options.Generic{
  464. netlabel.GenericData: options.Generic{
  465. "ParentEndpoints": parentEndpoints,
  466. "ChildEndpoints": childEndpoints,
  467. },
  468. }
  469. sboxOptions = append(sboxOptions, libnetwork.OptionGeneric(linkOptions))
  470. return sboxOptions, nil
  471. }
  472. func (container *Container) buildPortMapInfo(ep libnetwork.Endpoint, networkSettings *network.Settings) (*network.Settings, error) {
  473. if ep == nil {
  474. return nil, derr.ErrorCodeEmptyEndpoint
  475. }
  476. if networkSettings == nil {
  477. return nil, derr.ErrorCodeEmptyNetwork
  478. }
  479. driverInfo, err := ep.DriverInfo()
  480. if err != nil {
  481. return nil, err
  482. }
  483. if driverInfo == nil {
  484. // It is not an error for epInfo to be nil
  485. return networkSettings, nil
  486. }
  487. if mac, ok := driverInfo[netlabel.MacAddress]; ok {
  488. networkSettings.MacAddress = mac.(net.HardwareAddr).String()
  489. }
  490. networkSettings.Ports = nat.PortMap{}
  491. if expData, ok := driverInfo[netlabel.ExposedPorts]; ok {
  492. if exposedPorts, ok := expData.([]types.TransportPort); ok {
  493. for _, tp := range exposedPorts {
  494. natPort, err := nat.NewPort(tp.Proto.String(), strconv.Itoa(int(tp.Port)))
  495. if err != nil {
  496. return nil, derr.ErrorCodeParsingPort.WithArgs(tp.Port, err)
  497. }
  498. networkSettings.Ports[natPort] = nil
  499. }
  500. }
  501. }
  502. mapData, ok := driverInfo[netlabel.PortMap]
  503. if !ok {
  504. return networkSettings, nil
  505. }
  506. if portMapping, ok := mapData.([]types.PortBinding); ok {
  507. for _, pp := range portMapping {
  508. natPort, err := nat.NewPort(pp.Proto.String(), strconv.Itoa(int(pp.Port)))
  509. if err != nil {
  510. return nil, err
  511. }
  512. natBndg := nat.PortBinding{HostIP: pp.HostIP.String(), HostPort: strconv.Itoa(int(pp.HostPort))}
  513. networkSettings.Ports[natPort] = append(networkSettings.Ports[natPort], natBndg)
  514. }
  515. }
  516. return networkSettings, nil
  517. }
  518. func (container *Container) buildEndpointInfo(ep libnetwork.Endpoint, networkSettings *network.Settings) (*network.Settings, error) {
  519. if ep == nil {
  520. return nil, derr.ErrorCodeEmptyEndpoint
  521. }
  522. if networkSettings == nil {
  523. return nil, derr.ErrorCodeEmptyNetwork
  524. }
  525. epInfo := ep.Info()
  526. if epInfo == nil {
  527. // It is not an error to get an empty endpoint info
  528. return networkSettings, nil
  529. }
  530. iface := epInfo.Iface()
  531. if iface == nil {
  532. return networkSettings, nil
  533. }
  534. ones, _ := iface.Address().Mask.Size()
  535. networkSettings.IPAddress = iface.Address().IP.String()
  536. networkSettings.IPPrefixLen = ones
  537. if iface.AddressIPv6().IP.To16() != nil {
  538. onesv6, _ := iface.AddressIPv6().Mask.Size()
  539. networkSettings.GlobalIPv6Address = iface.AddressIPv6().IP.String()
  540. networkSettings.GlobalIPv6PrefixLen = onesv6
  541. }
  542. return networkSettings, nil
  543. }
  544. func (container *Container) updateJoinInfo(ep libnetwork.Endpoint) error {
  545. epInfo := ep.Info()
  546. if epInfo == nil {
  547. // It is not an error to get an empty endpoint info
  548. return nil
  549. }
  550. container.NetworkSettings.Gateway = epInfo.Gateway().String()
  551. if epInfo.GatewayIPv6().To16() != nil {
  552. container.NetworkSettings.IPv6Gateway = epInfo.GatewayIPv6().String()
  553. }
  554. return nil
  555. }
  556. func (container *Container) updateEndpointNetworkSettings(n libnetwork.Network, ep libnetwork.Endpoint) error {
  557. networkSettings := &network.Settings{NetworkID: n.ID(), EndpointID: ep.ID()}
  558. networkSettings, err := container.buildPortMapInfo(ep, networkSettings)
  559. if err != nil {
  560. return err
  561. }
  562. networkSettings, err = container.buildEndpointInfo(ep, networkSettings)
  563. if err != nil {
  564. return err
  565. }
  566. if container.hostConfig.NetworkMode == runconfig.NetworkMode("bridge") {
  567. networkSettings.Bridge = container.daemon.configStore.Bridge.Iface
  568. }
  569. container.NetworkSettings = networkSettings
  570. return nil
  571. }
  572. func (container *Container) updateSandboxNetworkSettings(sb libnetwork.Sandbox) error {
  573. container.NetworkSettings.SandboxID = sb.ID()
  574. container.NetworkSettings.SandboxKey = sb.Key()
  575. return nil
  576. }
  577. // UpdateNetwork is used to update the container's network (e.g. when linked containers
  578. // get removed/unlinked).
  579. func (container *Container) updateNetwork(ctx context.Context) error {
  580. ctrl := container.daemon.netController
  581. sid := container.NetworkSettings.SandboxID
  582. sb, err := ctrl.SandboxByID(sid)
  583. if err != nil {
  584. return derr.ErrorCodeNoSandbox.WithArgs(sid, err)
  585. }
  586. options, err := container.buildSandboxOptions(ctx)
  587. if err != nil {
  588. return derr.ErrorCodeNetworkUpdate.WithArgs(err)
  589. }
  590. if err := sb.Refresh(options...); err != nil {
  591. return derr.ErrorCodeNetworkRefresh.WithArgs(sid, err)
  592. }
  593. return nil
  594. }
  595. func (container *Container) buildCreateEndpointOptions() ([]libnetwork.EndpointOption, error) {
  596. var (
  597. portSpecs = make(nat.PortSet)
  598. bindings = make(nat.PortMap)
  599. pbList []types.PortBinding
  600. exposeList []types.TransportPort
  601. createOptions []libnetwork.EndpointOption
  602. )
  603. if container.Config.ExposedPorts != nil {
  604. portSpecs = container.Config.ExposedPorts
  605. }
  606. if container.hostConfig.PortBindings != nil {
  607. for p, b := range container.hostConfig.PortBindings {
  608. bindings[p] = []nat.PortBinding{}
  609. for _, bb := range b {
  610. bindings[p] = append(bindings[p], nat.PortBinding{
  611. HostIP: bb.HostIP,
  612. HostPort: bb.HostPort,
  613. })
  614. }
  615. }
  616. }
  617. ports := make([]nat.Port, len(portSpecs))
  618. var i int
  619. for p := range portSpecs {
  620. ports[i] = p
  621. i++
  622. }
  623. nat.SortPortMap(ports, bindings)
  624. for _, port := range ports {
  625. expose := types.TransportPort{}
  626. expose.Proto = types.ParseProtocol(port.Proto())
  627. expose.Port = uint16(port.Int())
  628. exposeList = append(exposeList, expose)
  629. pb := types.PortBinding{Port: expose.Port, Proto: expose.Proto}
  630. binding := bindings[port]
  631. for i := 0; i < len(binding); i++ {
  632. pbCopy := pb.GetCopy()
  633. newP, err := nat.NewPort(nat.SplitProtoPort(binding[i].HostPort))
  634. var portStart, portEnd int
  635. if err == nil {
  636. portStart, portEnd, err = newP.Range()
  637. }
  638. if err != nil {
  639. return nil, derr.ErrorCodeHostPort.WithArgs(binding[i].HostPort, err)
  640. }
  641. pbCopy.HostPort = uint16(portStart)
  642. pbCopy.HostPortEnd = uint16(portEnd)
  643. pbCopy.HostIP = net.ParseIP(binding[i].HostIP)
  644. pbList = append(pbList, pbCopy)
  645. }
  646. if container.hostConfig.PublishAllPorts && len(binding) == 0 {
  647. pbList = append(pbList, pb)
  648. }
  649. }
  650. createOptions = append(createOptions,
  651. libnetwork.CreateOptionPortMapping(pbList),
  652. libnetwork.CreateOptionExposedPorts(exposeList))
  653. if container.Config.MacAddress != "" {
  654. mac, err := net.ParseMAC(container.Config.MacAddress)
  655. if err != nil {
  656. return nil, err
  657. }
  658. genericOption := options.Generic{
  659. netlabel.MacAddress: mac,
  660. }
  661. createOptions = append(createOptions, libnetwork.EndpointOptionGeneric(genericOption))
  662. }
  663. return createOptions, nil
  664. }
  665. func parseService(controller libnetwork.NetworkController, service string) (string, string, string) {
  666. dn := controller.Config().Daemon.DefaultNetwork
  667. dd := controller.Config().Daemon.DefaultDriver
  668. snd := strings.Split(service, ".")
  669. if len(snd) > 2 {
  670. return strings.Join(snd[:len(snd)-2], "."), snd[len(snd)-2], snd[len(snd)-1]
  671. }
  672. if len(snd) > 1 {
  673. return snd[0], snd[1], dd
  674. }
  675. return snd[0], dn, dd
  676. }
  677. func createNetwork(controller libnetwork.NetworkController, dnet string, driver string) (libnetwork.Network, error) {
  678. createOptions := []libnetwork.NetworkOption{}
  679. genericOption := options.Generic{}
  680. // Bridge driver is special due to legacy reasons
  681. if runconfig.NetworkMode(driver).IsBridge() {
  682. genericOption[netlabel.GenericData] = map[string]interface{}{
  683. "BridgeName": dnet,
  684. "AllowNonDefaultBridge": "true",
  685. }
  686. networkOption := libnetwork.NetworkOptionGeneric(genericOption)
  687. createOptions = append(createOptions, networkOption)
  688. }
  689. return controller.NewNetwork(driver, dnet, createOptions...)
  690. }
  691. func (container *Container) allocateNetwork(ctx context.Context) error {
  692. mode := container.hostConfig.NetworkMode
  693. controller := container.daemon.netController
  694. if container.Config.NetworkDisabled || mode.IsContainer() {
  695. return nil
  696. }
  697. networkDriver := string(mode)
  698. service := container.Config.PublishService
  699. networkName := mode.NetworkName()
  700. if mode.IsDefault() {
  701. if service != "" {
  702. service, networkName, networkDriver = parseService(controller, service)
  703. } else {
  704. networkName = controller.Config().Daemon.DefaultNetwork
  705. networkDriver = controller.Config().Daemon.DefaultDriver
  706. }
  707. } else if service != "" {
  708. return derr.ErrorCodeNetworkConflict
  709. }
  710. if runconfig.NetworkMode(networkDriver).IsBridge() && container.daemon.configStore.DisableBridge {
  711. container.Config.NetworkDisabled = true
  712. return nil
  713. }
  714. if service == "" {
  715. // dot character "." has a special meaning to support SERVICE[.NETWORK] format.
  716. // For backward compatibility, replacing "." with "-", instead of failing
  717. service = strings.Replace(container.Name, ".", "-", -1)
  718. // Service names dont like "/" in them. removing it instead of failing for backward compatibility
  719. service = strings.Replace(service, "/", "", -1)
  720. }
  721. if err := container.configureNetwork(ctx, networkName, service, networkDriver, mode.IsDefault()); err != nil {
  722. return err
  723. }
  724. return container.writeHostConfig()
  725. }
  726. func (container *Container) configureNetwork(ctx context.Context, networkName, service, networkDriver string, canCreateNetwork bool) error {
  727. controller := container.daemon.netController
  728. n, err := controller.NetworkByName(networkName)
  729. if err != nil {
  730. if _, ok := err.(libnetwork.ErrNoSuchNetwork); !ok || !canCreateNetwork {
  731. return err
  732. }
  733. if n, err = createNetwork(controller, networkName, networkDriver); err != nil {
  734. return err
  735. }
  736. }
  737. ep, err := n.EndpointByName(service)
  738. if err != nil {
  739. if _, ok := err.(libnetwork.ErrNoSuchEndpoint); !ok {
  740. return err
  741. }
  742. createOptions, err := container.buildCreateEndpointOptions()
  743. if err != nil {
  744. return err
  745. }
  746. ep, err = n.CreateEndpoint(service, createOptions...)
  747. if err != nil {
  748. return err
  749. }
  750. }
  751. if err := container.updateEndpointNetworkSettings(n, ep); err != nil {
  752. return err
  753. }
  754. var sb libnetwork.Sandbox
  755. controller.WalkSandboxes(func(s libnetwork.Sandbox) bool {
  756. if s.ContainerID() == container.ID {
  757. sb = s
  758. return true
  759. }
  760. return false
  761. })
  762. if sb == nil {
  763. options, err := container.buildSandboxOptions(ctx)
  764. if err != nil {
  765. return err
  766. }
  767. sb, err = controller.NewSandbox(container.ID, options...)
  768. if err != nil {
  769. return err
  770. }
  771. }
  772. container.updateSandboxNetworkSettings(sb)
  773. if err := ep.Join(sb); err != nil {
  774. return err
  775. }
  776. if err := container.updateJoinInfo(ep); err != nil {
  777. return derr.ErrorCodeJoinInfo.WithArgs(err)
  778. }
  779. return nil
  780. }
  781. func (container *Container) initializeNetworking(ctx context.Context) error {
  782. var err error
  783. if container.hostConfig.NetworkMode.IsContainer() {
  784. // we need to get the hosts files from the container to join
  785. nc, err := container.getNetworkedContainer(ctx)
  786. if err != nil {
  787. return err
  788. }
  789. container.HostnamePath = nc.HostnamePath
  790. container.HostsPath = nc.HostsPath
  791. container.ResolvConfPath = nc.ResolvConfPath
  792. container.Config.Hostname = nc.Config.Hostname
  793. container.Config.Domainname = nc.Config.Domainname
  794. return nil
  795. }
  796. if container.hostConfig.NetworkMode.IsHost() {
  797. container.Config.Hostname, err = os.Hostname()
  798. if err != nil {
  799. return err
  800. }
  801. parts := strings.SplitN(container.Config.Hostname, ".", 2)
  802. if len(parts) > 1 {
  803. container.Config.Hostname = parts[0]
  804. container.Config.Domainname = parts[1]
  805. }
  806. }
  807. if err := container.allocateNetwork(ctx); err != nil {
  808. return err
  809. }
  810. return container.buildHostnameFile()
  811. }
  812. // called from the libcontainer pre-start hook to set the network
  813. // namespace configuration linkage to the libnetwork "sandbox" entity
  814. func (container *Container) setNetworkNamespaceKey(pid int) error {
  815. path := fmt.Sprintf("/proc/%d/ns/net", pid)
  816. var sandbox libnetwork.Sandbox
  817. search := libnetwork.SandboxContainerWalker(&sandbox, container.ID)
  818. container.daemon.netController.WalkSandboxes(search)
  819. if sandbox == nil {
  820. return derr.ErrorCodeNoSandbox.WithArgs(container.ID)
  821. }
  822. return sandbox.SetKey(path)
  823. }
  824. func (container *Container) getIpcContainer(ctx context.Context) (*Container, error) {
  825. containerID := container.hostConfig.IpcMode.Container()
  826. c, err := container.daemon.Get(ctx, containerID)
  827. if err != nil {
  828. return nil, err
  829. }
  830. if !c.IsRunning() {
  831. return nil, derr.ErrorCodeIPCRunning
  832. }
  833. return c, nil
  834. }
  835. func (container *Container) setupWorkingDirectory() error {
  836. if container.Config.WorkingDir != "" {
  837. container.Config.WorkingDir = filepath.Clean(container.Config.WorkingDir)
  838. pth, err := container.GetResourcePath(container.Config.WorkingDir)
  839. if err != nil {
  840. return err
  841. }
  842. pthInfo, err := os.Stat(pth)
  843. if err != nil {
  844. if !os.IsNotExist(err) {
  845. return err
  846. }
  847. if err := system.MkdirAll(pth, 0755); err != nil {
  848. return err
  849. }
  850. }
  851. if pthInfo != nil && !pthInfo.IsDir() {
  852. return derr.ErrorCodeNotADir.WithArgs(container.Config.WorkingDir)
  853. }
  854. }
  855. return nil
  856. }
  857. func (container *Container) getNetworkedContainer(ctx context.Context) (*Container, error) {
  858. parts := strings.SplitN(string(container.hostConfig.NetworkMode), ":", 2)
  859. switch parts[0] {
  860. case "container":
  861. if len(parts) != 2 {
  862. return nil, derr.ErrorCodeParseContainer
  863. }
  864. nc, err := container.daemon.Get(ctx, parts[1])
  865. if err != nil {
  866. return nil, err
  867. }
  868. if container == nc {
  869. return nil, derr.ErrorCodeJoinSelf
  870. }
  871. if !nc.IsRunning() {
  872. return nil, derr.ErrorCodeJoinRunning.WithArgs(parts[1])
  873. }
  874. return nc, nil
  875. default:
  876. return nil, derr.ErrorCodeModeNotContainer
  877. }
  878. }
  879. func (container *Container) releaseNetwork() {
  880. if container.hostConfig.NetworkMode.IsContainer() || container.Config.NetworkDisabled {
  881. return
  882. }
  883. sid := container.NetworkSettings.SandboxID
  884. eid := container.NetworkSettings.EndpointID
  885. nid := container.NetworkSettings.NetworkID
  886. container.NetworkSettings = &network.Settings{}
  887. if sid == "" || nid == "" || eid == "" {
  888. return
  889. }
  890. sb, err := container.daemon.netController.SandboxByID(sid)
  891. if err != nil {
  892. logrus.Errorf("error locating sandbox id %s: %v", sid, err)
  893. return
  894. }
  895. n, err := container.daemon.netController.NetworkByID(nid)
  896. if err != nil {
  897. logrus.Errorf("error locating network id %s: %v", nid, err)
  898. return
  899. }
  900. ep, err := n.EndpointByID(eid)
  901. if err != nil {
  902. logrus.Errorf("error locating endpoint id %s: %v", eid, err)
  903. return
  904. }
  905. if err := sb.Delete(); err != nil {
  906. logrus.Errorf("Error deleting sandbox id %s for container %s: %v", sid, container.ID, err)
  907. return
  908. }
  909. // In addition to leaving all endpoints, delete implicitly created endpoint
  910. if container.Config.PublishService == "" {
  911. if err := ep.Delete(); err != nil {
  912. logrus.Errorf("deleting endpoint failed: %v", err)
  913. }
  914. }
  915. }
  916. func (container *Container) unmountVolumes(forceSyscall bool) error {
  917. var volumeMounts []mountPoint
  918. for _, mntPoint := range container.MountPoints {
  919. dest, err := container.GetResourcePath(mntPoint.Destination)
  920. if err != nil {
  921. return err
  922. }
  923. volumeMounts = append(volumeMounts, mountPoint{Destination: dest, Volume: mntPoint.Volume})
  924. }
  925. for _, mnt := range container.networkMounts() {
  926. dest, err := container.GetResourcePath(mnt.Destination)
  927. if err != nil {
  928. return err
  929. }
  930. volumeMounts = append(volumeMounts, mountPoint{Destination: dest})
  931. }
  932. for _, volumeMount := range volumeMounts {
  933. if forceSyscall {
  934. syscall.Unmount(volumeMount.Destination, 0)
  935. }
  936. if volumeMount.Volume != nil {
  937. if err := volumeMount.Volume.Unmount(); err != nil {
  938. return err
  939. }
  940. }
  941. }
  942. return nil
  943. }
  944. func (container *Container) networkMounts() []execdriver.Mount {
  945. var mounts []execdriver.Mount
  946. shared := container.hostConfig.NetworkMode.IsContainer()
  947. if container.ResolvConfPath != "" {
  948. label.Relabel(container.ResolvConfPath, container.MountLabel, shared)
  949. writable := !container.hostConfig.ReadonlyRootfs
  950. if m, exists := container.MountPoints["/etc/resolv.conf"]; exists {
  951. writable = m.RW
  952. }
  953. mounts = append(mounts, execdriver.Mount{
  954. Source: container.ResolvConfPath,
  955. Destination: "/etc/resolv.conf",
  956. Writable: writable,
  957. Private: true,
  958. })
  959. }
  960. if container.HostnamePath != "" {
  961. label.Relabel(container.HostnamePath, container.MountLabel, shared)
  962. writable := !container.hostConfig.ReadonlyRootfs
  963. if m, exists := container.MountPoints["/etc/hostname"]; exists {
  964. writable = m.RW
  965. }
  966. mounts = append(mounts, execdriver.Mount{
  967. Source: container.HostnamePath,
  968. Destination: "/etc/hostname",
  969. Writable: writable,
  970. Private: true,
  971. })
  972. }
  973. if container.HostsPath != "" {
  974. label.Relabel(container.HostsPath, container.MountLabel, shared)
  975. writable := !container.hostConfig.ReadonlyRootfs
  976. if m, exists := container.MountPoints["/etc/hosts"]; exists {
  977. writable = m.RW
  978. }
  979. mounts = append(mounts, execdriver.Mount{
  980. Source: container.HostsPath,
  981. Destination: "/etc/hosts",
  982. Writable: writable,
  983. Private: true,
  984. })
  985. }
  986. return mounts
  987. }
  988. func (container *Container) addBindMountPoint(name, source, destination string, rw bool) {
  989. container.MountPoints[destination] = &mountPoint{
  990. Name: name,
  991. Source: source,
  992. Destination: destination,
  993. RW: rw,
  994. }
  995. }
  996. func (container *Container) addLocalMountPoint(name, destination string, rw bool) {
  997. container.MountPoints[destination] = &mountPoint{
  998. Name: name,
  999. Driver: volume.DefaultDriverName,
  1000. Destination: destination,
  1001. RW: rw,
  1002. }
  1003. }
  1004. func (container *Container) addMountPointWithVolume(destination string, vol volume.Volume, rw bool) {
  1005. container.MountPoints[destination] = &mountPoint{
  1006. Name: vol.Name(),
  1007. Driver: vol.DriverName(),
  1008. Destination: destination,
  1009. RW: rw,
  1010. Volume: vol,
  1011. }
  1012. }
  1013. func (container *Container) isDestinationMounted(destination string) bool {
  1014. return container.MountPoints[destination] != nil
  1015. }
  1016. func (container *Container) prepareMountPoints() error {
  1017. for _, config := range container.MountPoints {
  1018. if len(config.Driver) > 0 {
  1019. v, err := container.daemon.createVolume(config.Name, config.Driver, nil)
  1020. if err != nil {
  1021. return err
  1022. }
  1023. config.Volume = v
  1024. }
  1025. }
  1026. return nil
  1027. }
  1028. func (container *Container) removeMountPoints(rm bool) error {
  1029. var rmErrors []string
  1030. for _, m := range container.MountPoints {
  1031. if m.Volume == nil {
  1032. continue
  1033. }
  1034. container.daemon.volumes.Decrement(m.Volume)
  1035. if rm {
  1036. err := container.daemon.volumes.Remove(m.Volume)
  1037. // ErrVolumeInUse is ignored because having this
  1038. // volume being referenced by othe container is
  1039. // not an error, but an implementation detail.
  1040. // This prevents docker from logging "ERROR: Volume in use"
  1041. // where there is another container using the volume.
  1042. if err != nil && err != store.ErrVolumeInUse {
  1043. rmErrors = append(rmErrors, err.Error())
  1044. }
  1045. }
  1046. }
  1047. if len(rmErrors) > 0 {
  1048. return derr.ErrorCodeRemovingVolume.WithArgs(strings.Join(rmErrors, "\n"))
  1049. }
  1050. return nil
  1051. }
  1052. func (container *Container) shmPath() (string, error) {
  1053. return container.getRootResourcePath("shm")
  1054. }
  1055. func (container *Container) mqueuePath() (string, error) {
  1056. return container.getRootResourcePath("mqueue")
  1057. }
  1058. func (container *Container) setupIpcDirs() error {
  1059. shmPath, err := container.shmPath()
  1060. if err != nil {
  1061. return err
  1062. }
  1063. if err := os.MkdirAll(shmPath, 0700); err != nil {
  1064. return err
  1065. }
  1066. 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 {
  1067. return fmt.Errorf("mounting shm tmpfs: %s", err)
  1068. }
  1069. mqueuePath, err := container.mqueuePath()
  1070. if err != nil {
  1071. return err
  1072. }
  1073. if err := os.MkdirAll(mqueuePath, 0700); err != nil {
  1074. return err
  1075. }
  1076. if err := syscall.Mount("mqueue", mqueuePath, "mqueue", uintptr(syscall.MS_NOEXEC|syscall.MS_NOSUID|syscall.MS_NODEV), ""); err != nil {
  1077. return fmt.Errorf("mounting mqueue mqueue : %s", err)
  1078. }
  1079. return nil
  1080. }
  1081. func (container *Container) unmountIpcMounts() error {
  1082. if container.hostConfig.IpcMode.IsContainer() || container.hostConfig.IpcMode.IsHost() {
  1083. return nil
  1084. }
  1085. var errors []string
  1086. shmPath, err := container.shmPath()
  1087. if err != nil {
  1088. logrus.Error(err)
  1089. errors = append(errors, err.Error())
  1090. } else {
  1091. if err := detachMounted(shmPath); err != nil {
  1092. logrus.Errorf("failed to umount %s: %v", shmPath, err)
  1093. errors = append(errors, err.Error())
  1094. }
  1095. }
  1096. mqueuePath, err := container.mqueuePath()
  1097. if err != nil {
  1098. logrus.Error(err)
  1099. errors = append(errors, err.Error())
  1100. } else {
  1101. if err := detachMounted(mqueuePath); err != nil {
  1102. logrus.Errorf("failed to umount %s: %v", mqueuePath, err)
  1103. errors = append(errors, err.Error())
  1104. }
  1105. }
  1106. if len(errors) > 0 {
  1107. return fmt.Errorf("failed to cleanup ipc mounts:\n%v", strings.Join(errors, "\n"))
  1108. }
  1109. return nil
  1110. }
  1111. func (container *Container) ipcMounts() []execdriver.Mount {
  1112. var mounts []execdriver.Mount
  1113. label.SetFileLabel(container.ShmPath, container.MountLabel)
  1114. mounts = append(mounts, execdriver.Mount{
  1115. Source: container.ShmPath,
  1116. Destination: "/dev/shm",
  1117. Writable: true,
  1118. Private: true,
  1119. })
  1120. label.SetFileLabel(container.MqueuePath, container.MountLabel)
  1121. mounts = append(mounts, execdriver.Mount{
  1122. Source: container.MqueuePath,
  1123. Destination: "/dev/mqueue",
  1124. Writable: true,
  1125. Private: true,
  1126. })
  1127. return mounts
  1128. }
  1129. func detachMounted(path string) error {
  1130. return syscall.Unmount(path, syscall.MNT_DETACH)
  1131. }