container_unix.go 34 KB

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