container_unix.go 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531
  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. // DefaultPathEnv is unix style list of directories to search for
  39. // executables. Each directory is separated from the next by a colon
  40. // ':' character .
  41. const DefaultPathEnv = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
  42. // Container holds the fields specific to unixen implementations. See
  43. // CommonContainer for standard fields common to all containers.
  44. type Container struct {
  45. CommonContainer
  46. // Fields below here are platform specific.
  47. activeLinks map[string]*links.Link
  48. AppArmorProfile string
  49. HostnamePath string
  50. HostsPath string
  51. ShmPath string
  52. MqueuePath string
  53. ResolvConfPath string
  54. }
  55. func killProcessDirectly(container *Container) error {
  56. if _, err := container.WaitStop(10 * time.Second); err != nil {
  57. // Ensure that we don't kill ourselves
  58. if pid := container.GetPID(); pid != 0 {
  59. logrus.Infof("Container %s failed to exit within 10 seconds of kill - trying direct SIGKILL", stringid.TruncateID(container.ID))
  60. if err := syscall.Kill(pid, 9); err != nil {
  61. if err != syscall.ESRCH {
  62. return err
  63. }
  64. logrus.Debugf("Cannot kill process (pid=%d) with signal 9: no such process.", pid)
  65. }
  66. }
  67. }
  68. return nil
  69. }
  70. func (daemon *Daemon) setupLinkedContainers(container *Container) ([]string, error) {
  71. var env []string
  72. children, err := daemon.children(container.Name)
  73. if err != nil {
  74. return nil, err
  75. }
  76. bridgeSettings := container.NetworkSettings.Networks["bridge"]
  77. if bridgeSettings == nil {
  78. return nil, nil
  79. }
  80. if len(children) > 0 {
  81. for linkAlias, child := range children {
  82. if !child.IsRunning() {
  83. return nil, derr.ErrorCodeLinkNotRunning.WithArgs(child.Name, linkAlias)
  84. }
  85. childBridgeSettings := child.NetworkSettings.Networks["bridge"]
  86. if childBridgeSettings == nil {
  87. return nil, fmt.Errorf("container %s not attached to default bridge network", child.ID)
  88. }
  89. link := links.NewLink(
  90. bridgeSettings.IPAddress,
  91. childBridgeSettings.IPAddress,
  92. linkAlias,
  93. child.Config.Env,
  94. child.Config.ExposedPorts,
  95. )
  96. for _, envVar := range link.ToEnv() {
  97. env = append(env, envVar)
  98. }
  99. }
  100. }
  101. return env, nil
  102. }
  103. func (container *Container) createDaemonEnvironment(linkedEnv []string) []string {
  104. // if a domain name was specified, append it to the hostname (see #7851)
  105. fullHostname := container.Config.Hostname
  106. if container.Config.Domainname != "" {
  107. fullHostname = fmt.Sprintf("%s.%s", fullHostname, container.Config.Domainname)
  108. }
  109. // Setup environment
  110. env := []string{
  111. "PATH=" + DefaultPathEnv,
  112. "HOSTNAME=" + fullHostname,
  113. // Note: we don't set HOME here because it'll get autoset intelligently
  114. // based on the value of USER inside dockerinit, but only if it isn't
  115. // set already (ie, that can be overridden by setting HOME via -e or ENV
  116. // in a Dockerfile).
  117. }
  118. if container.Config.Tty {
  119. env = append(env, "TERM=xterm")
  120. }
  121. env = append(env, linkedEnv...)
  122. // because the env on the container can override certain default values
  123. // we need to replace the 'env' keys where they match and append anything
  124. // else.
  125. env = utils.ReplaceOrAppendEnvValues(env, container.Config.Env)
  126. return env
  127. }
  128. func getDevicesFromPath(deviceMapping runconfig.DeviceMapping) (devs []*configs.Device, err error) {
  129. device, err := devices.DeviceFromPath(deviceMapping.PathOnHost, deviceMapping.CgroupPermissions)
  130. // if there was no error, return the device
  131. if err == nil {
  132. device.Path = deviceMapping.PathInContainer
  133. return append(devs, device), nil
  134. }
  135. // if the device is not a device node
  136. // try to see if it's a directory holding many devices
  137. if err == devices.ErrNotADevice {
  138. // check if it is a directory
  139. if src, e := os.Stat(deviceMapping.PathOnHost); e == nil && src.IsDir() {
  140. // mount the internal devices recursively
  141. filepath.Walk(deviceMapping.PathOnHost, func(dpath string, f os.FileInfo, e error) error {
  142. childDevice, e := devices.DeviceFromPath(dpath, deviceMapping.CgroupPermissions)
  143. if e != nil {
  144. // ignore the device
  145. return nil
  146. }
  147. // add the device to userSpecified devices
  148. childDevice.Path = strings.Replace(dpath, deviceMapping.PathOnHost, deviceMapping.PathInContainer, 1)
  149. devs = append(devs, childDevice)
  150. return nil
  151. })
  152. }
  153. }
  154. if len(devs) > 0 {
  155. return devs, nil
  156. }
  157. return devs, derr.ErrorCodeDeviceInfo.WithArgs(deviceMapping.PathOnHost, err)
  158. }
  159. func (daemon *Daemon) populateCommand(c *Container, env []string) error {
  160. var en *execdriver.Network
  161. if !c.Config.NetworkDisabled {
  162. en = &execdriver.Network{}
  163. if !daemon.execDriver.SupportsHooks() || c.hostConfig.NetworkMode.IsHost() {
  164. en.NamespacePath = c.NetworkSettings.SandboxKey
  165. }
  166. if c.hostConfig.NetworkMode.IsContainer() {
  167. nc, err := daemon.getNetworkedContainer(c.ID, c.hostConfig.NetworkMode.ConnectedContainer())
  168. if err != nil {
  169. return err
  170. }
  171. en.ContainerID = nc.ID
  172. }
  173. }
  174. ipc := &execdriver.Ipc{}
  175. var err error
  176. c.ShmPath, err = c.shmPath()
  177. if err != nil {
  178. return err
  179. }
  180. c.MqueuePath, err = c.mqueuePath()
  181. if err != nil {
  182. return err
  183. }
  184. if c.hostConfig.IpcMode.IsContainer() {
  185. ic, err := daemon.getIpcContainer(c)
  186. if err != nil {
  187. return err
  188. }
  189. ipc.ContainerID = ic.ID
  190. c.ShmPath = ic.ShmPath
  191. c.MqueuePath = ic.MqueuePath
  192. } else {
  193. ipc.HostIpc = c.hostConfig.IpcMode.IsHost()
  194. if ipc.HostIpc {
  195. if _, err := os.Stat("/dev/shm"); err != nil {
  196. return fmt.Errorf("/dev/shm is not mounted, but must be for --ipc=host")
  197. }
  198. if _, err := os.Stat("/dev/mqueue"); err != nil {
  199. return fmt.Errorf("/dev/mqueue is not mounted, but must be for --ipc=host")
  200. }
  201. c.ShmPath = "/dev/shm"
  202. c.MqueuePath = "/dev/mqueue"
  203. }
  204. }
  205. pid := &execdriver.Pid{}
  206. pid.HostPid = c.hostConfig.PidMode.IsHost()
  207. uts := &execdriver.UTS{
  208. HostUTS: c.hostConfig.UTSMode.IsHost(),
  209. }
  210. // Build lists of devices allowed and created within the container.
  211. var userSpecifiedDevices []*configs.Device
  212. for _, deviceMapping := range c.hostConfig.Devices {
  213. devs, err := getDevicesFromPath(deviceMapping)
  214. if err != nil {
  215. return err
  216. }
  217. userSpecifiedDevices = append(userSpecifiedDevices, devs...)
  218. }
  219. allowedDevices := mergeDevices(configs.DefaultAllowedDevices, userSpecifiedDevices)
  220. autoCreatedDevices := mergeDevices(configs.DefaultAutoCreatedDevices, userSpecifiedDevices)
  221. var rlimits []*ulimit.Rlimit
  222. ulimits := c.hostConfig.Ulimits
  223. // Merge ulimits with daemon defaults
  224. ulIdx := make(map[string]*ulimit.Ulimit)
  225. for _, ul := range ulimits {
  226. ulIdx[ul.Name] = ul
  227. }
  228. for name, ul := range daemon.configStore.Ulimits {
  229. if _, exists := ulIdx[name]; !exists {
  230. ulimits = append(ulimits, ul)
  231. }
  232. }
  233. weightDevices, err := getBlkioWeightDevices(c.hostConfig)
  234. if err != nil {
  235. return err
  236. }
  237. for _, limit := range ulimits {
  238. rl, err := limit.GetRlimit()
  239. if err != nil {
  240. return err
  241. }
  242. rlimits = append(rlimits, rl)
  243. }
  244. resources := &execdriver.Resources{
  245. CommonResources: execdriver.CommonResources{
  246. Memory: c.hostConfig.Memory,
  247. MemoryReservation: c.hostConfig.MemoryReservation,
  248. CPUShares: c.hostConfig.CPUShares,
  249. BlkioWeight: c.hostConfig.BlkioWeight,
  250. },
  251. MemorySwap: c.hostConfig.MemorySwap,
  252. KernelMemory: c.hostConfig.KernelMemory,
  253. CpusetCpus: c.hostConfig.CpusetCpus,
  254. CpusetMems: c.hostConfig.CpusetMems,
  255. CPUPeriod: c.hostConfig.CPUPeriod,
  256. CPUQuota: c.hostConfig.CPUQuota,
  257. Rlimits: rlimits,
  258. BlkioWeightDevice: weightDevices,
  259. OomKillDisable: c.hostConfig.OomKillDisable,
  260. MemorySwappiness: -1,
  261. }
  262. if c.hostConfig.MemorySwappiness != nil {
  263. resources.MemorySwappiness = *c.hostConfig.MemorySwappiness
  264. }
  265. processConfig := execdriver.ProcessConfig{
  266. CommonProcessConfig: execdriver.CommonProcessConfig{
  267. Entrypoint: c.Path,
  268. Arguments: c.Args,
  269. Tty: c.Config.Tty,
  270. },
  271. Privileged: c.hostConfig.Privileged,
  272. User: c.Config.User,
  273. }
  274. processConfig.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
  275. processConfig.Env = env
  276. remappedRoot := &execdriver.User{}
  277. rootUID, rootGID := daemon.GetRemappedUIDGID()
  278. if rootUID != 0 {
  279. remappedRoot.UID = rootUID
  280. remappedRoot.GID = rootGID
  281. }
  282. uidMap, gidMap := daemon.GetUIDGIDMaps()
  283. c.command = &execdriver.Command{
  284. CommonCommand: execdriver.CommonCommand{
  285. ID: c.ID,
  286. InitPath: "/.dockerinit",
  287. MountLabel: c.getMountLabel(),
  288. Network: en,
  289. ProcessConfig: processConfig,
  290. ProcessLabel: c.getProcessLabel(),
  291. Rootfs: c.rootfsPath(),
  292. Resources: resources,
  293. WorkingDir: c.Config.WorkingDir,
  294. },
  295. AllowedDevices: allowedDevices,
  296. AppArmorProfile: c.AppArmorProfile,
  297. AutoCreatedDevices: autoCreatedDevices,
  298. CapAdd: c.hostConfig.CapAdd.Slice(),
  299. CapDrop: c.hostConfig.CapDrop.Slice(),
  300. CgroupParent: c.hostConfig.CgroupParent,
  301. GIDMapping: gidMap,
  302. GroupAdd: c.hostConfig.GroupAdd,
  303. Ipc: ipc,
  304. OomScoreAdj: c.hostConfig.OomScoreAdj,
  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. // When ShmSize is 0 or less, the SHM size is set to 64MB.
  1164. if container.hostConfig.ShmSize <= 0 {
  1165. container.hostConfig.ShmSize = 67108864
  1166. }
  1167. shmproperty := "mode=1777,size=" + strconv.FormatInt(container.hostConfig.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. }