container_unix.go 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446
  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. if networkSettings.Ports == nil {
  527. networkSettings.Ports = nat.PortMap{}
  528. }
  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. if !container.hostConfig.NetworkMode.IsHost() && runconfig.NetworkMode(n.Type()).IsHost() {
  613. return runconfig.ErrConflictHostNetwork
  614. }
  615. for s := range container.NetworkSettings.Networks {
  616. sn, err := daemon.FindNetwork(s)
  617. if err != nil {
  618. continue
  619. }
  620. if sn.Name() == n.Name() {
  621. // Avoid duplicate config
  622. return nil
  623. }
  624. if !runconfig.NetworkMode(sn.Type()).IsPrivate() ||
  625. !runconfig.NetworkMode(n.Type()).IsPrivate() {
  626. return runconfig.ErrConflictSharedNetwork
  627. }
  628. if runconfig.NetworkMode(sn.Name()).IsNone() ||
  629. runconfig.NetworkMode(n.Name()).IsNone() {
  630. return runconfig.ErrConflictNoNetwork
  631. }
  632. }
  633. container.NetworkSettings.Networks[n.Name()] = new(network.EndpointSettings)
  634. return nil
  635. }
  636. func (daemon *Daemon) updateEndpointNetworkSettings(container *Container, n libnetwork.Network, ep libnetwork.Endpoint) error {
  637. networkSettings, err := container.buildEndpointInfo(n, ep, container.NetworkSettings)
  638. if err != nil {
  639. return err
  640. }
  641. if container.hostConfig.NetworkMode == runconfig.NetworkMode("bridge") {
  642. networkSettings.Bridge = daemon.configStore.Bridge.Iface
  643. }
  644. return nil
  645. }
  646. func (container *Container) updateSandboxNetworkSettings(sb libnetwork.Sandbox) error {
  647. container.NetworkSettings.SandboxID = sb.ID()
  648. container.NetworkSettings.SandboxKey = sb.Key()
  649. return nil
  650. }
  651. // UpdateNetwork is used to update the container's network (e.g. when linked containers
  652. // get removed/unlinked).
  653. func (daemon *Daemon) updateNetwork(container *Container) error {
  654. ctrl := daemon.netController
  655. sid := container.NetworkSettings.SandboxID
  656. sb, err := ctrl.SandboxByID(sid)
  657. if err != nil {
  658. return derr.ErrorCodeNoSandbox.WithArgs(sid, err)
  659. }
  660. // Find if container is connected to the default bridge network
  661. var n libnetwork.Network
  662. for name := range container.NetworkSettings.Networks {
  663. sn, err := daemon.FindNetwork(name)
  664. if err != nil {
  665. continue
  666. }
  667. if sn.Name() == "bridge" {
  668. n = sn
  669. break
  670. }
  671. }
  672. if n == nil {
  673. // Not connected to the default bridge network; Nothing to do
  674. return nil
  675. }
  676. options, err := daemon.buildSandboxOptions(container, n)
  677. if err != nil {
  678. return derr.ErrorCodeNetworkUpdate.WithArgs(err)
  679. }
  680. if err := sb.Refresh(options...); err != nil {
  681. return derr.ErrorCodeNetworkRefresh.WithArgs(sid, err)
  682. }
  683. return nil
  684. }
  685. func (container *Container) buildCreateEndpointOptions(n libnetwork.Network) ([]libnetwork.EndpointOption, error) {
  686. var (
  687. portSpecs = make(nat.PortSet)
  688. bindings = make(nat.PortMap)
  689. pbList []types.PortBinding
  690. exposeList []types.TransportPort
  691. createOptions []libnetwork.EndpointOption
  692. )
  693. if n.Name() == "bridge" || container.NetworkSettings.IsAnonymousEndpoint {
  694. createOptions = append(createOptions, libnetwork.CreateOptionAnonymous())
  695. }
  696. // Other configs are applicable only for the endpoint in the network
  697. // to which container was connected to on docker run.
  698. if n.Name() != container.hostConfig.NetworkMode.NetworkName() &&
  699. !(n.Name() == "bridge" && container.hostConfig.NetworkMode.IsDefault()) {
  700. return createOptions, nil
  701. }
  702. if container.Config.ExposedPorts != nil {
  703. portSpecs = container.Config.ExposedPorts
  704. }
  705. if container.hostConfig.PortBindings != nil {
  706. for p, b := range container.hostConfig.PortBindings {
  707. bindings[p] = []nat.PortBinding{}
  708. for _, bb := range b {
  709. bindings[p] = append(bindings[p], nat.PortBinding{
  710. HostIP: bb.HostIP,
  711. HostPort: bb.HostPort,
  712. })
  713. }
  714. }
  715. }
  716. ports := make([]nat.Port, len(portSpecs))
  717. var i int
  718. for p := range portSpecs {
  719. ports[i] = p
  720. i++
  721. }
  722. nat.SortPortMap(ports, bindings)
  723. for _, port := range ports {
  724. expose := types.TransportPort{}
  725. expose.Proto = types.ParseProtocol(port.Proto())
  726. expose.Port = uint16(port.Int())
  727. exposeList = append(exposeList, expose)
  728. pb := types.PortBinding{Port: expose.Port, Proto: expose.Proto}
  729. binding := bindings[port]
  730. for i := 0; i < len(binding); i++ {
  731. pbCopy := pb.GetCopy()
  732. newP, err := nat.NewPort(nat.SplitProtoPort(binding[i].HostPort))
  733. var portStart, portEnd int
  734. if err == nil {
  735. portStart, portEnd, err = newP.Range()
  736. }
  737. if err != nil {
  738. return nil, derr.ErrorCodeHostPort.WithArgs(binding[i].HostPort, err)
  739. }
  740. pbCopy.HostPort = uint16(portStart)
  741. pbCopy.HostPortEnd = uint16(portEnd)
  742. pbCopy.HostIP = net.ParseIP(binding[i].HostIP)
  743. pbList = append(pbList, pbCopy)
  744. }
  745. if container.hostConfig.PublishAllPorts && len(binding) == 0 {
  746. pbList = append(pbList, pb)
  747. }
  748. }
  749. createOptions = append(createOptions,
  750. libnetwork.CreateOptionPortMapping(pbList),
  751. libnetwork.CreateOptionExposedPorts(exposeList))
  752. if container.Config.MacAddress != "" {
  753. mac, err := net.ParseMAC(container.Config.MacAddress)
  754. if err != nil {
  755. return nil, err
  756. }
  757. genericOption := options.Generic{
  758. netlabel.MacAddress: mac,
  759. }
  760. createOptions = append(createOptions, libnetwork.EndpointOptionGeneric(genericOption))
  761. }
  762. return createOptions, nil
  763. }
  764. func (daemon *Daemon) allocateNetwork(container *Container) error {
  765. controller := daemon.netController
  766. // Cleanup any stale sandbox left over due to ungraceful daemon shutdown
  767. if err := controller.SandboxDestroy(container.ID); err != nil {
  768. logrus.Errorf("failed to cleanup up stale network sandbox for container %s", container.ID)
  769. }
  770. updateSettings := false
  771. if len(container.NetworkSettings.Networks) == 0 {
  772. mode := container.hostConfig.NetworkMode
  773. if container.Config.NetworkDisabled || mode.IsContainer() {
  774. return nil
  775. }
  776. networkName := mode.NetworkName()
  777. if mode.IsDefault() {
  778. networkName = controller.Config().Daemon.DefaultNetwork
  779. }
  780. if mode.IsUserDefined() {
  781. n, err := daemon.FindNetwork(networkName)
  782. if err != nil {
  783. return err
  784. }
  785. networkName = n.Name()
  786. }
  787. container.NetworkSettings.Networks = make(map[string]*network.EndpointSettings)
  788. container.NetworkSettings.Networks[networkName] = new(network.EndpointSettings)
  789. updateSettings = true
  790. }
  791. for n := range container.NetworkSettings.Networks {
  792. if err := daemon.connectToNetwork(container, n, updateSettings); err != nil {
  793. return err
  794. }
  795. }
  796. return container.writeHostConfig()
  797. }
  798. func (daemon *Daemon) getNetworkSandbox(container *Container) libnetwork.Sandbox {
  799. var sb libnetwork.Sandbox
  800. daemon.netController.WalkSandboxes(func(s libnetwork.Sandbox) bool {
  801. if s.ContainerID() == container.ID {
  802. sb = s
  803. return true
  804. }
  805. return false
  806. })
  807. return sb
  808. }
  809. // ConnectToNetwork connects a container to a network
  810. func (daemon *Daemon) ConnectToNetwork(container *Container, idOrName string) error {
  811. if !container.Running {
  812. return derr.ErrorCodeNotRunning.WithArgs(container.ID)
  813. }
  814. if err := daemon.connectToNetwork(container, idOrName, true); err != nil {
  815. return err
  816. }
  817. if err := container.toDiskLocking(); err != nil {
  818. return fmt.Errorf("Error saving container to disk: %v", err)
  819. }
  820. return nil
  821. }
  822. func (daemon *Daemon) connectToNetwork(container *Container, idOrName string, updateSettings bool) (err error) {
  823. if container.hostConfig.NetworkMode.IsContainer() {
  824. return runconfig.ErrConflictSharedNetwork
  825. }
  826. if runconfig.NetworkMode(idOrName).IsBridge() &&
  827. daemon.configStore.DisableBridge {
  828. container.Config.NetworkDisabled = true
  829. return nil
  830. }
  831. controller := daemon.netController
  832. n, err := daemon.FindNetwork(idOrName)
  833. if err != nil {
  834. return err
  835. }
  836. if updateSettings {
  837. if err := daemon.updateNetworkSettings(container, n); err != nil {
  838. return err
  839. }
  840. }
  841. ep, err := container.getEndpointInNetwork(n)
  842. if err == nil {
  843. return fmt.Errorf("container already connected to network %s", idOrName)
  844. }
  845. if _, ok := err.(libnetwork.ErrNoSuchEndpoint); !ok {
  846. return err
  847. }
  848. createOptions, err := container.buildCreateEndpointOptions(n)
  849. if err != nil {
  850. return err
  851. }
  852. endpointName := strings.TrimPrefix(container.Name, "/")
  853. ep, err = n.CreateEndpoint(endpointName, createOptions...)
  854. if err != nil {
  855. return err
  856. }
  857. defer func() {
  858. if err != nil {
  859. if e := ep.Delete(); e != nil {
  860. logrus.Warnf("Could not rollback container connection to network %s", idOrName)
  861. }
  862. }
  863. }()
  864. if err := daemon.updateEndpointNetworkSettings(container, n, ep); err != nil {
  865. return err
  866. }
  867. sb := daemon.getNetworkSandbox(container)
  868. if sb == nil {
  869. options, err := daemon.buildSandboxOptions(container, n)
  870. if err != nil {
  871. return err
  872. }
  873. sb, err = controller.NewSandbox(container.ID, options...)
  874. if err != nil {
  875. return err
  876. }
  877. container.updateSandboxNetworkSettings(sb)
  878. }
  879. if err := ep.Join(sb); err != nil {
  880. return err
  881. }
  882. if err := container.updateJoinInfo(n, ep); err != nil {
  883. return derr.ErrorCodeJoinInfo.WithArgs(err)
  884. }
  885. return nil
  886. }
  887. func (daemon *Daemon) initializeNetworking(container *Container) error {
  888. var err error
  889. if container.hostConfig.NetworkMode.IsContainer() {
  890. // we need to get the hosts files from the container to join
  891. nc, err := daemon.getNetworkedContainer(container.ID, container.hostConfig.NetworkMode.ConnectedContainer())
  892. if err != nil {
  893. return err
  894. }
  895. container.HostnamePath = nc.HostnamePath
  896. container.HostsPath = nc.HostsPath
  897. container.ResolvConfPath = nc.ResolvConfPath
  898. container.Config.Hostname = nc.Config.Hostname
  899. container.Config.Domainname = nc.Config.Domainname
  900. return nil
  901. }
  902. if container.hostConfig.NetworkMode.IsHost() {
  903. container.Config.Hostname, err = os.Hostname()
  904. if err != nil {
  905. return err
  906. }
  907. parts := strings.SplitN(container.Config.Hostname, ".", 2)
  908. if len(parts) > 1 {
  909. container.Config.Hostname = parts[0]
  910. container.Config.Domainname = parts[1]
  911. }
  912. }
  913. if err := daemon.allocateNetwork(container); err != nil {
  914. return err
  915. }
  916. return container.buildHostnameFile()
  917. }
  918. // called from the libcontainer pre-start hook to set the network
  919. // namespace configuration linkage to the libnetwork "sandbox" entity
  920. func (daemon *Daemon) setNetworkNamespaceKey(containerID string, pid int) error {
  921. path := fmt.Sprintf("/proc/%d/ns/net", pid)
  922. var sandbox libnetwork.Sandbox
  923. search := libnetwork.SandboxContainerWalker(&sandbox, containerID)
  924. daemon.netController.WalkSandboxes(search)
  925. if sandbox == nil {
  926. return derr.ErrorCodeNoSandbox.WithArgs(containerID, "no sandbox found")
  927. }
  928. return sandbox.SetKey(path)
  929. }
  930. func (daemon *Daemon) getIpcContainer(container *Container) (*Container, error) {
  931. containerID := container.hostConfig.IpcMode.Container()
  932. c, err := daemon.Get(containerID)
  933. if err != nil {
  934. return nil, err
  935. }
  936. if !c.IsRunning() {
  937. return nil, derr.ErrorCodeIPCRunning
  938. }
  939. return c, nil
  940. }
  941. func (container *Container) setupWorkingDirectory() error {
  942. if container.Config.WorkingDir == "" {
  943. return nil
  944. }
  945. container.Config.WorkingDir = filepath.Clean(container.Config.WorkingDir)
  946. pth, err := container.GetResourcePath(container.Config.WorkingDir)
  947. if err != nil {
  948. return err
  949. }
  950. pthInfo, err := os.Stat(pth)
  951. if err != nil {
  952. if !os.IsNotExist(err) {
  953. return err
  954. }
  955. if err := system.MkdirAll(pth, 0755); err != nil {
  956. return err
  957. }
  958. }
  959. if pthInfo != nil && !pthInfo.IsDir() {
  960. return derr.ErrorCodeNotADir.WithArgs(container.Config.WorkingDir)
  961. }
  962. return nil
  963. }
  964. func (daemon *Daemon) getNetworkedContainer(containerID, connectedContainerID string) (*Container, error) {
  965. nc, err := daemon.Get(connectedContainerID)
  966. if err != nil {
  967. return nil, err
  968. }
  969. if containerID == nc.ID {
  970. return nil, derr.ErrorCodeJoinSelf
  971. }
  972. if !nc.IsRunning() {
  973. return nil, derr.ErrorCodeJoinRunning.WithArgs(connectedContainerID)
  974. }
  975. return nc, nil
  976. }
  977. func (daemon *Daemon) releaseNetwork(container *Container) {
  978. if container.hostConfig.NetworkMode.IsContainer() || container.Config.NetworkDisabled {
  979. return
  980. }
  981. sid := container.NetworkSettings.SandboxID
  982. networks := container.NetworkSettings.Networks
  983. for n := range networks {
  984. networks[n] = &network.EndpointSettings{}
  985. }
  986. container.NetworkSettings = &network.Settings{Networks: networks}
  987. if sid == "" || len(networks) == 0 {
  988. return
  989. }
  990. sb, err := daemon.netController.SandboxByID(sid)
  991. if err != nil {
  992. logrus.Errorf("error locating sandbox id %s: %v", sid, err)
  993. return
  994. }
  995. if err := sb.Delete(); err != nil {
  996. logrus.Errorf("Error deleting sandbox id %s for container %s: %v", sid, container.ID, err)
  997. }
  998. }
  999. // DisconnectFromNetwork disconnects a container from a network
  1000. func (container *Container) DisconnectFromNetwork(n libnetwork.Network) error {
  1001. if !container.Running {
  1002. return derr.ErrorCodeNotRunning.WithArgs(container.ID)
  1003. }
  1004. if container.hostConfig.NetworkMode.IsHost() && runconfig.NetworkMode(n.Type()).IsHost() {
  1005. return runconfig.ErrConflictHostNetwork
  1006. }
  1007. if err := container.disconnectFromNetwork(n); err != nil {
  1008. return err
  1009. }
  1010. if err := container.toDiskLocking(); err != nil {
  1011. return fmt.Errorf("Error saving container to disk: %v", err)
  1012. }
  1013. return nil
  1014. }
  1015. func (container *Container) disconnectFromNetwork(n libnetwork.Network) error {
  1016. var (
  1017. ep libnetwork.Endpoint
  1018. sbox libnetwork.Sandbox
  1019. )
  1020. s := func(current libnetwork.Endpoint) bool {
  1021. epInfo := current.Info()
  1022. if epInfo == nil {
  1023. return false
  1024. }
  1025. if sb := epInfo.Sandbox(); sb != nil {
  1026. if sb.ContainerID() == container.ID {
  1027. ep = current
  1028. sbox = sb
  1029. return true
  1030. }
  1031. }
  1032. return false
  1033. }
  1034. n.WalkEndpoints(s)
  1035. if ep == nil {
  1036. return fmt.Errorf("container %s is not connected to the network", container.ID)
  1037. }
  1038. if err := ep.Leave(sbox); err != nil {
  1039. return fmt.Errorf("container %s failed to leave network %s: %v", container.ID, n.Name(), err)
  1040. }
  1041. if err := ep.Delete(); err != nil {
  1042. return fmt.Errorf("endpoint delete failed for container %s on network %s: %v", container.ID, n.Name(), err)
  1043. }
  1044. delete(container.NetworkSettings.Networks, n.Name())
  1045. return nil
  1046. }
  1047. // appendNetworkMounts appends any network mounts to the array of mount points passed in
  1048. func appendNetworkMounts(container *Container, volumeMounts []volume.MountPoint) ([]volume.MountPoint, error) {
  1049. for _, mnt := range container.networkMounts() {
  1050. dest, err := container.GetResourcePath(mnt.Destination)
  1051. if err != nil {
  1052. return nil, err
  1053. }
  1054. volumeMounts = append(volumeMounts, volume.MountPoint{Destination: dest})
  1055. }
  1056. return volumeMounts, nil
  1057. }
  1058. func (container *Container) networkMounts() []execdriver.Mount {
  1059. var mounts []execdriver.Mount
  1060. shared := container.hostConfig.NetworkMode.IsContainer()
  1061. if container.ResolvConfPath != "" {
  1062. if _, err := os.Stat(container.ResolvConfPath); err != nil {
  1063. logrus.Warnf("ResolvConfPath set to %q, but can't stat this filename (err = %v); skipping", container.ResolvConfPath, err)
  1064. } else {
  1065. label.Relabel(container.ResolvConfPath, container.MountLabel, shared)
  1066. writable := !container.hostConfig.ReadonlyRootfs
  1067. if m, exists := container.MountPoints["/etc/resolv.conf"]; exists {
  1068. writable = m.RW
  1069. }
  1070. mounts = append(mounts, execdriver.Mount{
  1071. Source: container.ResolvConfPath,
  1072. Destination: "/etc/resolv.conf",
  1073. Writable: writable,
  1074. Private: true,
  1075. })
  1076. }
  1077. }
  1078. if container.HostnamePath != "" {
  1079. if _, err := os.Stat(container.HostnamePath); err != nil {
  1080. logrus.Warnf("HostnamePath set to %q, but can't stat this filename (err = %v); skipping", container.HostnamePath, err)
  1081. } else {
  1082. label.Relabel(container.HostnamePath, container.MountLabel, shared)
  1083. writable := !container.hostConfig.ReadonlyRootfs
  1084. if m, exists := container.MountPoints["/etc/hostname"]; exists {
  1085. writable = m.RW
  1086. }
  1087. mounts = append(mounts, execdriver.Mount{
  1088. Source: container.HostnamePath,
  1089. Destination: "/etc/hostname",
  1090. Writable: writable,
  1091. Private: true,
  1092. })
  1093. }
  1094. }
  1095. if container.HostsPath != "" {
  1096. if _, err := os.Stat(container.HostsPath); err != nil {
  1097. logrus.Warnf("HostsPath set to %q, but can't stat this filename (err = %v); skipping", container.HostsPath, err)
  1098. } else {
  1099. label.Relabel(container.HostsPath, container.MountLabel, shared)
  1100. writable := !container.hostConfig.ReadonlyRootfs
  1101. if m, exists := container.MountPoints["/etc/hosts"]; exists {
  1102. writable = m.RW
  1103. }
  1104. mounts = append(mounts, execdriver.Mount{
  1105. Source: container.HostsPath,
  1106. Destination: "/etc/hosts",
  1107. Writable: writable,
  1108. Private: true,
  1109. })
  1110. }
  1111. }
  1112. return mounts
  1113. }
  1114. func (container *Container) copyImagePathContent(v volume.Volume, destination string) error {
  1115. rootfs, err := symlink.FollowSymlinkInScope(filepath.Join(container.basefs, destination), container.basefs)
  1116. if err != nil {
  1117. return err
  1118. }
  1119. if _, err = ioutil.ReadDir(rootfs); err != nil {
  1120. if os.IsNotExist(err) {
  1121. return nil
  1122. }
  1123. return err
  1124. }
  1125. path, err := v.Mount()
  1126. if err != nil {
  1127. return err
  1128. }
  1129. if err := copyExistingContents(rootfs, path); err != nil {
  1130. return err
  1131. }
  1132. return v.Unmount()
  1133. }
  1134. func (container *Container) shmPath() (string, error) {
  1135. return container.getRootResourcePath("shm")
  1136. }
  1137. func (container *Container) mqueuePath() (string, error) {
  1138. return container.getRootResourcePath("mqueue")
  1139. }
  1140. func (container *Container) hasMountFor(path string) bool {
  1141. _, exists := container.MountPoints[path]
  1142. return exists
  1143. }
  1144. func (daemon *Daemon) setupIpcDirs(container *Container) error {
  1145. rootUID, rootGID := daemon.GetRemappedUIDGID()
  1146. if !container.hasMountFor("/dev/shm") {
  1147. shmPath, err := container.shmPath()
  1148. if err != nil {
  1149. return err
  1150. }
  1151. if err := idtools.MkdirAllAs(shmPath, 0700, rootUID, rootGID); err != nil {
  1152. return err
  1153. }
  1154. 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 {
  1155. return fmt.Errorf("mounting shm tmpfs: %s", err)
  1156. }
  1157. if err := os.Chown(shmPath, rootUID, rootGID); err != nil {
  1158. return err
  1159. }
  1160. }
  1161. if !container.hasMountFor("/dev/mqueue") {
  1162. mqueuePath, err := container.mqueuePath()
  1163. if err != nil {
  1164. return err
  1165. }
  1166. if err := idtools.MkdirAllAs(mqueuePath, 0700, rootUID, rootGID); err != nil {
  1167. return err
  1168. }
  1169. if err := syscall.Mount("mqueue", mqueuePath, "mqueue", uintptr(syscall.MS_NOEXEC|syscall.MS_NOSUID|syscall.MS_NODEV), ""); err != nil {
  1170. return fmt.Errorf("mounting mqueue mqueue : %s", err)
  1171. }
  1172. if err := os.Chown(mqueuePath, rootUID, rootGID); err != nil {
  1173. return err
  1174. }
  1175. }
  1176. return nil
  1177. }
  1178. func (container *Container) unmountIpcMounts(unmount func(pth string) error) {
  1179. if container.hostConfig.IpcMode.IsContainer() || container.hostConfig.IpcMode.IsHost() {
  1180. return
  1181. }
  1182. var warnings []string
  1183. if !container.hasMountFor("/dev/shm") {
  1184. shmPath, err := container.shmPath()
  1185. if err != nil {
  1186. logrus.Error(err)
  1187. warnings = append(warnings, err.Error())
  1188. } else if shmPath != "" {
  1189. if err := unmount(shmPath); err != nil {
  1190. warnings = append(warnings, fmt.Sprintf("failed to umount %s: %v", shmPath, err))
  1191. }
  1192. }
  1193. }
  1194. if !container.hasMountFor("/dev/mqueue") {
  1195. mqueuePath, err := container.mqueuePath()
  1196. if err != nil {
  1197. logrus.Error(err)
  1198. warnings = append(warnings, err.Error())
  1199. } else if mqueuePath != "" {
  1200. if err := unmount(mqueuePath); err != nil {
  1201. warnings = append(warnings, fmt.Sprintf("failed to umount %s: %v", mqueuePath, err))
  1202. }
  1203. }
  1204. }
  1205. if len(warnings) > 0 {
  1206. logrus.Warnf("failed to cleanup ipc mounts:\n%v", strings.Join(warnings, "\n"))
  1207. }
  1208. }
  1209. func (container *Container) ipcMounts() []execdriver.Mount {
  1210. var mounts []execdriver.Mount
  1211. if !container.hasMountFor("/dev/shm") {
  1212. label.SetFileLabel(container.ShmPath, container.MountLabel)
  1213. mounts = append(mounts, execdriver.Mount{
  1214. Source: container.ShmPath,
  1215. Destination: "/dev/shm",
  1216. Writable: true,
  1217. Private: true,
  1218. })
  1219. }
  1220. if !container.hasMountFor("/dev/mqueue") {
  1221. label.SetFileLabel(container.MqueuePath, container.MountLabel)
  1222. mounts = append(mounts, execdriver.Mount{
  1223. Source: container.MqueuePath,
  1224. Destination: "/dev/mqueue",
  1225. Writable: true,
  1226. Private: true,
  1227. })
  1228. }
  1229. return mounts
  1230. }
  1231. func detachMounted(path string) error {
  1232. return syscall.Unmount(path, syscall.MNT_DETACH)
  1233. }