container_unix.go 37 KB

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