container_unix.go 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428
  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 %d 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. ID: c.ID,
  288. Rootfs: c.rootfsPath(),
  289. ReadonlyRootfs: c.hostConfig.ReadonlyRootfs,
  290. InitPath: "/.dockerinit",
  291. WorkingDir: c.Config.WorkingDir,
  292. Network: en,
  293. Ipc: ipc,
  294. UIDMapping: uidMap,
  295. GIDMapping: gidMap,
  296. RemappedRoot: remappedRoot,
  297. Pid: pid,
  298. UTS: uts,
  299. Resources: resources,
  300. AllowedDevices: allowedDevices,
  301. AutoCreatedDevices: autoCreatedDevices,
  302. CapAdd: c.hostConfig.CapAdd.Slice(),
  303. CapDrop: c.hostConfig.CapDrop.Slice(),
  304. GroupAdd: c.hostConfig.GroupAdd,
  305. ProcessConfig: processConfig,
  306. ProcessLabel: c.getProcessLabel(),
  307. MountLabel: c.getMountLabel(),
  308. LxcConfig: lxcConfig,
  309. AppArmorProfile: c.AppArmorProfile,
  310. CgroupParent: c.hostConfig.CgroupParent,
  311. }
  312. return nil
  313. }
  314. func mergeDevices(defaultDevices, userDevices []*configs.Device) []*configs.Device {
  315. if len(userDevices) == 0 {
  316. return defaultDevices
  317. }
  318. paths := map[string]*configs.Device{}
  319. for _, d := range userDevices {
  320. paths[d.Path] = d
  321. }
  322. var devs []*configs.Device
  323. for _, d := range defaultDevices {
  324. if _, defined := paths[d.Path]; !defined {
  325. devs = append(devs, d)
  326. }
  327. }
  328. return append(devs, userDevices...)
  329. }
  330. // GetSize returns the real size & virtual size of the container.
  331. func (container *Container) getSize() (int64, int64) {
  332. var (
  333. sizeRw, sizeRootfs int64
  334. err error
  335. driver = container.daemon.driver
  336. )
  337. if err := container.Mount(); err != nil {
  338. logrus.Errorf("Failed to compute size of container rootfs %s: %s", container.ID, err)
  339. return sizeRw, sizeRootfs
  340. }
  341. defer container.Unmount()
  342. initID := fmt.Sprintf("%s-init", container.ID)
  343. sizeRw, err = driver.DiffSize(container.ID, initID)
  344. if err != nil {
  345. logrus.Errorf("Driver %s couldn't return diff size of container %s: %s", driver, container.ID, err)
  346. // FIXME: GetSize should return an error. Not changing it now in case
  347. // there is a side-effect.
  348. sizeRw = -1
  349. }
  350. if _, err = os.Stat(container.basefs); err == nil {
  351. if sizeRootfs, err = directory.Size(container.basefs); err != nil {
  352. sizeRootfs = -1
  353. }
  354. }
  355. return sizeRw, sizeRootfs
  356. }
  357. // Attempt to set the network mounts given a provided destination and
  358. // the path to use for it; return true if the given destination was a
  359. // network mount file
  360. func (container *Container) trySetNetworkMount(destination string, path string) bool {
  361. if destination == "/etc/resolv.conf" {
  362. container.ResolvConfPath = path
  363. return true
  364. }
  365. if destination == "/etc/hostname" {
  366. container.HostnamePath = path
  367. return true
  368. }
  369. if destination == "/etc/hosts" {
  370. container.HostsPath = path
  371. return true
  372. }
  373. return false
  374. }
  375. func (container *Container) buildHostnameFile() error {
  376. hostnamePath, err := container.getRootResourcePath("hostname")
  377. if err != nil {
  378. return err
  379. }
  380. container.HostnamePath = hostnamePath
  381. if container.Config.Domainname != "" {
  382. return ioutil.WriteFile(container.HostnamePath, []byte(fmt.Sprintf("%s.%s\n", container.Config.Hostname, container.Config.Domainname)), 0644)
  383. }
  384. return ioutil.WriteFile(container.HostnamePath, []byte(container.Config.Hostname+"\n"), 0644)
  385. }
  386. func (container *Container) buildSandboxOptions(n libnetwork.Network) ([]libnetwork.SandboxOption, error) {
  387. var (
  388. sboxOptions []libnetwork.SandboxOption
  389. err error
  390. dns []string
  391. dnsSearch []string
  392. dnsOptions []string
  393. )
  394. sboxOptions = append(sboxOptions, libnetwork.OptionHostname(container.Config.Hostname),
  395. libnetwork.OptionDomainname(container.Config.Domainname))
  396. if container.hostConfig.NetworkMode.IsHost() {
  397. sboxOptions = append(sboxOptions, libnetwork.OptionUseDefaultSandbox())
  398. sboxOptions = append(sboxOptions, libnetwork.OptionOriginHostsPath("/etc/hosts"))
  399. sboxOptions = append(sboxOptions, libnetwork.OptionOriginResolvConfPath("/etc/resolv.conf"))
  400. } else if container.daemon.execDriver.SupportsHooks() {
  401. // OptionUseExternalKey is mandatory for userns support.
  402. // But optional for non-userns support
  403. sboxOptions = append(sboxOptions, libnetwork.OptionUseExternalKey())
  404. }
  405. container.HostsPath, err = container.getRootResourcePath("hosts")
  406. if err != nil {
  407. return nil, err
  408. }
  409. sboxOptions = append(sboxOptions, libnetwork.OptionHostsPath(container.HostsPath))
  410. container.ResolvConfPath, err = container.getRootResourcePath("resolv.conf")
  411. if err != nil {
  412. return nil, err
  413. }
  414. sboxOptions = append(sboxOptions, libnetwork.OptionResolvConfPath(container.ResolvConfPath))
  415. if len(container.hostConfig.DNS) > 0 {
  416. dns = container.hostConfig.DNS
  417. } else if len(container.daemon.configStore.DNS) > 0 {
  418. dns = container.daemon.configStore.DNS
  419. }
  420. for _, d := range dns {
  421. sboxOptions = append(sboxOptions, libnetwork.OptionDNS(d))
  422. }
  423. if len(container.hostConfig.DNSSearch) > 0 {
  424. dnsSearch = container.hostConfig.DNSSearch
  425. } else if len(container.daemon.configStore.DNSSearch) > 0 {
  426. dnsSearch = container.daemon.configStore.DNSSearch
  427. }
  428. for _, ds := range dnsSearch {
  429. sboxOptions = append(sboxOptions, libnetwork.OptionDNSSearch(ds))
  430. }
  431. if len(container.hostConfig.DNSOptions) > 0 {
  432. dnsOptions = container.hostConfig.DNSOptions
  433. } else if len(container.daemon.configStore.DNSOptions) > 0 {
  434. dnsOptions = container.daemon.configStore.DNSOptions
  435. }
  436. for _, ds := range dnsOptions {
  437. sboxOptions = append(sboxOptions, libnetwork.OptionDNSOptions(ds))
  438. }
  439. if container.NetworkSettings.SecondaryIPAddresses != nil {
  440. name := container.Config.Hostname
  441. if container.Config.Domainname != "" {
  442. name = name + "." + container.Config.Domainname
  443. }
  444. for _, a := range container.NetworkSettings.SecondaryIPAddresses {
  445. sboxOptions = append(sboxOptions, libnetwork.OptionExtraHost(name, a.Addr))
  446. }
  447. }
  448. for _, extraHost := range container.hostConfig.ExtraHosts {
  449. // allow IPv6 addresses in extra hosts; only split on first ":"
  450. parts := strings.SplitN(extraHost, ":", 2)
  451. sboxOptions = append(sboxOptions, libnetwork.OptionExtraHost(parts[0], parts[1]))
  452. }
  453. // Link feature is supported only for the default bridge network.
  454. // return if this call to build join options is not for default bridge network
  455. if n.Name() != "bridge" {
  456. return sboxOptions, nil
  457. }
  458. ep, _ := container.getEndpointInNetwork(n)
  459. if ep == nil {
  460. return sboxOptions, nil
  461. }
  462. var childEndpoints, parentEndpoints []string
  463. children, err := container.daemon.children(container.Name)
  464. if err != nil {
  465. return nil, err
  466. }
  467. for linkAlias, child := range children {
  468. if !isLinkable(child) {
  469. return nil, fmt.Errorf("Cannot link to %s, as it does not belong to the default network", child.Name)
  470. }
  471. _, alias := path.Split(linkAlias)
  472. // allow access to the linked container via the alias, real name, and container hostname
  473. aliasList := alias + " " + child.Config.Hostname
  474. // only add the name if alias isn't equal to the name
  475. if alias != child.Name[1:] {
  476. aliasList = aliasList + " " + child.Name[1:]
  477. }
  478. sboxOptions = append(sboxOptions, libnetwork.OptionExtraHost(aliasList, child.NetworkSettings.Networks["bridge"].IPAddress))
  479. cEndpoint, _ := child.getEndpointInNetwork(n)
  480. if cEndpoint != nil && cEndpoint.ID() != "" {
  481. childEndpoints = append(childEndpoints, cEndpoint.ID())
  482. }
  483. }
  484. bridgeSettings := container.NetworkSettings.Networks["bridge"]
  485. refs := container.daemon.containerGraph().RefPaths(container.ID)
  486. for _, ref := range refs {
  487. if ref.ParentID == "0" {
  488. continue
  489. }
  490. c, err := container.daemon.Get(ref.ParentID)
  491. if err != nil {
  492. logrus.Error(err)
  493. }
  494. if c != nil && !container.daemon.configStore.DisableBridge && container.hostConfig.NetworkMode.IsPrivate() {
  495. logrus.Debugf("Update /etc/hosts of %s for alias %s with ip %s", c.ID, ref.Name, bridgeSettings.IPAddress)
  496. sboxOptions = append(sboxOptions, libnetwork.OptionParentUpdate(c.ID, ref.Name, bridgeSettings.IPAddress))
  497. if ep.ID() != "" {
  498. parentEndpoints = append(parentEndpoints, ep.ID())
  499. }
  500. }
  501. }
  502. linkOptions := options.Generic{
  503. netlabel.GenericData: options.Generic{
  504. "ParentEndpoints": parentEndpoints,
  505. "ChildEndpoints": childEndpoints,
  506. },
  507. }
  508. sboxOptions = append(sboxOptions, libnetwork.OptionGeneric(linkOptions))
  509. return sboxOptions, nil
  510. }
  511. func isLinkable(child *Container) bool {
  512. // A container is linkable only if it belongs to the default network
  513. _, ok := child.NetworkSettings.Networks["bridge"]
  514. return ok
  515. }
  516. func (container *Container) getEndpointInNetwork(n libnetwork.Network) (libnetwork.Endpoint, error) {
  517. endpointName := strings.TrimPrefix(container.Name, "/")
  518. return n.EndpointByName(endpointName)
  519. }
  520. func (container *Container) buildPortMapInfo(ep libnetwork.Endpoint, networkSettings *network.Settings) (*network.Settings, error) {
  521. if ep == nil {
  522. return nil, derr.ErrorCodeEmptyEndpoint
  523. }
  524. if networkSettings == nil {
  525. return nil, derr.ErrorCodeEmptyNetwork
  526. }
  527. driverInfo, err := ep.DriverInfo()
  528. if err != nil {
  529. return nil, err
  530. }
  531. if driverInfo == nil {
  532. // It is not an error for epInfo to be nil
  533. return networkSettings, nil
  534. }
  535. networkSettings.Ports = nat.PortMap{}
  536. if expData, ok := driverInfo[netlabel.ExposedPorts]; ok {
  537. if exposedPorts, ok := expData.([]types.TransportPort); ok {
  538. for _, tp := range exposedPorts {
  539. natPort, err := nat.NewPort(tp.Proto.String(), strconv.Itoa(int(tp.Port)))
  540. if err != nil {
  541. return nil, derr.ErrorCodeParsingPort.WithArgs(tp.Port, err)
  542. }
  543. networkSettings.Ports[natPort] = nil
  544. }
  545. }
  546. }
  547. mapData, ok := driverInfo[netlabel.PortMap]
  548. if !ok {
  549. return networkSettings, nil
  550. }
  551. if portMapping, ok := mapData.([]types.PortBinding); ok {
  552. for _, pp := range portMapping {
  553. natPort, err := nat.NewPort(pp.Proto.String(), strconv.Itoa(int(pp.Port)))
  554. if err != nil {
  555. return nil, err
  556. }
  557. natBndg := nat.PortBinding{HostIP: pp.HostIP.String(), HostPort: strconv.Itoa(int(pp.HostPort))}
  558. networkSettings.Ports[natPort] = append(networkSettings.Ports[natPort], natBndg)
  559. }
  560. }
  561. return networkSettings, nil
  562. }
  563. func (container *Container) buildEndpointInfo(n libnetwork.Network, ep libnetwork.Endpoint, networkSettings *network.Settings) (*network.Settings, error) {
  564. if ep == nil {
  565. return nil, derr.ErrorCodeEmptyEndpoint
  566. }
  567. if networkSettings == nil {
  568. return nil, derr.ErrorCodeEmptyNetwork
  569. }
  570. epInfo := ep.Info()
  571. if epInfo == nil {
  572. // It is not an error to get an empty endpoint info
  573. return networkSettings, nil
  574. }
  575. if _, ok := networkSettings.Networks[n.Name()]; !ok {
  576. networkSettings.Networks[n.Name()] = new(network.EndpointSettings)
  577. }
  578. networkSettings.Networks[n.Name()].EndpointID = ep.ID()
  579. iface := epInfo.Iface()
  580. if iface == nil {
  581. return networkSettings, nil
  582. }
  583. if iface.Address() != nil {
  584. ones, _ := iface.Address().Mask.Size()
  585. networkSettings.Networks[n.Name()].IPAddress = iface.Address().IP.String()
  586. networkSettings.Networks[n.Name()].IPPrefixLen = ones
  587. }
  588. if iface.AddressIPv6() != nil && iface.AddressIPv6().IP.To16() != nil {
  589. onesv6, _ := iface.AddressIPv6().Mask.Size()
  590. networkSettings.Networks[n.Name()].GlobalIPv6Address = iface.AddressIPv6().IP.String()
  591. networkSettings.Networks[n.Name()].GlobalIPv6PrefixLen = onesv6
  592. }
  593. driverInfo, err := ep.DriverInfo()
  594. if err != nil {
  595. return nil, err
  596. }
  597. if driverInfo == nil {
  598. // It is not an error for epInfo to be nil
  599. return networkSettings, nil
  600. }
  601. if mac, ok := driverInfo[netlabel.MacAddress]; ok {
  602. networkSettings.Networks[n.Name()].MacAddress = mac.(net.HardwareAddr).String()
  603. }
  604. return networkSettings, nil
  605. }
  606. func (container *Container) updateJoinInfo(n libnetwork.Network, ep libnetwork.Endpoint) error {
  607. epInfo := ep.Info()
  608. if epInfo == nil {
  609. // It is not an error to get an empty endpoint info
  610. return nil
  611. }
  612. if epInfo.Gateway() != nil {
  613. container.NetworkSettings.Networks[n.Name()].Gateway = epInfo.Gateway().String()
  614. }
  615. if epInfo.GatewayIPv6().To16() != nil {
  616. container.NetworkSettings.Networks[n.Name()].IPv6Gateway = epInfo.GatewayIPv6().String()
  617. }
  618. return nil
  619. }
  620. func (container *Container) updateNetworkSettings(n libnetwork.Network) error {
  621. if container.NetworkSettings == nil {
  622. container.NetworkSettings = &network.Settings{Networks: make(map[string]*network.EndpointSettings)}
  623. }
  624. for s := range container.NetworkSettings.Networks {
  625. sn, err := container.daemon.FindNetwork(s)
  626. if err != nil {
  627. continue
  628. }
  629. if sn.Name() == n.Name() {
  630. // Avoid duplicate config
  631. return nil
  632. }
  633. if !runconfig.NetworkMode(sn.Type()).IsPrivate() ||
  634. !runconfig.NetworkMode(n.Type()).IsPrivate() {
  635. return runconfig.ErrConflictSharedNetwork
  636. }
  637. if runconfig.NetworkMode(sn.Name()).IsNone() ||
  638. runconfig.NetworkMode(n.Name()).IsNone() {
  639. return runconfig.ErrConflictNoNetwork
  640. }
  641. }
  642. container.NetworkSettings.Networks[n.Name()] = new(network.EndpointSettings)
  643. return nil
  644. }
  645. func (container *Container) updateEndpointNetworkSettings(n libnetwork.Network, ep libnetwork.Endpoint) error {
  646. networkSettings, err := container.buildPortMapInfo(ep, container.NetworkSettings)
  647. if err != nil {
  648. return err
  649. }
  650. networkSettings, err = container.buildEndpointInfo(n, ep, networkSettings)
  651. if err != nil {
  652. return err
  653. }
  654. if container.hostConfig.NetworkMode == runconfig.NetworkMode("bridge") {
  655. networkSettings.Bridge = container.daemon.configStore.Bridge.Iface
  656. }
  657. return nil
  658. }
  659. func (container *Container) updateSandboxNetworkSettings(sb libnetwork.Sandbox) error {
  660. container.NetworkSettings.SandboxID = sb.ID()
  661. container.NetworkSettings.SandboxKey = sb.Key()
  662. return nil
  663. }
  664. // UpdateNetwork is used to update the container's network (e.g. when linked containers
  665. // get removed/unlinked).
  666. func (container *Container) updateNetwork() error {
  667. ctrl := container.daemon.netController
  668. sid := container.NetworkSettings.SandboxID
  669. sb, err := ctrl.SandboxByID(sid)
  670. if err != nil {
  671. return derr.ErrorCodeNoSandbox.WithArgs(sid, err)
  672. }
  673. // Find if container is connected to the default bridge network
  674. var n libnetwork.Network
  675. for name := range container.NetworkSettings.Networks {
  676. sn, err := container.daemon.FindNetwork(name)
  677. if err != nil {
  678. continue
  679. }
  680. if sn.Name() == "bridge" {
  681. n = sn
  682. break
  683. }
  684. }
  685. if n == nil {
  686. // Not connected to the default bridge network; Nothing to do
  687. return nil
  688. }
  689. options, err := container.buildSandboxOptions(n)
  690. if err != nil {
  691. return derr.ErrorCodeNetworkUpdate.WithArgs(err)
  692. }
  693. if err := sb.Refresh(options...); err != nil {
  694. return derr.ErrorCodeNetworkRefresh.WithArgs(sid, err)
  695. }
  696. return nil
  697. }
  698. func (container *Container) buildCreateEndpointOptions(n libnetwork.Network) ([]libnetwork.EndpointOption, error) {
  699. var (
  700. portSpecs = make(nat.PortSet)
  701. bindings = make(nat.PortMap)
  702. pbList []types.PortBinding
  703. exposeList []types.TransportPort
  704. createOptions []libnetwork.EndpointOption
  705. )
  706. if container.Config.ExposedPorts != nil {
  707. portSpecs = container.Config.ExposedPorts
  708. }
  709. if container.hostConfig.PortBindings != nil {
  710. for p, b := range container.hostConfig.PortBindings {
  711. bindings[p] = []nat.PortBinding{}
  712. for _, bb := range b {
  713. bindings[p] = append(bindings[p], nat.PortBinding{
  714. HostIP: bb.HostIP,
  715. HostPort: bb.HostPort,
  716. })
  717. }
  718. }
  719. }
  720. ports := make([]nat.Port, len(portSpecs))
  721. var i int
  722. for p := range portSpecs {
  723. ports[i] = p
  724. i++
  725. }
  726. nat.SortPortMap(ports, bindings)
  727. for _, port := range ports {
  728. expose := types.TransportPort{}
  729. expose.Proto = types.ParseProtocol(port.Proto())
  730. expose.Port = uint16(port.Int())
  731. exposeList = append(exposeList, expose)
  732. pb := types.PortBinding{Port: expose.Port, Proto: expose.Proto}
  733. binding := bindings[port]
  734. for i := 0; i < len(binding); i++ {
  735. pbCopy := pb.GetCopy()
  736. newP, err := nat.NewPort(nat.SplitProtoPort(binding[i].HostPort))
  737. var portStart, portEnd int
  738. if err == nil {
  739. portStart, portEnd, err = newP.Range()
  740. }
  741. if err != nil {
  742. return nil, derr.ErrorCodeHostPort.WithArgs(binding[i].HostPort, err)
  743. }
  744. pbCopy.HostPort = uint16(portStart)
  745. pbCopy.HostPortEnd = uint16(portEnd)
  746. pbCopy.HostIP = net.ParseIP(binding[i].HostIP)
  747. pbList = append(pbList, pbCopy)
  748. }
  749. if container.hostConfig.PublishAllPorts && len(binding) == 0 {
  750. pbList = append(pbList, pb)
  751. }
  752. }
  753. createOptions = append(createOptions,
  754. libnetwork.CreateOptionPortMapping(pbList),
  755. libnetwork.CreateOptionExposedPorts(exposeList))
  756. if container.Config.MacAddress != "" {
  757. mac, err := net.ParseMAC(container.Config.MacAddress)
  758. if err != nil {
  759. return nil, err
  760. }
  761. genericOption := options.Generic{
  762. netlabel.MacAddress: mac,
  763. }
  764. createOptions = append(createOptions, libnetwork.EndpointOptionGeneric(genericOption))
  765. }
  766. if n.Name() == "bridge" || container.NetworkSettings.IsAnonymousEndpoint {
  767. createOptions = append(createOptions, libnetwork.CreateOptionAnonymous())
  768. }
  769. return createOptions, nil
  770. }
  771. func (container *Container) allocateNetwork() error {
  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. // ConnectToNetwork connects a container to a netork
  795. func (container *Container) ConnectToNetwork(idOrName string) error {
  796. if !container.Running {
  797. return derr.ErrorCodeNotRunning.WithArgs(container.ID)
  798. }
  799. return container.connectToNetwork(idOrName, true)
  800. }
  801. func (container *Container) connectToNetwork(idOrName string, updateSettings bool) error {
  802. var err error
  803. if container.hostConfig.NetworkMode.IsContainer() {
  804. return runconfig.ErrConflictSharedNetwork
  805. }
  806. if runconfig.NetworkMode(idOrName).IsBridge() &&
  807. container.daemon.configStore.DisableBridge {
  808. container.Config.NetworkDisabled = true
  809. return nil
  810. }
  811. controller := container.daemon.netController
  812. n, err := container.daemon.FindNetwork(idOrName)
  813. if err != nil {
  814. return err
  815. }
  816. if updateSettings {
  817. if err := container.updateNetworkSettings(n); err != nil {
  818. return err
  819. }
  820. }
  821. ep, err := container.getEndpointInNetwork(n)
  822. if err == nil {
  823. return fmt.Errorf("container already connected to network %s", idOrName)
  824. }
  825. if _, ok := err.(libnetwork.ErrNoSuchEndpoint); !ok {
  826. return err
  827. }
  828. createOptions, err := container.buildCreateEndpointOptions(n)
  829. if err != nil {
  830. return err
  831. }
  832. endpointName := strings.TrimPrefix(container.Name, "/")
  833. ep, err = n.CreateEndpoint(endpointName, createOptions...)
  834. if err != nil {
  835. return err
  836. }
  837. defer func() {
  838. if err != nil {
  839. if e := ep.Delete(); e != nil {
  840. logrus.Warnf("Could not rollback container connection to network %s", idOrName)
  841. }
  842. }
  843. }()
  844. if err := container.updateEndpointNetworkSettings(n, ep); err != nil {
  845. return err
  846. }
  847. var sb libnetwork.Sandbox
  848. controller.WalkSandboxes(func(s libnetwork.Sandbox) bool {
  849. if s.ContainerID() == container.ID {
  850. sb = s
  851. return true
  852. }
  853. return false
  854. })
  855. if sb == nil {
  856. options, err := container.buildSandboxOptions(n)
  857. if err != nil {
  858. return err
  859. }
  860. sb, err = controller.NewSandbox(container.ID, options...)
  861. if err != nil {
  862. return err
  863. }
  864. container.updateSandboxNetworkSettings(sb)
  865. }
  866. if err := ep.Join(sb); err != nil {
  867. return err
  868. }
  869. if err := container.updateJoinInfo(n, ep); err != nil {
  870. return derr.ErrorCodeJoinInfo.WithArgs(err)
  871. }
  872. return nil
  873. }
  874. func (container *Container) initializeNetworking() error {
  875. var err error
  876. if container.hostConfig.NetworkMode.IsContainer() {
  877. // we need to get the hosts files from the container to join
  878. nc, err := container.getNetworkedContainer()
  879. if err != nil {
  880. return err
  881. }
  882. container.HostnamePath = nc.HostnamePath
  883. container.HostsPath = nc.HostsPath
  884. container.ResolvConfPath = nc.ResolvConfPath
  885. container.Config.Hostname = nc.Config.Hostname
  886. container.Config.Domainname = nc.Config.Domainname
  887. return nil
  888. }
  889. if container.hostConfig.NetworkMode.IsHost() {
  890. container.Config.Hostname, err = os.Hostname()
  891. if err != nil {
  892. return err
  893. }
  894. parts := strings.SplitN(container.Config.Hostname, ".", 2)
  895. if len(parts) > 1 {
  896. container.Config.Hostname = parts[0]
  897. container.Config.Domainname = parts[1]
  898. }
  899. }
  900. if err := container.allocateNetwork(); err != nil {
  901. return err
  902. }
  903. return container.buildHostnameFile()
  904. }
  905. // called from the libcontainer pre-start hook to set the network
  906. // namespace configuration linkage to the libnetwork "sandbox" entity
  907. func (container *Container) setNetworkNamespaceKey(pid int) error {
  908. path := fmt.Sprintf("/proc/%d/ns/net", pid)
  909. var sandbox libnetwork.Sandbox
  910. search := libnetwork.SandboxContainerWalker(&sandbox, container.ID)
  911. container.daemon.netController.WalkSandboxes(search)
  912. if sandbox == nil {
  913. return derr.ErrorCodeNoSandbox.WithArgs(container.ID)
  914. }
  915. return sandbox.SetKey(path)
  916. }
  917. func (container *Container) getIpcContainer() (*Container, error) {
  918. containerID := container.hostConfig.IpcMode.Container()
  919. c, err := container.daemon.Get(containerID)
  920. if err != nil {
  921. return nil, err
  922. }
  923. if !c.IsRunning() {
  924. return nil, derr.ErrorCodeIPCRunning
  925. }
  926. return c, nil
  927. }
  928. func (container *Container) setupWorkingDirectory() error {
  929. if container.Config.WorkingDir != "" {
  930. container.Config.WorkingDir = filepath.Clean(container.Config.WorkingDir)
  931. pth, err := container.GetResourcePath(container.Config.WorkingDir)
  932. if err != nil {
  933. return err
  934. }
  935. pthInfo, err := os.Stat(pth)
  936. if err != nil {
  937. if !os.IsNotExist(err) {
  938. return err
  939. }
  940. if err := system.MkdirAll(pth, 0755); err != nil {
  941. return err
  942. }
  943. }
  944. if pthInfo != nil && !pthInfo.IsDir() {
  945. return derr.ErrorCodeNotADir.WithArgs(container.Config.WorkingDir)
  946. }
  947. }
  948. return nil
  949. }
  950. func (container *Container) getNetworkedContainer() (*Container, error) {
  951. parts := strings.SplitN(string(container.hostConfig.NetworkMode), ":", 2)
  952. switch parts[0] {
  953. case "container":
  954. if len(parts) != 2 {
  955. return nil, derr.ErrorCodeParseContainer
  956. }
  957. nc, err := container.daemon.Get(parts[1])
  958. if err != nil {
  959. return nil, err
  960. }
  961. if container == nc {
  962. return nil, derr.ErrorCodeJoinSelf
  963. }
  964. if !nc.IsRunning() {
  965. return nil, derr.ErrorCodeJoinRunning.WithArgs(parts[1])
  966. }
  967. return nc, nil
  968. default:
  969. return nil, derr.ErrorCodeModeNotContainer
  970. }
  971. }
  972. func (container *Container) releaseNetwork() {
  973. if container.hostConfig.NetworkMode.IsContainer() || container.Config.NetworkDisabled {
  974. return
  975. }
  976. sid := container.NetworkSettings.SandboxID
  977. networks := container.NetworkSettings.Networks
  978. for n := range networks {
  979. networks[n] = &network.EndpointSettings{}
  980. }
  981. container.NetworkSettings = &network.Settings{Networks: networks}
  982. if sid == "" || len(networks) == 0 {
  983. return
  984. }
  985. sb, err := container.daemon.netController.SandboxByID(sid)
  986. if err != nil {
  987. logrus.Errorf("error locating sandbox id %s: %v", sid, err)
  988. return
  989. }
  990. if err := sb.Delete(); err != nil {
  991. logrus.Errorf("Error deleting sandbox id %s for container %s: %v", sid, container.ID, err)
  992. }
  993. }
  994. // DisconnectFromNetwork disconnects a container from a network
  995. func (container *Container) DisconnectFromNetwork(n libnetwork.Network) error {
  996. if !container.Running {
  997. return derr.ErrorCodeNotRunning.WithArgs(container.ID)
  998. }
  999. return container.disconnectFromNetwork(n)
  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. if sb := current.Info().Sandbox(); sb != nil {
  1008. if sb.ContainerID() == container.ID {
  1009. ep = current
  1010. sbox = sb
  1011. return true
  1012. }
  1013. }
  1014. return false
  1015. }
  1016. n.WalkEndpoints(s)
  1017. if ep == nil {
  1018. return fmt.Errorf("container %s is not connected to the network", container.ID)
  1019. }
  1020. if err := ep.Leave(sbox); err != nil {
  1021. return fmt.Errorf("container %s failed to leave network %s: %v", container.ID, n.Name(), err)
  1022. }
  1023. if err := ep.Delete(); err != nil {
  1024. return fmt.Errorf("endpoint delete failed for container %s on network %s: %v", container.ID, n.Name(), err)
  1025. }
  1026. delete(container.NetworkSettings.Networks, n.Name())
  1027. return nil
  1028. }
  1029. // appendNetworkMounts appends any network mounts to the array of mount points passed in
  1030. func appendNetworkMounts(container *Container, volumeMounts []volume.MountPoint) ([]volume.MountPoint, error) {
  1031. for _, mnt := range container.networkMounts() {
  1032. dest, err := container.GetResourcePath(mnt.Destination)
  1033. if err != nil {
  1034. return nil, err
  1035. }
  1036. volumeMounts = append(volumeMounts, volume.MountPoint{Destination: dest})
  1037. }
  1038. return volumeMounts, nil
  1039. }
  1040. func (container *Container) networkMounts() []execdriver.Mount {
  1041. var mounts []execdriver.Mount
  1042. shared := container.hostConfig.NetworkMode.IsContainer()
  1043. if container.ResolvConfPath != "" {
  1044. if _, err := os.Stat(container.ResolvConfPath); err != nil {
  1045. logrus.Warnf("ResolvConfPath set to %q, but can't stat this filename (err = %v); skipping", container.ResolvConfPath, err)
  1046. } else {
  1047. label.Relabel(container.ResolvConfPath, container.MountLabel, shared)
  1048. writable := !container.hostConfig.ReadonlyRootfs
  1049. if m, exists := container.MountPoints["/etc/resolv.conf"]; exists {
  1050. writable = m.RW
  1051. }
  1052. mounts = append(mounts, execdriver.Mount{
  1053. Source: container.ResolvConfPath,
  1054. Destination: "/etc/resolv.conf",
  1055. Writable: writable,
  1056. Private: true,
  1057. })
  1058. }
  1059. }
  1060. if container.HostnamePath != "" {
  1061. if _, err := os.Stat(container.HostnamePath); err != nil {
  1062. logrus.Warnf("HostnamePath set to %q, but can't stat this filename (err = %v); skipping", container.HostnamePath, err)
  1063. } else {
  1064. label.Relabel(container.HostnamePath, container.MountLabel, shared)
  1065. writable := !container.hostConfig.ReadonlyRootfs
  1066. if m, exists := container.MountPoints["/etc/hostname"]; exists {
  1067. writable = m.RW
  1068. }
  1069. mounts = append(mounts, execdriver.Mount{
  1070. Source: container.HostnamePath,
  1071. Destination: "/etc/hostname",
  1072. Writable: writable,
  1073. Private: true,
  1074. })
  1075. }
  1076. }
  1077. if container.HostsPath != "" {
  1078. if _, err := os.Stat(container.HostsPath); err != nil {
  1079. logrus.Warnf("HostsPath set to %q, but can't stat this filename (err = %v); skipping", container.HostsPath, err)
  1080. } else {
  1081. label.Relabel(container.HostsPath, container.MountLabel, shared)
  1082. writable := !container.hostConfig.ReadonlyRootfs
  1083. if m, exists := container.MountPoints["/etc/hosts"]; exists {
  1084. writable = m.RW
  1085. }
  1086. mounts = append(mounts, execdriver.Mount{
  1087. Source: container.HostsPath,
  1088. Destination: "/etc/hosts",
  1089. Writable: writable,
  1090. Private: true,
  1091. })
  1092. }
  1093. }
  1094. return mounts
  1095. }
  1096. func (container *Container) copyImagePathContent(v volume.Volume, destination string) error {
  1097. rootfs, err := symlink.FollowSymlinkInScope(filepath.Join(container.basefs, destination), container.basefs)
  1098. if err != nil {
  1099. return err
  1100. }
  1101. if _, err = ioutil.ReadDir(rootfs); err != nil {
  1102. if os.IsNotExist(err) {
  1103. return nil
  1104. }
  1105. return err
  1106. }
  1107. path, err := v.Mount()
  1108. if err != nil {
  1109. return err
  1110. }
  1111. if err := copyExistingContents(rootfs, path); err != nil {
  1112. return err
  1113. }
  1114. return v.Unmount()
  1115. }
  1116. func (container *Container) shmPath() (string, error) {
  1117. return container.getRootResourcePath("shm")
  1118. }
  1119. func (container *Container) mqueuePath() (string, error) {
  1120. return container.getRootResourcePath("mqueue")
  1121. }
  1122. func (container *Container) hasMountFor(path string) bool {
  1123. _, exists := container.MountPoints[path]
  1124. return exists
  1125. }
  1126. func (container *Container) setupIpcDirs() error {
  1127. rootUID, rootGID := container.daemon.GetRemappedUIDGID()
  1128. if !container.hasMountFor("/dev/shm") {
  1129. shmPath, err := container.shmPath()
  1130. if err != nil {
  1131. return err
  1132. }
  1133. if err := idtools.MkdirAllAs(shmPath, 0700, rootUID, rootGID); err != nil {
  1134. return err
  1135. }
  1136. 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 {
  1137. return fmt.Errorf("mounting shm tmpfs: %s", err)
  1138. }
  1139. if err := os.Chown(shmPath, rootUID, rootGID); err != nil {
  1140. return err
  1141. }
  1142. }
  1143. if !container.hasMountFor("/dev/mqueue") {
  1144. mqueuePath, err := container.mqueuePath()
  1145. if err != nil {
  1146. return err
  1147. }
  1148. if err := idtools.MkdirAllAs(mqueuePath, 0700, rootUID, rootGID); err != nil {
  1149. return err
  1150. }
  1151. if err := syscall.Mount("mqueue", mqueuePath, "mqueue", uintptr(syscall.MS_NOEXEC|syscall.MS_NOSUID|syscall.MS_NODEV), ""); err != nil {
  1152. return fmt.Errorf("mounting mqueue mqueue : %s", err)
  1153. }
  1154. if err := os.Chown(mqueuePath, rootUID, rootGID); err != nil {
  1155. return err
  1156. }
  1157. }
  1158. return nil
  1159. }
  1160. func (container *Container) unmountIpcMounts() error {
  1161. if container.hostConfig.IpcMode.IsContainer() || container.hostConfig.IpcMode.IsHost() {
  1162. return nil
  1163. }
  1164. var errors []string
  1165. if !container.hasMountFor("/dev/shm") {
  1166. shmPath, err := container.shmPath()
  1167. if err != nil {
  1168. logrus.Error(err)
  1169. errors = append(errors, err.Error())
  1170. } else {
  1171. if err := detachMounted(shmPath); err != nil {
  1172. logrus.Errorf("failed to umount %s: %v", shmPath, err)
  1173. errors = append(errors, err.Error())
  1174. }
  1175. }
  1176. }
  1177. if !container.hasMountFor("/dev/mqueue") {
  1178. mqueuePath, err := container.mqueuePath()
  1179. if err != nil {
  1180. logrus.Error(err)
  1181. errors = append(errors, err.Error())
  1182. } else {
  1183. if err := detachMounted(mqueuePath); err != nil {
  1184. logrus.Errorf("failed to umount %s: %v", mqueuePath, err)
  1185. errors = append(errors, err.Error())
  1186. }
  1187. }
  1188. }
  1189. if len(errors) > 0 {
  1190. return fmt.Errorf("failed to cleanup ipc mounts:\n%v", strings.Join(errors, "\n"))
  1191. }
  1192. return nil
  1193. }
  1194. func (container *Container) ipcMounts() []execdriver.Mount {
  1195. var mounts []execdriver.Mount
  1196. if !container.hasMountFor("/dev/shm") {
  1197. label.SetFileLabel(container.ShmPath, container.MountLabel)
  1198. mounts = append(mounts, execdriver.Mount{
  1199. Source: container.ShmPath,
  1200. Destination: "/dev/shm",
  1201. Writable: true,
  1202. Private: true,
  1203. })
  1204. }
  1205. if !container.hasMountFor("/dev/mqueue") {
  1206. label.SetFileLabel(container.MqueuePath, container.MountLabel)
  1207. mounts = append(mounts, execdriver.Mount{
  1208. Source: container.MqueuePath,
  1209. Destination: "/dev/mqueue",
  1210. Writable: true,
  1211. Private: true,
  1212. })
  1213. }
  1214. return mounts
  1215. }
  1216. func detachMounted(path string) error {
  1217. return syscall.Unmount(path, syscall.MNT_DETACH)
  1218. }