container_unix.go 42 KB

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