container_unix.go 41 KB

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