container_unix.go 42 KB

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