container_unix.go 41 KB

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