container_unix.go 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482
  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. if updateSettings {
  764. return err
  765. }
  766. // dont fail a container restart case if the user removed the network
  767. logrus.Warnf("Could not connect container %s : %v", container.ID, err)
  768. }
  769. }
  770. return container.writeHostConfig()
  771. }
  772. // ConnectToNetwork connects a container to a netork
  773. func (container *Container) ConnectToNetwork(idOrName string) error {
  774. if !container.Running {
  775. return derr.ErrorCodeNotRunning.WithArgs(container.ID)
  776. }
  777. return container.connectToNetwork(idOrName, true)
  778. }
  779. func (container *Container) connectToNetwork(idOrName string, updateSettings bool) error {
  780. var err error
  781. if container.hostConfig.NetworkMode.IsContainer() {
  782. return runconfig.ErrConflictSharedNetwork
  783. }
  784. if runconfig.NetworkMode(idOrName).IsBridge() &&
  785. container.daemon.configStore.DisableBridge {
  786. container.Config.NetworkDisabled = true
  787. return nil
  788. }
  789. controller := container.daemon.netController
  790. n, err := container.daemon.FindNetwork(idOrName)
  791. if err != nil {
  792. return err
  793. }
  794. if updateSettings {
  795. if err := container.updateNetworkSettings(n); err != nil {
  796. return err
  797. }
  798. }
  799. ep, err := container.getEndpointInNetwork(n)
  800. if err == nil {
  801. return fmt.Errorf("container already connected to network %s", idOrName)
  802. }
  803. if _, ok := err.(libnetwork.ErrNoSuchEndpoint); !ok {
  804. return err
  805. }
  806. createOptions, err := container.buildCreateEndpointOptions()
  807. if err != nil {
  808. return err
  809. }
  810. endpointName := strings.TrimPrefix(container.Name, "/")
  811. ep, err = n.CreateEndpoint(endpointName, createOptions...)
  812. if err != nil {
  813. return err
  814. }
  815. defer func() {
  816. if err != nil {
  817. if e := ep.Delete(); e != nil {
  818. logrus.Warnf("Could not rollback container connection to network %s", idOrName)
  819. }
  820. }
  821. }()
  822. if err := container.updateEndpointNetworkSettings(n, ep); err != nil {
  823. return err
  824. }
  825. var sb libnetwork.Sandbox
  826. controller.WalkSandboxes(func(s libnetwork.Sandbox) bool {
  827. if s.ContainerID() == container.ID {
  828. sb = s
  829. return true
  830. }
  831. return false
  832. })
  833. if sb == nil {
  834. options, err := container.buildSandboxOptions(n)
  835. if err != nil {
  836. return err
  837. }
  838. sb, err = controller.NewSandbox(container.ID, options...)
  839. if err != nil {
  840. return err
  841. }
  842. container.updateSandboxNetworkSettings(sb)
  843. }
  844. if err := ep.Join(sb); err != nil {
  845. return err
  846. }
  847. if err := container.updateJoinInfo(ep); err != nil {
  848. return derr.ErrorCodeJoinInfo.WithArgs(err)
  849. }
  850. return nil
  851. }
  852. func (container *Container) initializeNetworking() error {
  853. var err error
  854. if container.hostConfig.NetworkMode.IsContainer() {
  855. // we need to get the hosts files from the container to join
  856. nc, err := container.getNetworkedContainer()
  857. if err != nil {
  858. return err
  859. }
  860. container.HostnamePath = nc.HostnamePath
  861. container.HostsPath = nc.HostsPath
  862. container.ResolvConfPath = nc.ResolvConfPath
  863. container.Config.Hostname = nc.Config.Hostname
  864. container.Config.Domainname = nc.Config.Domainname
  865. return nil
  866. }
  867. if container.hostConfig.NetworkMode.IsHost() {
  868. container.Config.Hostname, err = os.Hostname()
  869. if err != nil {
  870. return err
  871. }
  872. parts := strings.SplitN(container.Config.Hostname, ".", 2)
  873. if len(parts) > 1 {
  874. container.Config.Hostname = parts[0]
  875. container.Config.Domainname = parts[1]
  876. }
  877. }
  878. if err := container.allocateNetwork(); err != nil {
  879. return err
  880. }
  881. return container.buildHostnameFile()
  882. }
  883. // called from the libcontainer pre-start hook to set the network
  884. // namespace configuration linkage to the libnetwork "sandbox" entity
  885. func (container *Container) setNetworkNamespaceKey(pid int) error {
  886. path := fmt.Sprintf("/proc/%d/ns/net", pid)
  887. var sandbox libnetwork.Sandbox
  888. search := libnetwork.SandboxContainerWalker(&sandbox, container.ID)
  889. container.daemon.netController.WalkSandboxes(search)
  890. if sandbox == nil {
  891. return derr.ErrorCodeNoSandbox.WithArgs(container.ID)
  892. }
  893. return sandbox.SetKey(path)
  894. }
  895. func (container *Container) getIpcContainer() (*Container, error) {
  896. containerID := container.hostConfig.IpcMode.Container()
  897. c, err := container.daemon.Get(containerID)
  898. if err != nil {
  899. return nil, err
  900. }
  901. if !c.IsRunning() {
  902. return nil, derr.ErrorCodeIPCRunning
  903. }
  904. return c, nil
  905. }
  906. func (container *Container) setupWorkingDirectory() error {
  907. if container.Config.WorkingDir != "" {
  908. container.Config.WorkingDir = filepath.Clean(container.Config.WorkingDir)
  909. pth, err := container.GetResourcePath(container.Config.WorkingDir)
  910. if err != nil {
  911. return err
  912. }
  913. pthInfo, err := os.Stat(pth)
  914. if err != nil {
  915. if !os.IsNotExist(err) {
  916. return err
  917. }
  918. if err := system.MkdirAll(pth, 0755); err != nil {
  919. return err
  920. }
  921. }
  922. if pthInfo != nil && !pthInfo.IsDir() {
  923. return derr.ErrorCodeNotADir.WithArgs(container.Config.WorkingDir)
  924. }
  925. }
  926. return nil
  927. }
  928. func (container *Container) getNetworkedContainer() (*Container, error) {
  929. parts := strings.SplitN(string(container.hostConfig.NetworkMode), ":", 2)
  930. switch parts[0] {
  931. case "container":
  932. if len(parts) != 2 {
  933. return nil, derr.ErrorCodeParseContainer
  934. }
  935. nc, err := container.daemon.Get(parts[1])
  936. if err != nil {
  937. return nil, err
  938. }
  939. if container == nc {
  940. return nil, derr.ErrorCodeJoinSelf
  941. }
  942. if !nc.IsRunning() {
  943. return nil, derr.ErrorCodeJoinRunning.WithArgs(parts[1])
  944. }
  945. return nc, nil
  946. default:
  947. return nil, derr.ErrorCodeModeNotContainer
  948. }
  949. }
  950. func (container *Container) releaseNetwork() {
  951. if container.hostConfig.NetworkMode.IsContainer() || container.Config.NetworkDisabled {
  952. return
  953. }
  954. sid := container.NetworkSettings.SandboxID
  955. networks := container.NetworkSettings.Networks
  956. container.NetworkSettings = &network.Settings{Networks: networks}
  957. if sid == "" || len(networks) == 0 {
  958. return
  959. }
  960. sb, err := container.daemon.netController.SandboxByID(sid)
  961. if err != nil {
  962. logrus.Errorf("error locating sandbox id %s: %v", sid, err)
  963. return
  964. }
  965. if err := sb.Delete(); err != nil {
  966. logrus.Errorf("Error deleting sandbox id %s for container %s: %v", sid, container.ID, err)
  967. }
  968. }
  969. // DisconnectFromNetwork disconnects a container from a network
  970. func (container *Container) DisconnectFromNetwork(n libnetwork.Network) error {
  971. if !container.Running {
  972. return derr.ErrorCodeNotRunning.WithArgs(container.ID)
  973. }
  974. return container.disconnectFromNetwork(n)
  975. }
  976. func (container *Container) disconnectFromNetwork(n libnetwork.Network) error {
  977. var (
  978. ep libnetwork.Endpoint
  979. sbox libnetwork.Sandbox
  980. )
  981. s := func(current libnetwork.Endpoint) bool {
  982. if sb := current.Info().Sandbox(); sb != nil {
  983. if sb.ContainerID() == container.ID {
  984. ep = current
  985. sbox = sb
  986. return true
  987. }
  988. }
  989. return false
  990. }
  991. n.WalkEndpoints(s)
  992. if ep == nil {
  993. return fmt.Errorf("container %s is not connected to the network", container.ID)
  994. }
  995. if err := ep.Leave(sbox); err != nil {
  996. return fmt.Errorf("container %s failed to leave network %s: %v", container.ID, n.Name(), err)
  997. }
  998. if err := ep.Delete(); err != nil {
  999. return fmt.Errorf("endpoint delete failed for container %s on network %s: %v", container.ID, n.Name(), err)
  1000. }
  1001. networks := container.NetworkSettings.Networks
  1002. for i, s := range networks {
  1003. sn, err := container.daemon.FindNetwork(s)
  1004. if err != nil {
  1005. continue
  1006. }
  1007. if sn.Name() == n.Name() {
  1008. networks = append(networks[:i], networks[i+1:]...)
  1009. container.NetworkSettings.Networks = networks
  1010. break
  1011. }
  1012. }
  1013. return nil
  1014. }
  1015. func (container *Container) unmountVolumes(forceSyscall bool) error {
  1016. var volumeMounts []mountPoint
  1017. for _, mntPoint := range container.MountPoints {
  1018. dest, err := container.GetResourcePath(mntPoint.Destination)
  1019. if err != nil {
  1020. return err
  1021. }
  1022. volumeMounts = append(volumeMounts, mountPoint{Destination: dest, Volume: mntPoint.Volume})
  1023. }
  1024. for _, mnt := range container.networkMounts() {
  1025. dest, err := container.GetResourcePath(mnt.Destination)
  1026. if err != nil {
  1027. return err
  1028. }
  1029. volumeMounts = append(volumeMounts, mountPoint{Destination: dest})
  1030. }
  1031. for _, volumeMount := range volumeMounts {
  1032. if forceSyscall {
  1033. syscall.Unmount(volumeMount.Destination, 0)
  1034. }
  1035. if volumeMount.Volume != nil {
  1036. if err := volumeMount.Volume.Unmount(); err != nil {
  1037. return err
  1038. }
  1039. }
  1040. }
  1041. return nil
  1042. }
  1043. func (container *Container) networkMounts() []execdriver.Mount {
  1044. var mounts []execdriver.Mount
  1045. shared := container.hostConfig.NetworkMode.IsContainer()
  1046. if container.ResolvConfPath != "" {
  1047. if _, err := os.Stat(container.ResolvConfPath); err != nil {
  1048. logrus.Warnf("ResolvConfPath set to %q, but can't stat this filename (err = %v); skipping", container.ResolvConfPath, err)
  1049. } else {
  1050. label.Relabel(container.ResolvConfPath, container.MountLabel, shared)
  1051. writable := !container.hostConfig.ReadonlyRootfs
  1052. if m, exists := container.MountPoints["/etc/resolv.conf"]; exists {
  1053. writable = m.RW
  1054. }
  1055. mounts = append(mounts, execdriver.Mount{
  1056. Source: container.ResolvConfPath,
  1057. Destination: "/etc/resolv.conf",
  1058. Writable: writable,
  1059. Private: true,
  1060. })
  1061. }
  1062. }
  1063. if container.HostnamePath != "" {
  1064. if _, err := os.Stat(container.HostnamePath); err != nil {
  1065. logrus.Warnf("HostnamePath set to %q, but can't stat this filename (err = %v); skipping", container.HostnamePath, err)
  1066. } else {
  1067. label.Relabel(container.HostnamePath, container.MountLabel, shared)
  1068. writable := !container.hostConfig.ReadonlyRootfs
  1069. if m, exists := container.MountPoints["/etc/hostname"]; exists {
  1070. writable = m.RW
  1071. }
  1072. mounts = append(mounts, execdriver.Mount{
  1073. Source: container.HostnamePath,
  1074. Destination: "/etc/hostname",
  1075. Writable: writable,
  1076. Private: true,
  1077. })
  1078. }
  1079. }
  1080. if container.HostsPath != "" {
  1081. if _, err := os.Stat(container.HostsPath); err != nil {
  1082. logrus.Warnf("HostsPath set to %q, but can't stat this filename (err = %v); skipping", container.HostsPath, err)
  1083. } else {
  1084. label.Relabel(container.HostsPath, container.MountLabel, shared)
  1085. writable := !container.hostConfig.ReadonlyRootfs
  1086. if m, exists := container.MountPoints["/etc/hosts"]; exists {
  1087. writable = m.RW
  1088. }
  1089. mounts = append(mounts, execdriver.Mount{
  1090. Source: container.HostsPath,
  1091. Destination: "/etc/hosts",
  1092. Writable: writable,
  1093. Private: true,
  1094. })
  1095. }
  1096. }
  1097. return mounts
  1098. }
  1099. func (container *Container) addBindMountPoint(name, source, destination string, rw bool) {
  1100. container.MountPoints[destination] = &mountPoint{
  1101. Name: name,
  1102. Source: source,
  1103. Destination: destination,
  1104. RW: rw,
  1105. }
  1106. }
  1107. func (container *Container) addLocalMountPoint(name, destination string, rw bool) {
  1108. container.MountPoints[destination] = &mountPoint{
  1109. Name: name,
  1110. Driver: volume.DefaultDriverName,
  1111. Destination: destination,
  1112. RW: rw,
  1113. }
  1114. }
  1115. func (container *Container) addMountPointWithVolume(destination string, vol volume.Volume, rw bool) {
  1116. container.MountPoints[destination] = &mountPoint{
  1117. Name: vol.Name(),
  1118. Driver: vol.DriverName(),
  1119. Destination: destination,
  1120. RW: rw,
  1121. Volume: vol,
  1122. }
  1123. }
  1124. func (container *Container) isDestinationMounted(destination string) bool {
  1125. return container.MountPoints[destination] != nil
  1126. }
  1127. func (container *Container) prepareMountPoints() error {
  1128. for _, config := range container.MountPoints {
  1129. if len(config.Driver) > 0 {
  1130. v, err := container.daemon.createVolume(config.Name, config.Driver, nil)
  1131. if err != nil {
  1132. return err
  1133. }
  1134. config.Volume = v
  1135. }
  1136. }
  1137. return nil
  1138. }
  1139. func (container *Container) removeMountPoints(rm bool) error {
  1140. var rmErrors []string
  1141. for _, m := range container.MountPoints {
  1142. if m.Volume == nil {
  1143. continue
  1144. }
  1145. container.daemon.volumes.Decrement(m.Volume)
  1146. if rm {
  1147. err := container.daemon.volumes.Remove(m.Volume)
  1148. // ErrVolumeInUse is ignored because having this
  1149. // volume being referenced by othe container is
  1150. // not an error, but an implementation detail.
  1151. // This prevents docker from logging "ERROR: Volume in use"
  1152. // where there is another container using the volume.
  1153. if err != nil && err != store.ErrVolumeInUse {
  1154. rmErrors = append(rmErrors, err.Error())
  1155. }
  1156. }
  1157. }
  1158. if len(rmErrors) > 0 {
  1159. return derr.ErrorCodeRemovingVolume.WithArgs(strings.Join(rmErrors, "\n"))
  1160. }
  1161. return nil
  1162. }
  1163. func (container *Container) shmPath() (string, error) {
  1164. return container.getRootResourcePath("shm")
  1165. }
  1166. func (container *Container) mqueuePath() (string, error) {
  1167. return container.getRootResourcePath("mqueue")
  1168. }
  1169. func (container *Container) hasMountFor(path string) bool {
  1170. _, exists := container.MountPoints[path]
  1171. return exists
  1172. }
  1173. func (container *Container) setupIpcDirs() error {
  1174. rootUID, rootGID := container.daemon.GetRemappedUIDGID()
  1175. if !container.hasMountFor("/dev/shm") {
  1176. shmPath, err := container.shmPath()
  1177. if err != nil {
  1178. return err
  1179. }
  1180. if err := idtools.MkdirAllAs(shmPath, 0700, rootUID, rootGID); err != nil {
  1181. return err
  1182. }
  1183. 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 {
  1184. return fmt.Errorf("mounting shm tmpfs: %s", err)
  1185. }
  1186. if err := os.Chown(shmPath, rootUID, rootGID); err != nil {
  1187. return err
  1188. }
  1189. }
  1190. if !container.hasMountFor("/dev/mqueue") {
  1191. mqueuePath, err := container.mqueuePath()
  1192. if err != nil {
  1193. return err
  1194. }
  1195. if err := idtools.MkdirAllAs(mqueuePath, 0700, rootUID, rootGID); err != nil {
  1196. return err
  1197. }
  1198. if err := syscall.Mount("mqueue", mqueuePath, "mqueue", uintptr(syscall.MS_NOEXEC|syscall.MS_NOSUID|syscall.MS_NODEV), ""); err != nil {
  1199. return fmt.Errorf("mounting mqueue mqueue : %s", err)
  1200. }
  1201. if err := os.Chown(mqueuePath, rootUID, rootGID); err != nil {
  1202. return err
  1203. }
  1204. }
  1205. return nil
  1206. }
  1207. func (container *Container) unmountIpcMounts() error {
  1208. if container.hostConfig.IpcMode.IsContainer() || container.hostConfig.IpcMode.IsHost() {
  1209. return nil
  1210. }
  1211. var errors []string
  1212. if !container.hasMountFor("/dev/shm") {
  1213. shmPath, err := container.shmPath()
  1214. if err != nil {
  1215. logrus.Error(err)
  1216. errors = append(errors, err.Error())
  1217. } else {
  1218. if err := detachMounted(shmPath); err != nil {
  1219. logrus.Errorf("failed to umount %s: %v", shmPath, err)
  1220. errors = append(errors, err.Error())
  1221. }
  1222. }
  1223. }
  1224. if !container.hasMountFor("/dev/mqueue") {
  1225. mqueuePath, err := container.mqueuePath()
  1226. if err != nil {
  1227. logrus.Error(err)
  1228. errors = append(errors, err.Error())
  1229. } else {
  1230. if err := detachMounted(mqueuePath); err != nil {
  1231. logrus.Errorf("failed to umount %s: %v", mqueuePath, err)
  1232. errors = append(errors, err.Error())
  1233. }
  1234. }
  1235. }
  1236. if len(errors) > 0 {
  1237. return fmt.Errorf("failed to cleanup ipc mounts:\n%v", strings.Join(errors, "\n"))
  1238. }
  1239. return nil
  1240. }
  1241. func (container *Container) ipcMounts() []execdriver.Mount {
  1242. var mounts []execdriver.Mount
  1243. if !container.hasMountFor("/dev/shm") {
  1244. label.SetFileLabel(container.ShmPath, container.MountLabel)
  1245. mounts = append(mounts, execdriver.Mount{
  1246. Source: container.ShmPath,
  1247. Destination: "/dev/shm",
  1248. Writable: true,
  1249. Private: true,
  1250. })
  1251. }
  1252. if !container.hasMountFor("/dev/mqueue") {
  1253. label.SetFileLabel(container.MqueuePath, container.MountLabel)
  1254. mounts = append(mounts, execdriver.Mount{
  1255. Source: container.MqueuePath,
  1256. Destination: "/dev/mqueue",
  1257. Writable: true,
  1258. Private: true,
  1259. })
  1260. }
  1261. return mounts
  1262. }
  1263. func detachMounted(path string) error {
  1264. return syscall.Unmount(path, syscall.MNT_DETACH)
  1265. }