container_unix.go 40 KB

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