container_unix.go 40 KB

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