container_unix.go 41 KB

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