container_unix.go 40 KB

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