container_unix.go 42 KB

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