container_unix.go 42 KB

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