container_unix.go 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237
  1. // +build linux freebsd
  2. package daemon
  3. import (
  4. "fmt"
  5. "io/ioutil"
  6. "net"
  7. "os"
  8. "path"
  9. "path/filepath"
  10. "strconv"
  11. "strings"
  12. "syscall"
  13. "time"
  14. "github.com/Sirupsen/logrus"
  15. "github.com/docker/docker/daemon/execdriver"
  16. "github.com/docker/docker/daemon/links"
  17. "github.com/docker/docker/daemon/network"
  18. derr "github.com/docker/docker/errors"
  19. "github.com/docker/docker/pkg/directory"
  20. "github.com/docker/docker/pkg/nat"
  21. "github.com/docker/docker/pkg/stringid"
  22. "github.com/docker/docker/pkg/system"
  23. "github.com/docker/docker/pkg/ulimit"
  24. "github.com/docker/docker/runconfig"
  25. "github.com/docker/docker/utils"
  26. "github.com/docker/docker/volume"
  27. "github.com/docker/libnetwork"
  28. "github.com/docker/libnetwork/netlabel"
  29. "github.com/docker/libnetwork/options"
  30. "github.com/docker/libnetwork/types"
  31. "github.com/opencontainers/runc/libcontainer/configs"
  32. "github.com/opencontainers/runc/libcontainer/devices"
  33. "github.com/opencontainers/runc/libcontainer/label"
  34. )
  35. // DefaultPathEnv is unix style list of directories to search for
  36. // executables. Each directory is separated from the next by a colon
  37. // ':' character .
  38. const DefaultPathEnv = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
  39. // Container holds the fields specific to unixen implementations. See
  40. // CommonContainer for standard fields common to all containers.
  41. type Container struct {
  42. CommonContainer
  43. // Fields below here are platform specific.
  44. activeLinks map[string]*links.Link
  45. AppArmorProfile string
  46. HostnamePath string
  47. HostsPath string
  48. MountPoints map[string]*mountPoint
  49. ResolvConfPath string
  50. Volumes map[string]string // Deprecated since 1.7, kept for backwards compatibility
  51. VolumesRW map[string]bool // Deprecated since 1.7, kept for backwards compatibility
  52. }
  53. func killProcessDirectly(container *Container) error {
  54. if _, err := container.WaitStop(10 * time.Second); err != nil {
  55. // Ensure that we don't kill ourselves
  56. if pid := container.getPID(); pid != 0 {
  57. logrus.Infof("Container %s failed to exit within 10 seconds of kill - trying direct SIGKILL", stringid.TruncateID(container.ID))
  58. if err := syscall.Kill(pid, 9); err != nil {
  59. if err != syscall.ESRCH {
  60. return err
  61. }
  62. logrus.Debugf("Cannot kill process (pid=%d) with signal 9: no such process.", pid)
  63. }
  64. }
  65. }
  66. return nil
  67. }
  68. func (container *Container) setupLinkedContainers() ([]string, error) {
  69. var (
  70. env []string
  71. daemon = container.daemon
  72. )
  73. children, err := daemon.children(container.Name)
  74. if err != nil {
  75. return nil, err
  76. }
  77. if len(children) > 0 {
  78. for linkAlias, child := range children {
  79. if !child.IsRunning() {
  80. return nil, derr.ErrorCodeLinkNotRunning.WithArgs(child.Name, linkAlias)
  81. }
  82. link := links.NewLink(
  83. container.NetworkSettings.IPAddress,
  84. child.NetworkSettings.IPAddress,
  85. linkAlias,
  86. child.Config.Env,
  87. child.Config.ExposedPorts,
  88. )
  89. for _, envVar := range link.ToEnv() {
  90. env = append(env, envVar)
  91. }
  92. }
  93. }
  94. return env, nil
  95. }
  96. func (container *Container) createDaemonEnvironment(linkedEnv []string) []string {
  97. // if a domain name was specified, append it to the hostname (see #7851)
  98. fullHostname := container.Config.Hostname
  99. if container.Config.Domainname != "" {
  100. fullHostname = fmt.Sprintf("%s.%s", fullHostname, container.Config.Domainname)
  101. }
  102. // Setup environment
  103. env := []string{
  104. "PATH=" + DefaultPathEnv,
  105. "HOSTNAME=" + fullHostname,
  106. // Note: we don't set HOME here because it'll get autoset intelligently
  107. // based on the value of USER inside dockerinit, but only if it isn't
  108. // set already (ie, that can be overridden by setting HOME via -e or ENV
  109. // in a Dockerfile).
  110. }
  111. if container.Config.Tty {
  112. env = append(env, "TERM=xterm")
  113. }
  114. env = append(env, linkedEnv...)
  115. // because the env on the container can override certain default values
  116. // we need to replace the 'env' keys where they match and append anything
  117. // else.
  118. env = utils.ReplaceOrAppendEnvValues(env, container.Config.Env)
  119. return env
  120. }
  121. func getDevicesFromPath(deviceMapping runconfig.DeviceMapping) (devs []*configs.Device, err error) {
  122. device, err := devices.DeviceFromPath(deviceMapping.PathOnHost, deviceMapping.CgroupPermissions)
  123. // if there was no error, return the device
  124. if err == nil {
  125. device.Path = deviceMapping.PathInContainer
  126. return append(devs, device), nil
  127. }
  128. // if the device is not a device node
  129. // try to see if it's a directory holding many devices
  130. if err == devices.ErrNotADevice {
  131. // check if it is a directory
  132. if src, e := os.Stat(deviceMapping.PathOnHost); e == nil && src.IsDir() {
  133. // mount the internal devices recursively
  134. filepath.Walk(deviceMapping.PathOnHost, func(dpath string, f os.FileInfo, e error) error {
  135. childDevice, e := devices.DeviceFromPath(dpath, deviceMapping.CgroupPermissions)
  136. if e != nil {
  137. // ignore the device
  138. return nil
  139. }
  140. // add the device to userSpecified devices
  141. childDevice.Path = strings.Replace(dpath, deviceMapping.PathOnHost, deviceMapping.PathInContainer, 1)
  142. devs = append(devs, childDevice)
  143. return nil
  144. })
  145. }
  146. }
  147. if len(devs) > 0 {
  148. return devs, nil
  149. }
  150. return devs, derr.ErrorCodeDeviceInfo.WithArgs(deviceMapping.PathOnHost, err)
  151. }
  152. func populateCommand(c *Container, env []string) error {
  153. var en *execdriver.Network
  154. if !c.Config.NetworkDisabled {
  155. en = &execdriver.Network{}
  156. if !c.daemon.execDriver.SupportsHooks() || c.hostConfig.NetworkMode.IsHost() {
  157. en.NamespacePath = c.NetworkSettings.SandboxKey
  158. }
  159. parts := strings.SplitN(string(c.hostConfig.NetworkMode), ":", 2)
  160. if parts[0] == "container" {
  161. nc, err := c.getNetworkedContainer()
  162. if err != nil {
  163. return err
  164. }
  165. en.ContainerID = nc.ID
  166. }
  167. }
  168. ipc := &execdriver.Ipc{}
  169. if c.hostConfig.IpcMode.IsContainer() {
  170. ic, err := c.getIpcContainer()
  171. if err != nil {
  172. return err
  173. }
  174. ipc.ContainerID = ic.ID
  175. } else {
  176. ipc.HostIpc = c.hostConfig.IpcMode.IsHost()
  177. }
  178. pid := &execdriver.Pid{}
  179. pid.HostPid = c.hostConfig.PidMode.IsHost()
  180. uts := &execdriver.UTS{
  181. HostUTS: c.hostConfig.UTSMode.IsHost(),
  182. }
  183. // Build lists of devices allowed and created within the container.
  184. var userSpecifiedDevices []*configs.Device
  185. for _, deviceMapping := range c.hostConfig.Devices {
  186. devs, err := getDevicesFromPath(deviceMapping)
  187. if err != nil {
  188. return err
  189. }
  190. userSpecifiedDevices = append(userSpecifiedDevices, devs...)
  191. }
  192. allowedDevices := mergeDevices(configs.DefaultAllowedDevices, userSpecifiedDevices)
  193. autoCreatedDevices := mergeDevices(configs.DefaultAutoCreatedDevices, userSpecifiedDevices)
  194. // TODO: this can be removed after lxc-conf is fully deprecated
  195. lxcConfig, err := mergeLxcConfIntoOptions(c.hostConfig)
  196. if err != nil {
  197. return err
  198. }
  199. var rlimits []*ulimit.Rlimit
  200. ulimits := c.hostConfig.Ulimits
  201. // Merge ulimits with daemon defaults
  202. ulIdx := make(map[string]*ulimit.Ulimit)
  203. for _, ul := range ulimits {
  204. ulIdx[ul.Name] = ul
  205. }
  206. for name, ul := range c.daemon.configStore.Ulimits {
  207. if _, exists := ulIdx[name]; !exists {
  208. ulimits = append(ulimits, ul)
  209. }
  210. }
  211. for _, limit := range ulimits {
  212. rl, err := limit.GetRlimit()
  213. if err != nil {
  214. return err
  215. }
  216. rlimits = append(rlimits, rl)
  217. }
  218. resources := &execdriver.Resources{
  219. Memory: c.hostConfig.Memory,
  220. MemorySwap: c.hostConfig.MemorySwap,
  221. KernelMemory: c.hostConfig.KernelMemory,
  222. CPUShares: c.hostConfig.CPUShares,
  223. CpusetCpus: c.hostConfig.CpusetCpus,
  224. CpusetMems: c.hostConfig.CpusetMems,
  225. CPUPeriod: c.hostConfig.CPUPeriod,
  226. CPUQuota: c.hostConfig.CPUQuota,
  227. BlkioWeight: c.hostConfig.BlkioWeight,
  228. Rlimits: rlimits,
  229. OomKillDisable: c.hostConfig.OomKillDisable,
  230. MemorySwappiness: -1,
  231. }
  232. if c.hostConfig.MemorySwappiness != nil {
  233. resources.MemorySwappiness = *c.hostConfig.MemorySwappiness
  234. }
  235. processConfig := execdriver.ProcessConfig{
  236. Privileged: c.hostConfig.Privileged,
  237. Entrypoint: c.Path,
  238. Arguments: c.Args,
  239. Tty: c.Config.Tty,
  240. User: c.Config.User,
  241. }
  242. processConfig.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
  243. processConfig.Env = env
  244. c.command = &execdriver.Command{
  245. ID: c.ID,
  246. Rootfs: c.rootfsPath(),
  247. ReadonlyRootfs: c.hostConfig.ReadonlyRootfs,
  248. InitPath: "/.dockerinit",
  249. WorkingDir: c.Config.WorkingDir,
  250. Network: en,
  251. Ipc: ipc,
  252. Pid: pid,
  253. UTS: uts,
  254. Resources: resources,
  255. AllowedDevices: allowedDevices,
  256. AutoCreatedDevices: autoCreatedDevices,
  257. CapAdd: c.hostConfig.CapAdd.Slice(),
  258. CapDrop: c.hostConfig.CapDrop.Slice(),
  259. GroupAdd: c.hostConfig.GroupAdd,
  260. ProcessConfig: processConfig,
  261. ProcessLabel: c.getProcessLabel(),
  262. MountLabel: c.getMountLabel(),
  263. LxcConfig: lxcConfig,
  264. AppArmorProfile: c.AppArmorProfile,
  265. CgroupParent: c.hostConfig.CgroupParent,
  266. }
  267. return nil
  268. }
  269. func mergeDevices(defaultDevices, userDevices []*configs.Device) []*configs.Device {
  270. if len(userDevices) == 0 {
  271. return defaultDevices
  272. }
  273. paths := map[string]*configs.Device{}
  274. for _, d := range userDevices {
  275. paths[d.Path] = d
  276. }
  277. var devs []*configs.Device
  278. for _, d := range defaultDevices {
  279. if _, defined := paths[d.Path]; !defined {
  280. devs = append(devs, d)
  281. }
  282. }
  283. return append(devs, userDevices...)
  284. }
  285. // GetSize returns the real size & virtual size of the container.
  286. func (container *Container) getSize() (int64, int64) {
  287. var (
  288. sizeRw, sizeRootfs int64
  289. err error
  290. driver = container.daemon.driver
  291. )
  292. if err := container.Mount(); err != nil {
  293. logrus.Errorf("Failed to compute size of container rootfs %s: %s", container.ID, err)
  294. return sizeRw, sizeRootfs
  295. }
  296. defer container.Unmount()
  297. initID := fmt.Sprintf("%s-init", container.ID)
  298. sizeRw, err = driver.DiffSize(container.ID, initID)
  299. if err != nil {
  300. logrus.Errorf("Driver %s couldn't return diff size of container %s: %s", driver, container.ID, err)
  301. // FIXME: GetSize should return an error. Not changing it now in case
  302. // there is a side-effect.
  303. sizeRw = -1
  304. }
  305. if _, err = os.Stat(container.basefs); err == nil {
  306. if sizeRootfs, err = directory.Size(container.basefs); err != nil {
  307. sizeRootfs = -1
  308. }
  309. }
  310. return sizeRw, sizeRootfs
  311. }
  312. // Attempt to set the network mounts given a provided destination and
  313. // the path to use for it; return true if the given destination was a
  314. // network mount file
  315. func (container *Container) trySetNetworkMount(destination string, path string) bool {
  316. if destination == "/etc/resolv.conf" {
  317. container.ResolvConfPath = path
  318. return true
  319. }
  320. if destination == "/etc/hostname" {
  321. container.HostnamePath = path
  322. return true
  323. }
  324. if destination == "/etc/hosts" {
  325. container.HostsPath = path
  326. return true
  327. }
  328. return false
  329. }
  330. func (container *Container) buildHostnameFile() error {
  331. hostnamePath, err := container.getRootResourcePath("hostname")
  332. if err != nil {
  333. return err
  334. }
  335. container.HostnamePath = hostnamePath
  336. if container.Config.Domainname != "" {
  337. return ioutil.WriteFile(container.HostnamePath, []byte(fmt.Sprintf("%s.%s\n", container.Config.Hostname, container.Config.Domainname)), 0644)
  338. }
  339. return ioutil.WriteFile(container.HostnamePath, []byte(container.Config.Hostname+"\n"), 0644)
  340. }
  341. func (container *Container) buildSandboxOptions() ([]libnetwork.SandboxOption, error) {
  342. var (
  343. sboxOptions []libnetwork.SandboxOption
  344. err error
  345. dns []string
  346. dnsSearch []string
  347. dnsOptions []string
  348. )
  349. sboxOptions = append(sboxOptions, libnetwork.OptionHostname(container.Config.Hostname),
  350. libnetwork.OptionDomainname(container.Config.Domainname))
  351. if container.hostConfig.NetworkMode.IsHost() {
  352. sboxOptions = append(sboxOptions, libnetwork.OptionUseDefaultSandbox())
  353. sboxOptions = append(sboxOptions, libnetwork.OptionOriginHostsPath("/etc/hosts"))
  354. sboxOptions = append(sboxOptions, libnetwork.OptionOriginResolvConfPath("/etc/resolv.conf"))
  355. } else if container.daemon.execDriver.SupportsHooks() {
  356. // OptionUseExternalKey is mandatory for userns support.
  357. // But optional for non-userns support
  358. sboxOptions = append(sboxOptions, libnetwork.OptionUseExternalKey())
  359. }
  360. container.HostsPath, err = container.getRootResourcePath("hosts")
  361. if err != nil {
  362. return nil, err
  363. }
  364. sboxOptions = append(sboxOptions, libnetwork.OptionHostsPath(container.HostsPath))
  365. container.ResolvConfPath, err = container.getRootResourcePath("resolv.conf")
  366. if err != nil {
  367. return nil, err
  368. }
  369. sboxOptions = append(sboxOptions, libnetwork.OptionResolvConfPath(container.ResolvConfPath))
  370. if len(container.hostConfig.DNS) > 0 {
  371. dns = container.hostConfig.DNS
  372. } else if len(container.daemon.configStore.DNS) > 0 {
  373. dns = container.daemon.configStore.DNS
  374. }
  375. for _, d := range dns {
  376. sboxOptions = append(sboxOptions, libnetwork.OptionDNS(d))
  377. }
  378. if len(container.hostConfig.DNSSearch) > 0 {
  379. dnsSearch = container.hostConfig.DNSSearch
  380. } else if len(container.daemon.configStore.DNSSearch) > 0 {
  381. dnsSearch = container.daemon.configStore.DNSSearch
  382. }
  383. for _, ds := range dnsSearch {
  384. sboxOptions = append(sboxOptions, libnetwork.OptionDNSSearch(ds))
  385. }
  386. if len(container.hostConfig.DNSOptions) > 0 {
  387. dnsOptions = container.hostConfig.DNSOptions
  388. } else if len(container.daemon.configStore.DNSOptions) > 0 {
  389. dnsOptions = container.daemon.configStore.DNSOptions
  390. }
  391. for _, ds := range dnsOptions {
  392. sboxOptions = append(sboxOptions, libnetwork.OptionDNSOptions(ds))
  393. }
  394. if container.NetworkSettings.SecondaryIPAddresses != nil {
  395. name := container.Config.Hostname
  396. if container.Config.Domainname != "" {
  397. name = name + "." + container.Config.Domainname
  398. }
  399. for _, a := range container.NetworkSettings.SecondaryIPAddresses {
  400. sboxOptions = append(sboxOptions, libnetwork.OptionExtraHost(name, a.Addr))
  401. }
  402. }
  403. var childEndpoints, parentEndpoints []string
  404. children, err := container.daemon.children(container.Name)
  405. if err != nil {
  406. return nil, err
  407. }
  408. for linkAlias, child := range children {
  409. _, alias := path.Split(linkAlias)
  410. // allow access to the linked container via the alias, real name, and container hostname
  411. aliasList := alias + " " + child.Config.Hostname
  412. // only add the name if alias isn't equal to the name
  413. if alias != child.Name[1:] {
  414. aliasList = aliasList + " " + child.Name[1:]
  415. }
  416. sboxOptions = append(sboxOptions, libnetwork.OptionExtraHost(aliasList, child.NetworkSettings.IPAddress))
  417. if child.NetworkSettings.EndpointID != "" {
  418. childEndpoints = append(childEndpoints, child.NetworkSettings.EndpointID)
  419. }
  420. }
  421. for _, extraHost := range container.hostConfig.ExtraHosts {
  422. // allow IPv6 addresses in extra hosts; only split on first ":"
  423. parts := strings.SplitN(extraHost, ":", 2)
  424. sboxOptions = append(sboxOptions, libnetwork.OptionExtraHost(parts[0], parts[1]))
  425. }
  426. refs := container.daemon.containerGraph().RefPaths(container.ID)
  427. for _, ref := range refs {
  428. if ref.ParentID == "0" {
  429. continue
  430. }
  431. c, err := container.daemon.Get(ref.ParentID)
  432. if err != nil {
  433. logrus.Error(err)
  434. }
  435. if c != nil && !container.daemon.configStore.DisableBridge && container.hostConfig.NetworkMode.IsPrivate() {
  436. logrus.Debugf("Update /etc/hosts of %s for alias %s with ip %s", c.ID, ref.Name, container.NetworkSettings.IPAddress)
  437. sboxOptions = append(sboxOptions, libnetwork.OptionParentUpdate(c.ID, ref.Name, container.NetworkSettings.IPAddress))
  438. if c.NetworkSettings.EndpointID != "" {
  439. parentEndpoints = append(parentEndpoints, c.NetworkSettings.EndpointID)
  440. }
  441. }
  442. }
  443. linkOptions := options.Generic{
  444. netlabel.GenericData: options.Generic{
  445. "ParentEndpoints": parentEndpoints,
  446. "ChildEndpoints": childEndpoints,
  447. },
  448. }
  449. sboxOptions = append(sboxOptions, libnetwork.OptionGeneric(linkOptions))
  450. return sboxOptions, nil
  451. }
  452. func (container *Container) buildPortMapInfo(ep libnetwork.Endpoint, networkSettings *network.Settings) (*network.Settings, error) {
  453. if ep == nil {
  454. return nil, derr.ErrorCodeEmptyEndpoint
  455. }
  456. if networkSettings == nil {
  457. return nil, derr.ErrorCodeEmptyNetwork
  458. }
  459. driverInfo, err := ep.DriverInfo()
  460. if err != nil {
  461. return nil, err
  462. }
  463. if driverInfo == nil {
  464. // It is not an error for epInfo to be nil
  465. return networkSettings, nil
  466. }
  467. if mac, ok := driverInfo[netlabel.MacAddress]; ok {
  468. networkSettings.MacAddress = mac.(net.HardwareAddr).String()
  469. }
  470. networkSettings.Ports = nat.PortMap{}
  471. if expData, ok := driverInfo[netlabel.ExposedPorts]; ok {
  472. if exposedPorts, ok := expData.([]types.TransportPort); ok {
  473. for _, tp := range exposedPorts {
  474. natPort, err := nat.NewPort(tp.Proto.String(), strconv.Itoa(int(tp.Port)))
  475. if err != nil {
  476. return nil, derr.ErrorCodeParsingPort.WithArgs(tp.Port, err)
  477. }
  478. networkSettings.Ports[natPort] = nil
  479. }
  480. }
  481. }
  482. mapData, ok := driverInfo[netlabel.PortMap]
  483. if !ok {
  484. return networkSettings, nil
  485. }
  486. if portMapping, ok := mapData.([]types.PortBinding); ok {
  487. for _, pp := range portMapping {
  488. natPort, err := nat.NewPort(pp.Proto.String(), strconv.Itoa(int(pp.Port)))
  489. if err != nil {
  490. return nil, err
  491. }
  492. natBndg := nat.PortBinding{HostIP: pp.HostIP.String(), HostPort: strconv.Itoa(int(pp.HostPort))}
  493. networkSettings.Ports[natPort] = append(networkSettings.Ports[natPort], natBndg)
  494. }
  495. }
  496. return networkSettings, nil
  497. }
  498. func (container *Container) buildEndpointInfo(ep libnetwork.Endpoint, networkSettings *network.Settings) (*network.Settings, error) {
  499. if ep == nil {
  500. return nil, derr.ErrorCodeEmptyEndpoint
  501. }
  502. if networkSettings == nil {
  503. return nil, derr.ErrorCodeEmptyNetwork
  504. }
  505. epInfo := ep.Info()
  506. if epInfo == nil {
  507. // It is not an error to get an empty endpoint info
  508. return networkSettings, nil
  509. }
  510. iface := epInfo.Iface()
  511. if iface == nil {
  512. return networkSettings, nil
  513. }
  514. ones, _ := iface.Address().Mask.Size()
  515. networkSettings.IPAddress = iface.Address().IP.String()
  516. networkSettings.IPPrefixLen = ones
  517. if iface.AddressIPv6().IP.To16() != nil {
  518. onesv6, _ := iface.AddressIPv6().Mask.Size()
  519. networkSettings.GlobalIPv6Address = iface.AddressIPv6().IP.String()
  520. networkSettings.GlobalIPv6PrefixLen = onesv6
  521. }
  522. return networkSettings, nil
  523. }
  524. func (container *Container) updateJoinInfo(ep libnetwork.Endpoint) error {
  525. epInfo := ep.Info()
  526. if epInfo == nil {
  527. // It is not an error to get an empty endpoint info
  528. return nil
  529. }
  530. container.NetworkSettings.Gateway = epInfo.Gateway().String()
  531. if epInfo.GatewayIPv6().To16() != nil {
  532. container.NetworkSettings.IPv6Gateway = epInfo.GatewayIPv6().String()
  533. }
  534. return nil
  535. }
  536. func (container *Container) updateEndpointNetworkSettings(n libnetwork.Network, ep libnetwork.Endpoint) error {
  537. networkSettings := &network.Settings{NetworkID: n.ID(), EndpointID: ep.ID()}
  538. networkSettings, err := container.buildPortMapInfo(ep, networkSettings)
  539. if err != nil {
  540. return err
  541. }
  542. networkSettings, err = container.buildEndpointInfo(ep, networkSettings)
  543. if err != nil {
  544. return err
  545. }
  546. if container.hostConfig.NetworkMode == runconfig.NetworkMode("bridge") {
  547. networkSettings.Bridge = container.daemon.configStore.Bridge.Iface
  548. }
  549. container.NetworkSettings = networkSettings
  550. return nil
  551. }
  552. func (container *Container) updateSandboxNetworkSettings(sb libnetwork.Sandbox) error {
  553. container.NetworkSettings.SandboxID = sb.ID()
  554. container.NetworkSettings.SandboxKey = sb.Key()
  555. return nil
  556. }
  557. // UpdateNetwork is used to update the container's network (e.g. when linked containers
  558. // get removed/unlinked).
  559. func (container *Container) updateNetwork() error {
  560. ctrl := container.daemon.netController
  561. sid := container.NetworkSettings.SandboxID
  562. sb, err := ctrl.SandboxByID(sid)
  563. if err != nil {
  564. return derr.ErrorCodeNoSandbox.WithArgs(sid, err)
  565. }
  566. options, err := container.buildSandboxOptions()
  567. if err != nil {
  568. return derr.ErrorCodeNetworkUpdate.WithArgs(err)
  569. }
  570. if err := sb.Refresh(options...); err != nil {
  571. return derr.ErrorCodeNetworkRefresh.WithArgs(sid, err)
  572. }
  573. return nil
  574. }
  575. func (container *Container) buildCreateEndpointOptions() ([]libnetwork.EndpointOption, error) {
  576. var (
  577. portSpecs = make(nat.PortSet)
  578. bindings = make(nat.PortMap)
  579. pbList []types.PortBinding
  580. exposeList []types.TransportPort
  581. createOptions []libnetwork.EndpointOption
  582. )
  583. if container.Config.ExposedPorts != nil {
  584. portSpecs = container.Config.ExposedPorts
  585. }
  586. if container.hostConfig.PortBindings != nil {
  587. for p, b := range container.hostConfig.PortBindings {
  588. bindings[p] = []nat.PortBinding{}
  589. for _, bb := range b {
  590. bindings[p] = append(bindings[p], nat.PortBinding{
  591. HostIP: bb.HostIP,
  592. HostPort: bb.HostPort,
  593. })
  594. }
  595. }
  596. }
  597. ports := make([]nat.Port, len(portSpecs))
  598. var i int
  599. for p := range portSpecs {
  600. ports[i] = p
  601. i++
  602. }
  603. nat.SortPortMap(ports, bindings)
  604. for _, port := range ports {
  605. expose := types.TransportPort{}
  606. expose.Proto = types.ParseProtocol(port.Proto())
  607. expose.Port = uint16(port.Int())
  608. exposeList = append(exposeList, expose)
  609. pb := types.PortBinding{Port: expose.Port, Proto: expose.Proto}
  610. binding := bindings[port]
  611. for i := 0; i < len(binding); i++ {
  612. pbCopy := pb.GetCopy()
  613. newP, err := nat.NewPort(nat.SplitProtoPort(binding[i].HostPort))
  614. var portStart, portEnd int
  615. if err == nil {
  616. portStart, portEnd, err = newP.Range()
  617. }
  618. if err != nil {
  619. return nil, derr.ErrorCodeHostPort.WithArgs(binding[i].HostPort, err)
  620. }
  621. pbCopy.HostPort = uint16(portStart)
  622. pbCopy.HostPortEnd = uint16(portEnd)
  623. pbCopy.HostIP = net.ParseIP(binding[i].HostIP)
  624. pbList = append(pbList, pbCopy)
  625. }
  626. if container.hostConfig.PublishAllPorts && len(binding) == 0 {
  627. pbList = append(pbList, pb)
  628. }
  629. }
  630. createOptions = append(createOptions,
  631. libnetwork.CreateOptionPortMapping(pbList),
  632. libnetwork.CreateOptionExposedPorts(exposeList))
  633. if container.Config.MacAddress != "" {
  634. mac, err := net.ParseMAC(container.Config.MacAddress)
  635. if err != nil {
  636. return nil, err
  637. }
  638. genericOption := options.Generic{
  639. netlabel.MacAddress: mac,
  640. }
  641. createOptions = append(createOptions, libnetwork.EndpointOptionGeneric(genericOption))
  642. }
  643. return createOptions, nil
  644. }
  645. func parseService(controller libnetwork.NetworkController, service string) (string, string, string) {
  646. dn := controller.Config().Daemon.DefaultNetwork
  647. dd := controller.Config().Daemon.DefaultDriver
  648. snd := strings.Split(service, ".")
  649. if len(snd) > 2 {
  650. return strings.Join(snd[:len(snd)-2], "."), snd[len(snd)-2], snd[len(snd)-1]
  651. }
  652. if len(snd) > 1 {
  653. return snd[0], snd[1], dd
  654. }
  655. return snd[0], dn, dd
  656. }
  657. func createNetwork(controller libnetwork.NetworkController, dnet string, driver string) (libnetwork.Network, error) {
  658. createOptions := []libnetwork.NetworkOption{}
  659. genericOption := options.Generic{}
  660. // Bridge driver is special due to legacy reasons
  661. if runconfig.NetworkMode(driver).IsBridge() {
  662. genericOption[netlabel.GenericData] = map[string]interface{}{
  663. "BridgeName": dnet,
  664. "AllowNonDefaultBridge": "true",
  665. }
  666. networkOption := libnetwork.NetworkOptionGeneric(genericOption)
  667. createOptions = append(createOptions, networkOption)
  668. }
  669. return controller.NewNetwork(driver, dnet, createOptions...)
  670. }
  671. func (container *Container) secondaryNetworkRequired(primaryNetworkType string) bool {
  672. switch primaryNetworkType {
  673. case "bridge", "none", "host", "container":
  674. return false
  675. }
  676. if container.daemon.configStore.DisableBridge {
  677. return false
  678. }
  679. if container.Config.ExposedPorts != nil && len(container.Config.ExposedPorts) > 0 {
  680. return true
  681. }
  682. if container.hostConfig.PortBindings != nil && len(container.hostConfig.PortBindings) > 0 {
  683. return true
  684. }
  685. return false
  686. }
  687. func (container *Container) allocateNetwork() error {
  688. mode := container.hostConfig.NetworkMode
  689. controller := container.daemon.netController
  690. if container.Config.NetworkDisabled || mode.IsContainer() {
  691. return nil
  692. }
  693. networkDriver := string(mode)
  694. service := container.Config.PublishService
  695. networkName := mode.NetworkName()
  696. if mode.IsDefault() {
  697. if service != "" {
  698. service, networkName, networkDriver = parseService(controller, service)
  699. } else {
  700. networkName = controller.Config().Daemon.DefaultNetwork
  701. networkDriver = controller.Config().Daemon.DefaultDriver
  702. }
  703. } else if service != "" {
  704. return derr.ErrorCodeNetworkConflict
  705. }
  706. if runconfig.NetworkMode(networkDriver).IsBridge() && container.daemon.configStore.DisableBridge {
  707. container.Config.NetworkDisabled = true
  708. return nil
  709. }
  710. if service == "" {
  711. // dot character "." has a special meaning to support SERVICE[.NETWORK] format.
  712. // For backward compatibility, replacing "." with "-", instead of failing
  713. service = strings.Replace(container.Name, ".", "-", -1)
  714. // Service names dont like "/" in them. removing it instead of failing for backward compatibility
  715. service = strings.Replace(service, "/", "", -1)
  716. }
  717. if container.secondaryNetworkRequired(networkDriver) {
  718. // Configure Bridge as secondary network for port binding purposes
  719. if err := container.configureNetwork("bridge", service, "bridge", false); err != nil {
  720. return err
  721. }
  722. }
  723. if err := container.configureNetwork(networkName, service, networkDriver, mode.IsDefault()); err != nil {
  724. return err
  725. }
  726. return container.writeHostConfig()
  727. }
  728. func (container *Container) configureNetwork(networkName, service, networkDriver string, canCreateNetwork bool) error {
  729. controller := container.daemon.netController
  730. n, err := controller.NetworkByName(networkName)
  731. if err != nil {
  732. if _, ok := err.(libnetwork.ErrNoSuchNetwork); !ok || !canCreateNetwork {
  733. return err
  734. }
  735. if n, err = createNetwork(controller, networkName, networkDriver); err != nil {
  736. return err
  737. }
  738. }
  739. ep, err := n.EndpointByName(service)
  740. if err != nil {
  741. if _, ok := err.(libnetwork.ErrNoSuchEndpoint); !ok {
  742. return err
  743. }
  744. createOptions, err := container.buildCreateEndpointOptions()
  745. if err != nil {
  746. return err
  747. }
  748. ep, err = n.CreateEndpoint(service, createOptions...)
  749. if err != nil {
  750. return err
  751. }
  752. }
  753. if err := container.updateEndpointNetworkSettings(n, ep); err != nil {
  754. return err
  755. }
  756. var sb libnetwork.Sandbox
  757. controller.WalkSandboxes(func(s libnetwork.Sandbox) bool {
  758. if s.ContainerID() == container.ID {
  759. sb = s
  760. return true
  761. }
  762. return false
  763. })
  764. if sb == nil {
  765. options, err := container.buildSandboxOptions()
  766. if err != nil {
  767. return err
  768. }
  769. sb, err = controller.NewSandbox(container.ID, options...)
  770. if err != nil {
  771. return err
  772. }
  773. }
  774. container.updateSandboxNetworkSettings(sb)
  775. if err := ep.Join(sb); err != nil {
  776. return err
  777. }
  778. if err := container.updateJoinInfo(ep); err != nil {
  779. return derr.ErrorCodeJoinInfo.WithArgs(err)
  780. }
  781. return nil
  782. }
  783. func (container *Container) initializeNetworking() error {
  784. var err error
  785. if container.hostConfig.NetworkMode.IsContainer() {
  786. // we need to get the hosts files from the container to join
  787. nc, err := container.getNetworkedContainer()
  788. if err != nil {
  789. return err
  790. }
  791. container.HostnamePath = nc.HostnamePath
  792. container.HostsPath = nc.HostsPath
  793. container.ResolvConfPath = nc.ResolvConfPath
  794. container.Config.Hostname = nc.Config.Hostname
  795. container.Config.Domainname = nc.Config.Domainname
  796. return nil
  797. }
  798. if container.hostConfig.NetworkMode.IsHost() {
  799. container.Config.Hostname, err = os.Hostname()
  800. if err != nil {
  801. return err
  802. }
  803. parts := strings.SplitN(container.Config.Hostname, ".", 2)
  804. if len(parts) > 1 {
  805. container.Config.Hostname = parts[0]
  806. container.Config.Domainname = parts[1]
  807. }
  808. }
  809. if err := container.allocateNetwork(); err != nil {
  810. return err
  811. }
  812. return container.buildHostnameFile()
  813. }
  814. // called from the libcontainer pre-start hook to set the network
  815. // namespace configuration linkage to the libnetwork "sandbox" entity
  816. func (container *Container) setNetworkNamespaceKey(pid int) error {
  817. path := fmt.Sprintf("/proc/%d/ns/net", pid)
  818. var sandbox libnetwork.Sandbox
  819. search := libnetwork.SandboxContainerWalker(&sandbox, container.ID)
  820. container.daemon.netController.WalkSandboxes(search)
  821. if sandbox == nil {
  822. return fmt.Errorf("no sandbox present for %s", container.ID)
  823. }
  824. return sandbox.SetKey(path)
  825. }
  826. func (container *Container) getIpcContainer() (*Container, error) {
  827. containerID := container.hostConfig.IpcMode.Container()
  828. c, err := container.daemon.Get(containerID)
  829. if err != nil {
  830. return nil, err
  831. }
  832. if !c.IsRunning() {
  833. return nil, derr.ErrorCodeIPCRunning
  834. }
  835. return c, nil
  836. }
  837. func (container *Container) setupWorkingDirectory() error {
  838. if container.Config.WorkingDir != "" {
  839. container.Config.WorkingDir = filepath.Clean(container.Config.WorkingDir)
  840. pth, err := container.GetResourcePath(container.Config.WorkingDir)
  841. if err != nil {
  842. return err
  843. }
  844. pthInfo, err := os.Stat(pth)
  845. if err != nil {
  846. if !os.IsNotExist(err) {
  847. return err
  848. }
  849. if err := system.MkdirAll(pth, 0755); err != nil {
  850. return err
  851. }
  852. }
  853. if pthInfo != nil && !pthInfo.IsDir() {
  854. return derr.ErrorCodeNotADir.WithArgs(container.Config.WorkingDir)
  855. }
  856. }
  857. return nil
  858. }
  859. func (container *Container) getNetworkedContainer() (*Container, error) {
  860. parts := strings.SplitN(string(container.hostConfig.NetworkMode), ":", 2)
  861. switch parts[0] {
  862. case "container":
  863. if len(parts) != 2 {
  864. return nil, derr.ErrorCodeParseContainer
  865. }
  866. nc, err := container.daemon.Get(parts[1])
  867. if err != nil {
  868. return nil, err
  869. }
  870. if container == nc {
  871. return nil, derr.ErrorCodeJoinSelf
  872. }
  873. if !nc.IsRunning() {
  874. return nil, derr.ErrorCodeJoinRunning.WithArgs(parts[1])
  875. }
  876. return nc, nil
  877. default:
  878. return nil, derr.ErrorCodeModeNotContainer
  879. }
  880. }
  881. func (container *Container) releaseNetwork() {
  882. if container.hostConfig.NetworkMode.IsContainer() || container.Config.NetworkDisabled {
  883. return
  884. }
  885. sid := container.NetworkSettings.SandboxID
  886. eid := container.NetworkSettings.EndpointID
  887. nid := container.NetworkSettings.NetworkID
  888. container.NetworkSettings = &network.Settings{}
  889. if sid == "" || nid == "" || eid == "" {
  890. return
  891. }
  892. sb, err := container.daemon.netController.SandboxByID(sid)
  893. if err != nil {
  894. logrus.Errorf("error locating sandbox id %s: %v", sid, err)
  895. return
  896. }
  897. n, err := container.daemon.netController.NetworkByID(nid)
  898. if err != nil {
  899. logrus.Errorf("error locating network id %s: %v", nid, err)
  900. return
  901. }
  902. ep, err := n.EndpointByID(eid)
  903. if err != nil {
  904. logrus.Errorf("error locating endpoint id %s: %v", eid, err)
  905. return
  906. }
  907. if err := sb.Delete(); err != nil {
  908. logrus.Errorf("Error deleting sandbox id %s for container %s: %v", sid, container.ID, err)
  909. return
  910. }
  911. // In addition to leaving all endpoints, delete implicitly created endpoint
  912. if container.Config.PublishService == "" {
  913. if err := ep.Delete(); err != nil {
  914. logrus.Errorf("deleting endpoint failed: %v", err)
  915. }
  916. }
  917. }
  918. func (container *Container) unmountVolumes(forceSyscall bool) error {
  919. var volumeMounts []mountPoint
  920. for _, mntPoint := range container.MountPoints {
  921. dest, err := container.GetResourcePath(mntPoint.Destination)
  922. if err != nil {
  923. return err
  924. }
  925. volumeMounts = append(volumeMounts, mountPoint{Destination: dest, Volume: mntPoint.Volume})
  926. }
  927. for _, mnt := range container.networkMounts() {
  928. dest, err := container.GetResourcePath(mnt.Destination)
  929. if err != nil {
  930. return err
  931. }
  932. volumeMounts = append(volumeMounts, mountPoint{Destination: dest})
  933. }
  934. for _, volumeMount := range volumeMounts {
  935. if forceSyscall {
  936. syscall.Unmount(volumeMount.Destination, 0)
  937. }
  938. if volumeMount.Volume != nil {
  939. if err := volumeMount.Volume.Unmount(); err != nil {
  940. return err
  941. }
  942. }
  943. }
  944. return nil
  945. }
  946. func (container *Container) networkMounts() []execdriver.Mount {
  947. var mounts []execdriver.Mount
  948. shared := container.hostConfig.NetworkMode.IsContainer()
  949. if container.ResolvConfPath != "" {
  950. label.Relabel(container.ResolvConfPath, container.MountLabel, shared)
  951. writable := !container.hostConfig.ReadonlyRootfs
  952. if m, exists := container.MountPoints["/etc/resolv.conf"]; exists {
  953. writable = m.RW
  954. }
  955. mounts = append(mounts, execdriver.Mount{
  956. Source: container.ResolvConfPath,
  957. Destination: "/etc/resolv.conf",
  958. Writable: writable,
  959. Private: true,
  960. })
  961. }
  962. if container.HostnamePath != "" {
  963. label.Relabel(container.HostnamePath, container.MountLabel, shared)
  964. writable := !container.hostConfig.ReadonlyRootfs
  965. if m, exists := container.MountPoints["/etc/hostname"]; exists {
  966. writable = m.RW
  967. }
  968. mounts = append(mounts, execdriver.Mount{
  969. Source: container.HostnamePath,
  970. Destination: "/etc/hostname",
  971. Writable: writable,
  972. Private: true,
  973. })
  974. }
  975. if container.HostsPath != "" {
  976. label.Relabel(container.HostsPath, container.MountLabel, shared)
  977. writable := !container.hostConfig.ReadonlyRootfs
  978. if m, exists := container.MountPoints["/etc/hosts"]; exists {
  979. writable = m.RW
  980. }
  981. mounts = append(mounts, execdriver.Mount{
  982. Source: container.HostsPath,
  983. Destination: "/etc/hosts",
  984. Writable: writable,
  985. Private: true,
  986. })
  987. }
  988. return mounts
  989. }
  990. func (container *Container) addBindMountPoint(name, source, destination string, rw bool) {
  991. container.MountPoints[destination] = &mountPoint{
  992. Name: name,
  993. Source: source,
  994. Destination: destination,
  995. RW: rw,
  996. }
  997. }
  998. func (container *Container) addLocalMountPoint(name, destination string, rw bool) {
  999. container.MountPoints[destination] = &mountPoint{
  1000. Name: name,
  1001. Driver: volume.DefaultDriverName,
  1002. Destination: destination,
  1003. RW: rw,
  1004. }
  1005. }
  1006. func (container *Container) addMountPointWithVolume(destination string, vol volume.Volume, rw bool) {
  1007. container.MountPoints[destination] = &mountPoint{
  1008. Name: vol.Name(),
  1009. Driver: vol.DriverName(),
  1010. Destination: destination,
  1011. RW: rw,
  1012. Volume: vol,
  1013. }
  1014. }
  1015. func (container *Container) isDestinationMounted(destination string) bool {
  1016. return container.MountPoints[destination] != nil
  1017. }
  1018. func (container *Container) prepareMountPoints() error {
  1019. for _, config := range container.MountPoints {
  1020. if len(config.Driver) > 0 {
  1021. v, err := container.daemon.createVolume(config.Name, config.Driver, nil)
  1022. if err != nil {
  1023. return err
  1024. }
  1025. config.Volume = v
  1026. }
  1027. }
  1028. return nil
  1029. }
  1030. func (container *Container) removeMountPoints(rm bool) error {
  1031. var rmErrors []string
  1032. for _, m := range container.MountPoints {
  1033. if m.Volume == nil {
  1034. continue
  1035. }
  1036. container.daemon.volumes.Decrement(m.Volume)
  1037. if rm {
  1038. err := container.daemon.volumes.Remove(m.Volume)
  1039. // ErrVolumeInUse is ignored because having this
  1040. // volume being referenced by othe container is
  1041. // not an error, but an implementation detail.
  1042. // This prevents docker from logging "ERROR: Volume in use"
  1043. // where there is another container using the volume.
  1044. if err != nil && err != ErrVolumeInUse {
  1045. rmErrors = append(rmErrors, err.Error())
  1046. }
  1047. }
  1048. }
  1049. if len(rmErrors) > 0 {
  1050. return derr.ErrorCodeRemovingVolume.WithArgs(strings.Join(rmErrors, "\n"))
  1051. }
  1052. return nil
  1053. }