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