container_unix.go 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353
  1. // +build linux freebsd
  2. package daemon
  3. import (
  4. "fmt"
  5. "io/ioutil"
  6. "net"
  7. "os"
  8. "path"
  9. "path/filepath"
  10. "strconv"
  11. "strings"
  12. "syscall"
  13. "time"
  14. "github.com/Sirupsen/logrus"
  15. "github.com/docker/docker/context"
  16. "github.com/docker/docker/daemon/execdriver"
  17. "github.com/docker/docker/daemon/links"
  18. "github.com/docker/docker/daemon/network"
  19. derr "github.com/docker/docker/errors"
  20. "github.com/docker/docker/pkg/directory"
  21. "github.com/docker/docker/pkg/nat"
  22. "github.com/docker/docker/pkg/stringid"
  23. "github.com/docker/docker/pkg/system"
  24. "github.com/docker/docker/pkg/ulimit"
  25. "github.com/docker/docker/runconfig"
  26. "github.com/docker/docker/utils"
  27. "github.com/docker/docker/volume"
  28. "github.com/docker/docker/volume/store"
  29. "github.com/docker/libnetwork"
  30. "github.com/docker/libnetwork/netlabel"
  31. "github.com/docker/libnetwork/options"
  32. "github.com/docker/libnetwork/types"
  33. "github.com/opencontainers/runc/libcontainer/configs"
  34. "github.com/opencontainers/runc/libcontainer/devices"
  35. "github.com/opencontainers/runc/libcontainer/label"
  36. )
  37. // DefaultPathEnv is unix style list of directories to search for
  38. // executables. Each directory is separated from the next by a colon
  39. // ':' character .
  40. const DefaultPathEnv = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
  41. // Container holds the fields specific to unixen implementations. See
  42. // CommonContainer for standard fields common to all containers.
  43. type Container struct {
  44. CommonContainer
  45. // Fields below here are platform specific.
  46. activeLinks map[string]*links.Link
  47. AppArmorProfile string
  48. HostnamePath string
  49. HostsPath string
  50. ShmPath string
  51. MqueuePath string
  52. MountPoints map[string]*mountPoint
  53. ResolvConfPath string
  54. Volumes map[string]string // Deprecated since 1.7, kept for backwards compatibility
  55. VolumesRW map[string]bool // Deprecated since 1.7, kept for backwards compatibility
  56. }
  57. func killProcessDirectly(container *Container) error {
  58. if _, err := container.WaitStop(10 * time.Second); err != nil {
  59. // Ensure that we don't kill ourselves
  60. if pid := container.getPID(); pid != 0 {
  61. logrus.Infof("Container %s failed to exit within 10 seconds of kill - trying direct SIGKILL", stringid.TruncateID(container.ID))
  62. if err := syscall.Kill(pid, 9); err != nil {
  63. if err != syscall.ESRCH {
  64. return err
  65. }
  66. logrus.Debugf("Cannot kill process (pid=%d) with signal 9: no such process.", pid)
  67. }
  68. }
  69. }
  70. return nil
  71. }
  72. func (container *Container) setupLinkedContainers(ctx context.Context) ([]string, error) {
  73. var (
  74. env []string
  75. daemon = container.daemon
  76. )
  77. children, err := daemon.children(ctx, container.Name)
  78. if err != nil {
  79. return nil, err
  80. }
  81. if len(children) > 0 {
  82. for linkAlias, child := range children {
  83. if !child.IsRunning() {
  84. return nil, derr.ErrorCodeLinkNotRunning.WithArgs(child.Name, linkAlias)
  85. }
  86. link := links.NewLink(
  87. container.NetworkSettings.IPAddress,
  88. child.NetworkSettings.IPAddress,
  89. linkAlias,
  90. child.Config.Env,
  91. child.Config.ExposedPorts,
  92. )
  93. for _, envVar := range link.ToEnv() {
  94. env = append(env, envVar)
  95. }
  96. }
  97. }
  98. return env, nil
  99. }
  100. func (container *Container) createDaemonEnvironment(linkedEnv []string) []string {
  101. // if a domain name was specified, append it to the hostname (see #7851)
  102. fullHostname := container.Config.Hostname
  103. if container.Config.Domainname != "" {
  104. fullHostname = fmt.Sprintf("%s.%s", fullHostname, container.Config.Domainname)
  105. }
  106. // Setup environment
  107. env := []string{
  108. "PATH=" + DefaultPathEnv,
  109. "HOSTNAME=" + fullHostname,
  110. // Note: we don't set HOME here because it'll get autoset intelligently
  111. // based on the value of USER inside dockerinit, but only if it isn't
  112. // set already (ie, that can be overridden by setting HOME via -e or ENV
  113. // in a Dockerfile).
  114. }
  115. if container.Config.Tty {
  116. env = append(env, "TERM=xterm")
  117. }
  118. env = append(env, linkedEnv...)
  119. // because the env on the container can override certain default values
  120. // we need to replace the 'env' keys where they match and append anything
  121. // else.
  122. env = utils.ReplaceOrAppendEnvValues(env, container.Config.Env)
  123. return env
  124. }
  125. func getDevicesFromPath(deviceMapping runconfig.DeviceMapping) (devs []*configs.Device, err error) {
  126. device, err := devices.DeviceFromPath(deviceMapping.PathOnHost, deviceMapping.CgroupPermissions)
  127. // if there was no error, return the device
  128. if err == nil {
  129. device.Path = deviceMapping.PathInContainer
  130. return append(devs, device), nil
  131. }
  132. // if the device is not a device node
  133. // try to see if it's a directory holding many devices
  134. if err == devices.ErrNotADevice {
  135. // check if it is a directory
  136. if src, e := os.Stat(deviceMapping.PathOnHost); e == nil && src.IsDir() {
  137. // mount the internal devices recursively
  138. filepath.Walk(deviceMapping.PathOnHost, func(dpath string, f os.FileInfo, e error) error {
  139. childDevice, e := devices.DeviceFromPath(dpath, deviceMapping.CgroupPermissions)
  140. if e != nil {
  141. // ignore the device
  142. return nil
  143. }
  144. // add the device to userSpecified devices
  145. childDevice.Path = strings.Replace(dpath, deviceMapping.PathOnHost, deviceMapping.PathInContainer, 1)
  146. devs = append(devs, childDevice)
  147. return nil
  148. })
  149. }
  150. }
  151. if len(devs) > 0 {
  152. return devs, nil
  153. }
  154. return devs, derr.ErrorCodeDeviceInfo.WithArgs(deviceMapping.PathOnHost, err)
  155. }
  156. func populateCommand(ctx context.Context, c *Container, env []string) error {
  157. var en *execdriver.Network
  158. if !c.Config.NetworkDisabled {
  159. en = &execdriver.Network{}
  160. if !c.daemon.execDriver.SupportsHooks() || c.hostConfig.NetworkMode.IsHost() {
  161. en.NamespacePath = c.NetworkSettings.SandboxKey
  162. }
  163. parts := strings.SplitN(string(c.hostConfig.NetworkMode), ":", 2)
  164. if parts[0] == "container" {
  165. nc, err := c.getNetworkedContainer(ctx)
  166. if err != nil {
  167. return err
  168. }
  169. en.ContainerID = nc.ID
  170. }
  171. }
  172. ipc := &execdriver.Ipc{}
  173. var err error
  174. c.ShmPath, err = c.shmPath()
  175. if err != nil {
  176. return err
  177. }
  178. c.MqueuePath, err = c.mqueuePath()
  179. if err != nil {
  180. return err
  181. }
  182. if c.hostConfig.IpcMode.IsContainer() {
  183. ic, err := c.getIpcContainer(ctx)
  184. if err != nil {
  185. return err
  186. }
  187. ipc.ContainerID = ic.ID
  188. c.ShmPath = ic.ShmPath
  189. c.MqueuePath = ic.MqueuePath
  190. } else {
  191. ipc.HostIpc = c.hostConfig.IpcMode.IsHost()
  192. if ipc.HostIpc {
  193. c.ShmPath = "/dev/shm"
  194. c.MqueuePath = "/dev/mqueue"
  195. }
  196. }
  197. pid := &execdriver.Pid{}
  198. pid.HostPid = c.hostConfig.PidMode.IsHost()
  199. uts := &execdriver.UTS{
  200. HostUTS: c.hostConfig.UTSMode.IsHost(),
  201. }
  202. // Build lists of devices allowed and created within the container.
  203. var userSpecifiedDevices []*configs.Device
  204. for _, deviceMapping := range c.hostConfig.Devices {
  205. devs, err := getDevicesFromPath(deviceMapping)
  206. if err != nil {
  207. return err
  208. }
  209. userSpecifiedDevices = append(userSpecifiedDevices, devs...)
  210. }
  211. allowedDevices := mergeDevices(configs.DefaultAllowedDevices, userSpecifiedDevices)
  212. autoCreatedDevices := mergeDevices(configs.DefaultAutoCreatedDevices, userSpecifiedDevices)
  213. // TODO: this can be removed after lxc-conf is fully deprecated
  214. lxcConfig, err := mergeLxcConfIntoOptions(c.hostConfig)
  215. if err != nil {
  216. return err
  217. }
  218. var rlimits []*ulimit.Rlimit
  219. ulimits := c.hostConfig.Ulimits
  220. // Merge ulimits with daemon defaults
  221. ulIdx := make(map[string]*ulimit.Ulimit)
  222. for _, ul := range ulimits {
  223. ulIdx[ul.Name] = ul
  224. }
  225. for name, ul := range c.daemon.configStore.Ulimits {
  226. if _, exists := ulIdx[name]; !exists {
  227. ulimits = append(ulimits, ul)
  228. }
  229. }
  230. for _, limit := range ulimits {
  231. rl, err := limit.GetRlimit()
  232. if err != nil {
  233. return err
  234. }
  235. rlimits = append(rlimits, rl)
  236. }
  237. resources := &execdriver.Resources{
  238. Memory: c.hostConfig.Memory,
  239. MemorySwap: c.hostConfig.MemorySwap,
  240. 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(ctx context.Context) (int64, int64) {
  306. var (
  307. sizeRw, sizeRootfs int64
  308. err error
  309. driver = container.daemon.driver
  310. )
  311. if err := container.Mount(ctx); 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(ctx)
  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(ctx context.Context) ([]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(ctx, 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(ctx, 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(ctx context.Context) 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(ctx)
  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) secondaryNetworkRequired(ctx context.Context, primaryNetworkType string) bool {
  691. switch primaryNetworkType {
  692. case "bridge", "none", "host", "container":
  693. return false
  694. }
  695. if container.daemon.configStore.DisableBridge {
  696. return false
  697. }
  698. if container.Config.ExposedPorts != nil && len(container.Config.ExposedPorts) > 0 {
  699. return true
  700. }
  701. if container.hostConfig.PortBindings != nil && len(container.hostConfig.PortBindings) > 0 {
  702. return true
  703. }
  704. return false
  705. }
  706. func (container *Container) allocateNetwork(ctx context.Context) error {
  707. mode := container.hostConfig.NetworkMode
  708. controller := container.daemon.netController
  709. if container.Config.NetworkDisabled || mode.IsContainer() {
  710. return nil
  711. }
  712. networkDriver := string(mode)
  713. service := container.Config.PublishService
  714. networkName := mode.NetworkName()
  715. if mode.IsDefault() {
  716. if service != "" {
  717. service, networkName, networkDriver = parseService(controller, service)
  718. } else {
  719. networkName = controller.Config().Daemon.DefaultNetwork
  720. networkDriver = controller.Config().Daemon.DefaultDriver
  721. }
  722. } else if service != "" {
  723. return derr.ErrorCodeNetworkConflict
  724. }
  725. if runconfig.NetworkMode(networkDriver).IsBridge() && container.daemon.configStore.DisableBridge {
  726. container.Config.NetworkDisabled = true
  727. return nil
  728. }
  729. if service == "" {
  730. // dot character "." has a special meaning to support SERVICE[.NETWORK] format.
  731. // For backward compatibility, replacing "." with "-", instead of failing
  732. service = strings.Replace(container.Name, ".", "-", -1)
  733. // Service names dont like "/" in them. removing it instead of failing for backward compatibility
  734. service = strings.Replace(service, "/", "", -1)
  735. }
  736. if container.secondaryNetworkRequired(ctx, networkDriver) {
  737. // Configure Bridge as secondary network for port binding purposes
  738. if err := container.configureNetwork(ctx, "bridge", service, "bridge", false); err != nil {
  739. return err
  740. }
  741. }
  742. if err := container.configureNetwork(ctx, networkName, service, networkDriver, mode.IsDefault()); err != nil {
  743. return err
  744. }
  745. return container.writeHostConfig()
  746. }
  747. func (container *Container) configureNetwork(ctx context.Context, networkName, service, networkDriver string, canCreateNetwork bool) error {
  748. controller := container.daemon.netController
  749. n, err := controller.NetworkByName(networkName)
  750. if err != nil {
  751. if _, ok := err.(libnetwork.ErrNoSuchNetwork); !ok || !canCreateNetwork {
  752. return err
  753. }
  754. if n, err = createNetwork(controller, networkName, networkDriver); err != nil {
  755. return err
  756. }
  757. }
  758. ep, err := n.EndpointByName(service)
  759. if err != nil {
  760. if _, ok := err.(libnetwork.ErrNoSuchEndpoint); !ok {
  761. return err
  762. }
  763. createOptions, err := container.buildCreateEndpointOptions()
  764. if err != nil {
  765. return err
  766. }
  767. ep, err = n.CreateEndpoint(service, createOptions...)
  768. if err != nil {
  769. return err
  770. }
  771. }
  772. if err := container.updateEndpointNetworkSettings(n, ep); err != nil {
  773. return err
  774. }
  775. var sb libnetwork.Sandbox
  776. controller.WalkSandboxes(func(s libnetwork.Sandbox) bool {
  777. if s.ContainerID() == container.ID {
  778. sb = s
  779. return true
  780. }
  781. return false
  782. })
  783. if sb == nil {
  784. options, err := container.buildSandboxOptions(ctx)
  785. if err != nil {
  786. return err
  787. }
  788. sb, err = controller.NewSandbox(container.ID, options...)
  789. if err != nil {
  790. return err
  791. }
  792. }
  793. container.updateSandboxNetworkSettings(sb)
  794. if err := ep.Join(sb); err != nil {
  795. return err
  796. }
  797. if err := container.updateJoinInfo(ep); err != nil {
  798. return derr.ErrorCodeJoinInfo.WithArgs(err)
  799. }
  800. return nil
  801. }
  802. func (container *Container) initializeNetworking(ctx context.Context) error {
  803. var err error
  804. if container.hostConfig.NetworkMode.IsContainer() {
  805. // we need to get the hosts files from the container to join
  806. nc, err := container.getNetworkedContainer(ctx)
  807. if err != nil {
  808. return err
  809. }
  810. container.HostnamePath = nc.HostnamePath
  811. container.HostsPath = nc.HostsPath
  812. container.ResolvConfPath = nc.ResolvConfPath
  813. container.Config.Hostname = nc.Config.Hostname
  814. container.Config.Domainname = nc.Config.Domainname
  815. return nil
  816. }
  817. if container.hostConfig.NetworkMode.IsHost() {
  818. container.Config.Hostname, err = os.Hostname()
  819. if err != nil {
  820. return err
  821. }
  822. parts := strings.SplitN(container.Config.Hostname, ".", 2)
  823. if len(parts) > 1 {
  824. container.Config.Hostname = parts[0]
  825. container.Config.Domainname = parts[1]
  826. }
  827. }
  828. if err := container.allocateNetwork(ctx); err != nil {
  829. return err
  830. }
  831. return container.buildHostnameFile()
  832. }
  833. // called from the libcontainer pre-start hook to set the network
  834. // namespace configuration linkage to the libnetwork "sandbox" entity
  835. func (container *Container) setNetworkNamespaceKey(pid int) error {
  836. path := fmt.Sprintf("/proc/%d/ns/net", pid)
  837. var sandbox libnetwork.Sandbox
  838. search := libnetwork.SandboxContainerWalker(&sandbox, container.ID)
  839. container.daemon.netController.WalkSandboxes(search)
  840. if sandbox == nil {
  841. return derr.ErrorCodeNoSandbox.WithArgs(container.ID)
  842. }
  843. return sandbox.SetKey(path)
  844. }
  845. func (container *Container) getIpcContainer(ctx context.Context) (*Container, error) {
  846. containerID := container.hostConfig.IpcMode.Container()
  847. c, err := container.daemon.Get(ctx, containerID)
  848. if err != nil {
  849. return nil, err
  850. }
  851. if !c.IsRunning() {
  852. return nil, derr.ErrorCodeIPCRunning
  853. }
  854. return c, nil
  855. }
  856. func (container *Container) setupWorkingDirectory() error {
  857. if container.Config.WorkingDir != "" {
  858. container.Config.WorkingDir = filepath.Clean(container.Config.WorkingDir)
  859. pth, err := container.GetResourcePath(container.Config.WorkingDir)
  860. if err != nil {
  861. return err
  862. }
  863. pthInfo, err := os.Stat(pth)
  864. if err != nil {
  865. if !os.IsNotExist(err) {
  866. return err
  867. }
  868. if err := system.MkdirAll(pth, 0755); err != nil {
  869. return err
  870. }
  871. }
  872. if pthInfo != nil && !pthInfo.IsDir() {
  873. return derr.ErrorCodeNotADir.WithArgs(container.Config.WorkingDir)
  874. }
  875. }
  876. return nil
  877. }
  878. func (container *Container) getNetworkedContainer(ctx context.Context) (*Container, error) {
  879. parts := strings.SplitN(string(container.hostConfig.NetworkMode), ":", 2)
  880. switch parts[0] {
  881. case "container":
  882. if len(parts) != 2 {
  883. return nil, derr.ErrorCodeParseContainer
  884. }
  885. nc, err := container.daemon.Get(ctx, parts[1])
  886. if err != nil {
  887. return nil, err
  888. }
  889. if container == nc {
  890. return nil, derr.ErrorCodeJoinSelf
  891. }
  892. if !nc.IsRunning() {
  893. return nil, derr.ErrorCodeJoinRunning.WithArgs(parts[1])
  894. }
  895. return nc, nil
  896. default:
  897. return nil, derr.ErrorCodeModeNotContainer
  898. }
  899. }
  900. func (container *Container) releaseNetwork() {
  901. if container.hostConfig.NetworkMode.IsContainer() || container.Config.NetworkDisabled {
  902. return
  903. }
  904. sid := container.NetworkSettings.SandboxID
  905. eid := container.NetworkSettings.EndpointID
  906. nid := container.NetworkSettings.NetworkID
  907. container.NetworkSettings = &network.Settings{}
  908. if sid == "" || nid == "" || eid == "" {
  909. return
  910. }
  911. sb, err := container.daemon.netController.SandboxByID(sid)
  912. if err != nil {
  913. logrus.Errorf("error locating sandbox id %s: %v", sid, err)
  914. return
  915. }
  916. n, err := container.daemon.netController.NetworkByID(nid)
  917. if err != nil {
  918. logrus.Errorf("error locating network id %s: %v", nid, err)
  919. return
  920. }
  921. ep, err := n.EndpointByID(eid)
  922. if err != nil {
  923. logrus.Errorf("error locating endpoint id %s: %v", eid, err)
  924. return
  925. }
  926. if err := sb.Delete(); err != nil {
  927. logrus.Errorf("Error deleting sandbox id %s for container %s: %v", sid, container.ID, err)
  928. return
  929. }
  930. // In addition to leaving all endpoints, delete implicitly created endpoint
  931. if container.Config.PublishService == "" {
  932. if err := ep.Delete(); err != nil {
  933. logrus.Errorf("deleting endpoint failed: %v", err)
  934. }
  935. }
  936. }
  937. func (container *Container) unmountVolumes(forceSyscall bool) error {
  938. var volumeMounts []mountPoint
  939. for _, mntPoint := range container.MountPoints {
  940. dest, err := container.GetResourcePath(mntPoint.Destination)
  941. if err != nil {
  942. return err
  943. }
  944. volumeMounts = append(volumeMounts, mountPoint{Destination: dest, Volume: mntPoint.Volume})
  945. }
  946. for _, mnt := range container.networkMounts() {
  947. dest, err := container.GetResourcePath(mnt.Destination)
  948. if err != nil {
  949. return err
  950. }
  951. volumeMounts = append(volumeMounts, mountPoint{Destination: dest})
  952. }
  953. for _, volumeMount := range volumeMounts {
  954. if forceSyscall {
  955. syscall.Unmount(volumeMount.Destination, 0)
  956. }
  957. if volumeMount.Volume != nil {
  958. if err := volumeMount.Volume.Unmount(); err != nil {
  959. return err
  960. }
  961. }
  962. }
  963. return nil
  964. }
  965. func (container *Container) networkMounts() []execdriver.Mount {
  966. var mounts []execdriver.Mount
  967. shared := container.hostConfig.NetworkMode.IsContainer()
  968. if container.ResolvConfPath != "" {
  969. label.Relabel(container.ResolvConfPath, container.MountLabel, shared)
  970. writable := !container.hostConfig.ReadonlyRootfs
  971. if m, exists := container.MountPoints["/etc/resolv.conf"]; exists {
  972. writable = m.RW
  973. }
  974. mounts = append(mounts, execdriver.Mount{
  975. Source: container.ResolvConfPath,
  976. Destination: "/etc/resolv.conf",
  977. Writable: writable,
  978. Private: true,
  979. })
  980. }
  981. if container.HostnamePath != "" {
  982. label.Relabel(container.HostnamePath, container.MountLabel, shared)
  983. writable := !container.hostConfig.ReadonlyRootfs
  984. if m, exists := container.MountPoints["/etc/hostname"]; exists {
  985. writable = m.RW
  986. }
  987. mounts = append(mounts, execdriver.Mount{
  988. Source: container.HostnamePath,
  989. Destination: "/etc/hostname",
  990. Writable: writable,
  991. Private: true,
  992. })
  993. }
  994. if container.HostsPath != "" {
  995. label.Relabel(container.HostsPath, container.MountLabel, shared)
  996. writable := !container.hostConfig.ReadonlyRootfs
  997. if m, exists := container.MountPoints["/etc/hosts"]; exists {
  998. writable = m.RW
  999. }
  1000. mounts = append(mounts, execdriver.Mount{
  1001. Source: container.HostsPath,
  1002. Destination: "/etc/hosts",
  1003. Writable: writable,
  1004. Private: true,
  1005. })
  1006. }
  1007. return mounts
  1008. }
  1009. func (container *Container) addBindMountPoint(name, source, destination string, rw bool) {
  1010. container.MountPoints[destination] = &mountPoint{
  1011. Name: name,
  1012. Source: source,
  1013. Destination: destination,
  1014. RW: rw,
  1015. }
  1016. }
  1017. func (container *Container) addLocalMountPoint(name, destination string, rw bool) {
  1018. container.MountPoints[destination] = &mountPoint{
  1019. Name: name,
  1020. Driver: volume.DefaultDriverName,
  1021. Destination: destination,
  1022. RW: rw,
  1023. }
  1024. }
  1025. func (container *Container) addMountPointWithVolume(destination string, vol volume.Volume, rw bool) {
  1026. container.MountPoints[destination] = &mountPoint{
  1027. Name: vol.Name(),
  1028. Driver: vol.DriverName(),
  1029. Destination: destination,
  1030. RW: rw,
  1031. Volume: vol,
  1032. }
  1033. }
  1034. func (container *Container) isDestinationMounted(destination string) bool {
  1035. return container.MountPoints[destination] != nil
  1036. }
  1037. func (container *Container) prepareMountPoints() error {
  1038. for _, config := range container.MountPoints {
  1039. if len(config.Driver) > 0 {
  1040. v, err := container.daemon.createVolume(config.Name, config.Driver, nil)
  1041. if err != nil {
  1042. return err
  1043. }
  1044. config.Volume = v
  1045. }
  1046. }
  1047. return nil
  1048. }
  1049. func (container *Container) removeMountPoints(rm bool) error {
  1050. var rmErrors []string
  1051. for _, m := range container.MountPoints {
  1052. if m.Volume == nil {
  1053. continue
  1054. }
  1055. container.daemon.volumes.Decrement(m.Volume)
  1056. if rm {
  1057. err := container.daemon.volumes.Remove(m.Volume)
  1058. // ErrVolumeInUse is ignored because having this
  1059. // volume being referenced by othe container is
  1060. // not an error, but an implementation detail.
  1061. // This prevents docker from logging "ERROR: Volume in use"
  1062. // where there is another container using the volume.
  1063. if err != nil && err != store.ErrVolumeInUse {
  1064. rmErrors = append(rmErrors, err.Error())
  1065. }
  1066. }
  1067. }
  1068. if len(rmErrors) > 0 {
  1069. return derr.ErrorCodeRemovingVolume.WithArgs(strings.Join(rmErrors, "\n"))
  1070. }
  1071. return nil
  1072. }
  1073. func (container *Container) shmPath() (string, error) {
  1074. return container.getRootResourcePath("shm")
  1075. }
  1076. func (container *Container) mqueuePath() (string, error) {
  1077. return container.getRootResourcePath("mqueue")
  1078. }
  1079. func (container *Container) setupIpcDirs() error {
  1080. shmPath, err := container.shmPath()
  1081. if err != nil {
  1082. return err
  1083. }
  1084. if err := os.MkdirAll(shmPath, 0700); err != nil {
  1085. return err
  1086. }
  1087. 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 {
  1088. return fmt.Errorf("mounting shm tmpfs: %s", err)
  1089. }
  1090. mqueuePath, err := container.mqueuePath()
  1091. if err != nil {
  1092. return err
  1093. }
  1094. if err := os.MkdirAll(mqueuePath, 0700); err != nil {
  1095. return err
  1096. }
  1097. if err := syscall.Mount("mqueue", mqueuePath, "mqueue", uintptr(syscall.MS_NOEXEC|syscall.MS_NOSUID|syscall.MS_NODEV), ""); err != nil {
  1098. return fmt.Errorf("mounting mqueue mqueue : %s", err)
  1099. }
  1100. return nil
  1101. }
  1102. func (container *Container) unmountIpcMounts() error {
  1103. if container.hostConfig.IpcMode.IsContainer() || container.hostConfig.IpcMode.IsHost() {
  1104. return nil
  1105. }
  1106. var errors []string
  1107. shmPath, err := container.shmPath()
  1108. if err != nil {
  1109. logrus.Error(err)
  1110. errors = append(errors, err.Error())
  1111. } else {
  1112. if err := detachMounted(shmPath); err != nil {
  1113. logrus.Errorf("failed to umount %s: %v", shmPath, err)
  1114. errors = append(errors, err.Error())
  1115. }
  1116. }
  1117. mqueuePath, err := container.mqueuePath()
  1118. if err != nil {
  1119. logrus.Error(err)
  1120. errors = append(errors, err.Error())
  1121. } else {
  1122. if err := detachMounted(mqueuePath); err != nil {
  1123. logrus.Errorf("failed to umount %s: %v", mqueuePath, err)
  1124. errors = append(errors, err.Error())
  1125. }
  1126. }
  1127. if len(errors) > 0 {
  1128. return fmt.Errorf("failed to cleanup ipc mounts:\n%v", strings.Join(errors, "\n"))
  1129. }
  1130. return nil
  1131. }
  1132. func (container *Container) ipcMounts() []execdriver.Mount {
  1133. var mounts []execdriver.Mount
  1134. label.SetFileLabel(container.ShmPath, container.MountLabel)
  1135. mounts = append(mounts, execdriver.Mount{
  1136. Source: container.ShmPath,
  1137. Destination: "/dev/shm",
  1138. Writable: true,
  1139. Private: true,
  1140. })
  1141. label.SetFileLabel(container.MqueuePath, container.MountLabel)
  1142. mounts = append(mounts, execdriver.Mount{
  1143. Source: container.MqueuePath,
  1144. Destination: "/dev/mqueue",
  1145. Writable: true,
  1146. Private: true,
  1147. })
  1148. return mounts
  1149. }
  1150. func detachMounted(path string) error {
  1151. return syscall.Unmount(path, syscall.MNT_DETACH)
  1152. }