container_unix.go 40 KB

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