container_unix.go 43 KB

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