container_unix.go 43 KB

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