container_unix.go 37 KB

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