container_unix.go 40 KB

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