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