container_unix.go 42 KB

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