container_unix.go 40 KB

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