container_unix.go 42 KB

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