container_linux.go 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091
  1. // +build linux
  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/network"
  17. "github.com/docker/docker/links"
  18. "github.com/docker/docker/nat"
  19. "github.com/docker/docker/pkg/archive"
  20. "github.com/docker/docker/pkg/directory"
  21. "github.com/docker/docker/pkg/ioutils"
  22. "github.com/docker/docker/pkg/stringid"
  23. "github.com/docker/docker/pkg/ulimit"
  24. "github.com/docker/docker/runconfig"
  25. "github.com/docker/docker/utils"
  26. "github.com/docker/libcontainer/configs"
  27. "github.com/docker/libcontainer/devices"
  28. "github.com/docker/libnetwork"
  29. "github.com/docker/libnetwork/netlabel"
  30. "github.com/docker/libnetwork/options"
  31. "github.com/docker/libnetwork/types"
  32. )
  33. const DefaultPathEnv = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
  34. type Container struct {
  35. CommonContainer
  36. // Fields below here are platform specific.
  37. AppArmorProfile string
  38. activeLinks map[string]*links.Link
  39. }
  40. func killProcessDirectly(container *Container) error {
  41. if _, err := container.WaitStop(10 * time.Second); err != nil {
  42. // Ensure that we don't kill ourselves
  43. if pid := container.GetPid(); pid != 0 {
  44. logrus.Infof("Container %s failed to exit within 10 seconds of kill - trying direct SIGKILL", stringid.TruncateID(container.ID))
  45. if err := syscall.Kill(pid, 9); err != nil {
  46. if err != syscall.ESRCH {
  47. return err
  48. }
  49. logrus.Debugf("Cannot kill process (pid=%d) with signal 9: no such process.", pid)
  50. }
  51. }
  52. }
  53. return nil
  54. }
  55. func (container *Container) setupLinkedContainers() ([]string, error) {
  56. var (
  57. env []string
  58. daemon = container.daemon
  59. )
  60. children, err := daemon.Children(container.Name)
  61. if err != nil {
  62. return nil, err
  63. }
  64. if len(children) > 0 {
  65. container.activeLinks = make(map[string]*links.Link, len(children))
  66. // If we encounter an error make sure that we rollback any network
  67. // config and iptables changes
  68. rollback := func() {
  69. for _, link := range container.activeLinks {
  70. link.Disable()
  71. }
  72. container.activeLinks = nil
  73. }
  74. for linkAlias, child := range children {
  75. if !child.IsRunning() {
  76. return nil, fmt.Errorf("Cannot link to a non running container: %s AS %s", child.Name, linkAlias)
  77. }
  78. link, err := links.NewLink(
  79. container.NetworkSettings.IPAddress,
  80. child.NetworkSettings.IPAddress,
  81. linkAlias,
  82. child.Config.Env,
  83. child.Config.ExposedPorts,
  84. )
  85. if err != nil {
  86. rollback()
  87. return nil, err
  88. }
  89. container.activeLinks[link.Alias()] = link
  90. if err := link.Enable(); err != nil {
  91. rollback()
  92. return nil, err
  93. }
  94. for _, envVar := range link.ToEnv() {
  95. env = append(env, envVar)
  96. }
  97. }
  98. }
  99. return env, nil
  100. }
  101. func (container *Container) createDaemonEnvironment(linkedEnv []string) []string {
  102. // if a domain name was specified, append it to the hostname (see #7851)
  103. fullHostname := container.Config.Hostname
  104. if container.Config.Domainname != "" {
  105. fullHostname = fmt.Sprintf("%s.%s", fullHostname, container.Config.Domainname)
  106. }
  107. // Setup environment
  108. env := []string{
  109. "PATH=" + DefaultPathEnv,
  110. "HOSTNAME=" + fullHostname,
  111. // Note: we don't set HOME here because it'll get autoset intelligently
  112. // based on the value of USER inside dockerinit, but only if it isn't
  113. // set already (ie, that can be overridden by setting HOME via -e or ENV
  114. // in a Dockerfile).
  115. }
  116. if container.Config.Tty {
  117. env = append(env, "TERM=xterm")
  118. }
  119. env = append(env, linkedEnv...)
  120. // because the env on the container can override certain default values
  121. // we need to replace the 'env' keys where they match and append anything
  122. // else.
  123. env = utils.ReplaceOrAppendEnvValues(env, container.Config.Env)
  124. return env
  125. }
  126. func getDevicesFromPath(deviceMapping runconfig.DeviceMapping) (devs []*configs.Device, err error) {
  127. device, err := devices.DeviceFromPath(deviceMapping.PathOnHost, deviceMapping.CgroupPermissions)
  128. // if there was no error, return the device
  129. if err == nil {
  130. device.Path = deviceMapping.PathInContainer
  131. return append(devs, device), nil
  132. }
  133. // if the device is not a device node
  134. // try to see if it's a directory holding many devices
  135. if err == devices.ErrNotADevice {
  136. // check if it is a directory
  137. if src, e := os.Stat(deviceMapping.PathOnHost); e == nil && src.IsDir() {
  138. // mount the internal devices recursively
  139. filepath.Walk(deviceMapping.PathOnHost, func(dpath string, f os.FileInfo, e error) error {
  140. childDevice, e := devices.DeviceFromPath(dpath, deviceMapping.CgroupPermissions)
  141. if e != nil {
  142. // ignore the device
  143. return nil
  144. }
  145. // add the device to userSpecified devices
  146. childDevice.Path = strings.Replace(dpath, deviceMapping.PathOnHost, deviceMapping.PathInContainer, 1)
  147. devs = append(devs, childDevice)
  148. return nil
  149. })
  150. }
  151. }
  152. if len(devs) > 0 {
  153. return devs, nil
  154. }
  155. return devs, fmt.Errorf("error gathering device information while adding custom device %q: %s", deviceMapping.PathOnHost, err)
  156. }
  157. func populateCommand(c *Container, env []string) error {
  158. var en *execdriver.Network
  159. if !c.Config.NetworkDisabled {
  160. en = &execdriver.Network{
  161. NamespacePath: c.NetworkSettings.SandboxKey,
  162. }
  163. parts := strings.SplitN(string(c.hostConfig.NetworkMode), ":", 2)
  164. if parts[0] == "container" {
  165. nc, err := c.getNetworkedContainer()
  166. if err != nil {
  167. return err
  168. }
  169. en.ContainerID = nc.ID
  170. }
  171. }
  172. ipc := &execdriver.Ipc{}
  173. if c.hostConfig.IpcMode.IsContainer() {
  174. ic, err := c.getIpcContainer()
  175. if err != nil {
  176. return err
  177. }
  178. ipc.ContainerID = ic.ID
  179. } else {
  180. ipc.HostIpc = c.hostConfig.IpcMode.IsHost()
  181. }
  182. pid := &execdriver.Pid{}
  183. pid.HostPid = c.hostConfig.PidMode.IsHost()
  184. uts := &execdriver.UTS{
  185. HostUTS: c.hostConfig.UTSMode.IsHost(),
  186. }
  187. // Build lists of devices allowed and created within the container.
  188. var userSpecifiedDevices []*configs.Device
  189. for _, deviceMapping := range c.hostConfig.Devices {
  190. devs, err := getDevicesFromPath(deviceMapping)
  191. if err != nil {
  192. return err
  193. }
  194. userSpecifiedDevices = append(userSpecifiedDevices, devs...)
  195. }
  196. allowedDevices := mergeDevices(configs.DefaultAllowedDevices, userSpecifiedDevices)
  197. autoCreatedDevices := mergeDevices(configs.DefaultAutoCreatedDevices, userSpecifiedDevices)
  198. // TODO: this can be removed after lxc-conf is fully deprecated
  199. lxcConfig, err := mergeLxcConfIntoOptions(c.hostConfig)
  200. if err != nil {
  201. return err
  202. }
  203. var rlimits []*ulimit.Rlimit
  204. ulimits := c.hostConfig.Ulimits
  205. // Merge ulimits with daemon defaults
  206. ulIdx := make(map[string]*ulimit.Ulimit)
  207. for _, ul := range ulimits {
  208. ulIdx[ul.Name] = ul
  209. }
  210. for name, ul := range c.daemon.config.Ulimits {
  211. if _, exists := ulIdx[name]; !exists {
  212. ulimits = append(ulimits, ul)
  213. }
  214. }
  215. for _, limit := range ulimits {
  216. rl, err := limit.GetRlimit()
  217. if err != nil {
  218. return err
  219. }
  220. rlimits = append(rlimits, rl)
  221. }
  222. resources := &execdriver.Resources{
  223. Memory: c.hostConfig.Memory,
  224. MemorySwap: c.hostConfig.MemorySwap,
  225. CpuShares: c.hostConfig.CpuShares,
  226. CpusetCpus: c.hostConfig.CpusetCpus,
  227. CpusetMems: c.hostConfig.CpusetMems,
  228. CpuPeriod: c.hostConfig.CpuPeriod,
  229. CpuQuota: c.hostConfig.CpuQuota,
  230. BlkioWeight: c.hostConfig.BlkioWeight,
  231. Rlimits: rlimits,
  232. OomKillDisable: c.hostConfig.OomKillDisable,
  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,
  257. CapDrop: c.hostConfig.CapDrop,
  258. ProcessConfig: processConfig,
  259. ProcessLabel: c.GetProcessLabel(),
  260. MountLabel: c.GetMountLabel(),
  261. LxcConfig: lxcConfig,
  262. AppArmorProfile: c.AppArmorProfile,
  263. CgroupParent: c.hostConfig.CgroupParent,
  264. }
  265. return nil
  266. }
  267. func mergeDevices(defaultDevices, userDevices []*configs.Device) []*configs.Device {
  268. if len(userDevices) == 0 {
  269. return defaultDevices
  270. }
  271. paths := map[string]*configs.Device{}
  272. for _, d := range userDevices {
  273. paths[d.Path] = d
  274. }
  275. var devs []*configs.Device
  276. for _, d := range defaultDevices {
  277. if _, defined := paths[d.Path]; !defined {
  278. devs = append(devs, d)
  279. }
  280. }
  281. return append(devs, userDevices...)
  282. }
  283. // GetSize, return real size, virtual size
  284. func (container *Container) GetSize() (int64, int64) {
  285. var (
  286. sizeRw, sizeRootfs int64
  287. err error
  288. driver = container.daemon.driver
  289. )
  290. if err := container.Mount(); err != nil {
  291. logrus.Errorf("Failed to compute size of container rootfs %s: %s", container.ID, err)
  292. return sizeRw, sizeRootfs
  293. }
  294. defer container.Unmount()
  295. initID := fmt.Sprintf("%s-init", container.ID)
  296. sizeRw, err = driver.DiffSize(container.ID, initID)
  297. if err != nil {
  298. logrus.Errorf("Driver %s couldn't return diff size of container %s: %s", driver, container.ID, err)
  299. // FIXME: GetSize should return an error. Not changing it now in case
  300. // there is a side-effect.
  301. sizeRw = -1
  302. }
  303. if _, err = os.Stat(container.basefs); err == nil {
  304. if sizeRootfs, err = directory.Size(container.basefs); err != nil {
  305. sizeRootfs = -1
  306. }
  307. }
  308. return sizeRw, sizeRootfs
  309. }
  310. func (container *Container) buildHostnameFile() error {
  311. hostnamePath, err := container.GetRootResourcePath("hostname")
  312. if err != nil {
  313. return err
  314. }
  315. container.HostnamePath = hostnamePath
  316. if container.Config.Domainname != "" {
  317. return ioutil.WriteFile(container.HostnamePath, []byte(fmt.Sprintf("%s.%s\n", container.Config.Hostname, container.Config.Domainname)), 0644)
  318. }
  319. return ioutil.WriteFile(container.HostnamePath, []byte(container.Config.Hostname+"\n"), 0644)
  320. }
  321. func (container *Container) buildJoinOptions() ([]libnetwork.EndpointOption, error) {
  322. var (
  323. joinOptions []libnetwork.EndpointOption
  324. err error
  325. dns []string
  326. dnsSearch []string
  327. )
  328. joinOptions = append(joinOptions, libnetwork.JoinOptionHostname(container.Config.Hostname),
  329. libnetwork.JoinOptionDomainname(container.Config.Domainname))
  330. if container.hostConfig.NetworkMode.IsHost() {
  331. joinOptions = append(joinOptions, libnetwork.JoinOptionUseDefaultSandbox())
  332. }
  333. container.HostsPath, err = container.GetRootResourcePath("hosts")
  334. if err != nil {
  335. return nil, err
  336. }
  337. joinOptions = append(joinOptions, libnetwork.JoinOptionHostsPath(container.HostsPath))
  338. container.ResolvConfPath, err = container.GetRootResourcePath("resolv.conf")
  339. if err != nil {
  340. return nil, err
  341. }
  342. joinOptions = append(joinOptions, libnetwork.JoinOptionResolvConfPath(container.ResolvConfPath))
  343. if len(container.hostConfig.Dns) > 0 {
  344. dns = container.hostConfig.Dns
  345. } else if len(container.daemon.config.Dns) > 0 {
  346. dns = container.daemon.config.Dns
  347. }
  348. for _, d := range dns {
  349. joinOptions = append(joinOptions, libnetwork.JoinOptionDNS(d))
  350. }
  351. if len(container.hostConfig.DnsSearch) > 0 {
  352. dnsSearch = container.hostConfig.DnsSearch
  353. } else if len(container.daemon.config.DnsSearch) > 0 {
  354. dnsSearch = container.daemon.config.DnsSearch
  355. }
  356. for _, ds := range dnsSearch {
  357. joinOptions = append(joinOptions, libnetwork.JoinOptionDNSSearch(ds))
  358. }
  359. if container.NetworkSettings.SecondaryIPAddresses != nil {
  360. name := container.Config.Hostname
  361. if container.Config.Domainname != "" {
  362. name = name + "." + container.Config.Domainname
  363. }
  364. for _, a := range container.NetworkSettings.SecondaryIPAddresses {
  365. joinOptions = append(joinOptions, libnetwork.JoinOptionExtraHost(name, a.Addr))
  366. }
  367. }
  368. var childEndpoints, parentEndpoints []string
  369. children, err := container.daemon.Children(container.Name)
  370. if err != nil {
  371. return nil, err
  372. }
  373. for linkAlias, child := range children {
  374. _, alias := path.Split(linkAlias)
  375. // allow access to the linked container via the alias, real name, and container hostname
  376. aliasList := alias + " " + child.Config.Hostname
  377. // only add the name if alias isn't equal to the name
  378. if alias != child.Name[1:] {
  379. aliasList = aliasList + " " + child.Name[1:]
  380. }
  381. joinOptions = append(joinOptions, libnetwork.JoinOptionExtraHost(aliasList, child.NetworkSettings.IPAddress))
  382. if child.NetworkSettings.EndpointID != "" {
  383. childEndpoints = append(childEndpoints, child.NetworkSettings.EndpointID)
  384. }
  385. }
  386. for _, extraHost := range container.hostConfig.ExtraHosts {
  387. // allow IPv6 addresses in extra hosts; only split on first ":"
  388. parts := strings.SplitN(extraHost, ":", 2)
  389. joinOptions = append(joinOptions, libnetwork.JoinOptionExtraHost(parts[0], parts[1]))
  390. }
  391. refs := container.daemon.ContainerGraph().RefPaths(container.ID)
  392. for _, ref := range refs {
  393. if ref.ParentID == "0" {
  394. continue
  395. }
  396. c, err := container.daemon.Get(ref.ParentID)
  397. if err != nil {
  398. logrus.Error(err)
  399. }
  400. if c != nil && !container.daemon.config.DisableNetwork && container.hostConfig.NetworkMode.IsPrivate() {
  401. logrus.Debugf("Update /etc/hosts of %s for alias %s with ip %s", c.ID, ref.Name, container.NetworkSettings.IPAddress)
  402. joinOptions = append(joinOptions, libnetwork.JoinOptionParentUpdate(c.NetworkSettings.EndpointID, ref.Name, container.NetworkSettings.IPAddress))
  403. if c.NetworkSettings.EndpointID != "" {
  404. parentEndpoints = append(parentEndpoints, c.NetworkSettings.EndpointID)
  405. }
  406. }
  407. }
  408. linkOptions := options.Generic{
  409. netlabel.GenericData: options.Generic{
  410. "ParentEndpoints": parentEndpoints,
  411. "ChildEndpoints": childEndpoints,
  412. },
  413. }
  414. joinOptions = append(joinOptions, libnetwork.JoinOptionGeneric(linkOptions))
  415. return joinOptions, nil
  416. }
  417. func (container *Container) buildPortMapInfo(n libnetwork.Network, ep libnetwork.Endpoint, networkSettings *network.Settings) (*network.Settings, error) {
  418. if ep == nil {
  419. return nil, fmt.Errorf("invalid endpoint while building port map info")
  420. }
  421. if networkSettings == nil {
  422. return nil, fmt.Errorf("invalid networksettings while building port map info")
  423. }
  424. driverInfo, err := ep.DriverInfo()
  425. if err != nil {
  426. return nil, err
  427. }
  428. if driverInfo == nil {
  429. // It is not an error for epInfo to be nil
  430. return networkSettings, nil
  431. }
  432. if mac, ok := driverInfo[netlabel.MacAddress]; ok {
  433. networkSettings.MacAddress = mac.(net.HardwareAddr).String()
  434. }
  435. networkSettings.Ports = nat.PortMap{}
  436. if expData, ok := driverInfo[netlabel.ExposedPorts]; ok {
  437. if exposedPorts, ok := expData.([]types.TransportPort); ok {
  438. for _, tp := range exposedPorts {
  439. natPort := nat.NewPort(tp.Proto.String(), strconv.Itoa(int(tp.Port)))
  440. networkSettings.Ports[natPort] = nil
  441. }
  442. }
  443. }
  444. mapData, ok := driverInfo[netlabel.PortMap]
  445. if !ok {
  446. return networkSettings, nil
  447. }
  448. if portMapping, ok := mapData.([]types.PortBinding); ok {
  449. for _, pp := range portMapping {
  450. natPort := nat.NewPort(pp.Proto.String(), strconv.Itoa(int(pp.Port)))
  451. natBndg := nat.PortBinding{HostIp: pp.HostIP.String(), HostPort: strconv.Itoa(int(pp.HostPort))}
  452. networkSettings.Ports[natPort] = append(networkSettings.Ports[natPort], natBndg)
  453. }
  454. }
  455. return networkSettings, nil
  456. }
  457. func (container *Container) buildEndpointInfo(n libnetwork.Network, ep libnetwork.Endpoint, networkSettings *network.Settings) (*network.Settings, error) {
  458. if ep == nil {
  459. return nil, fmt.Errorf("invalid endpoint while building port map info")
  460. }
  461. if networkSettings == nil {
  462. return nil, fmt.Errorf("invalid networksettings while building port map info")
  463. }
  464. epInfo := ep.Info()
  465. if epInfo == nil {
  466. // It is not an error to get an empty endpoint info
  467. return networkSettings, nil
  468. }
  469. ifaceList := epInfo.InterfaceList()
  470. if len(ifaceList) == 0 {
  471. return networkSettings, nil
  472. }
  473. iface := ifaceList[0]
  474. ones, _ := iface.Address().Mask.Size()
  475. networkSettings.IPAddress = iface.Address().IP.String()
  476. networkSettings.IPPrefixLen = ones
  477. if iface.AddressIPv6().IP.To16() != nil {
  478. onesv6, _ := iface.AddressIPv6().Mask.Size()
  479. networkSettings.GlobalIPv6Address = iface.AddressIPv6().IP.String()
  480. networkSettings.GlobalIPv6PrefixLen = onesv6
  481. }
  482. if len(ifaceList) == 1 {
  483. return networkSettings, nil
  484. }
  485. networkSettings.SecondaryIPAddresses = make([]network.Address, 0, len(ifaceList)-1)
  486. networkSettings.SecondaryIPv6Addresses = make([]network.Address, 0, len(ifaceList)-1)
  487. for _, iface := range ifaceList[1:] {
  488. ones, _ := iface.Address().Mask.Size()
  489. addr := network.Address{Addr: iface.Address().IP.String(), PrefixLen: ones}
  490. networkSettings.SecondaryIPAddresses = append(networkSettings.SecondaryIPAddresses, addr)
  491. if iface.AddressIPv6().IP.To16() != nil {
  492. onesv6, _ := iface.AddressIPv6().Mask.Size()
  493. addrv6 := network.Address{Addr: iface.AddressIPv6().IP.String(), PrefixLen: onesv6}
  494. networkSettings.SecondaryIPv6Addresses = append(networkSettings.SecondaryIPv6Addresses, addrv6)
  495. }
  496. }
  497. return networkSettings, nil
  498. }
  499. func (container *Container) updateJoinInfo(ep libnetwork.Endpoint) error {
  500. epInfo := ep.Info()
  501. if epInfo == nil {
  502. // It is not an error to get an empty endpoint info
  503. return nil
  504. }
  505. container.NetworkSettings.Gateway = epInfo.Gateway().String()
  506. if epInfo.GatewayIPv6().To16() != nil {
  507. container.NetworkSettings.IPv6Gateway = epInfo.GatewayIPv6().String()
  508. }
  509. container.NetworkSettings.SandboxKey = epInfo.SandboxKey()
  510. return nil
  511. }
  512. func (container *Container) updateNetworkSettings(n libnetwork.Network, ep libnetwork.Endpoint) error {
  513. networkSettings := &network.Settings{NetworkID: n.ID(), EndpointID: ep.ID()}
  514. networkSettings, err := container.buildPortMapInfo(n, ep, networkSettings)
  515. if err != nil {
  516. return err
  517. }
  518. networkSettings, err = container.buildEndpointInfo(n, ep, networkSettings)
  519. if err != nil {
  520. return err
  521. }
  522. if container.hostConfig.NetworkMode == runconfig.NetworkMode("bridge") {
  523. networkSettings.Bridge = container.daemon.config.Bridge.Iface
  524. }
  525. container.NetworkSettings = networkSettings
  526. return nil
  527. }
  528. func (container *Container) UpdateNetwork() error {
  529. n, err := container.daemon.netController.NetworkByID(container.NetworkSettings.NetworkID)
  530. if err != nil {
  531. return fmt.Errorf("error locating network id %s: %v", container.NetworkSettings.NetworkID, err)
  532. }
  533. ep, err := n.EndpointByID(container.NetworkSettings.EndpointID)
  534. if err != nil {
  535. return fmt.Errorf("error locating endpoint id %s: %v", container.NetworkSettings.EndpointID, err)
  536. }
  537. if err := ep.Leave(container.ID); err != nil {
  538. return fmt.Errorf("endpoint leave failed: %v", err)
  539. }
  540. joinOptions, err := container.buildJoinOptions()
  541. if err != nil {
  542. return fmt.Errorf("Update network failed: %v", err)
  543. }
  544. if err := ep.Join(container.ID, joinOptions...); err != nil {
  545. return fmt.Errorf("endpoint join failed: %v", err)
  546. }
  547. if err := container.updateJoinInfo(ep); err != nil {
  548. return fmt.Errorf("Updating join info failed: %v", err)
  549. }
  550. return nil
  551. }
  552. func (container *Container) buildCreateEndpointOptions() ([]libnetwork.EndpointOption, error) {
  553. var (
  554. portSpecs = make(nat.PortSet)
  555. bindings = make(nat.PortMap)
  556. pbList []types.PortBinding
  557. exposeList []types.TransportPort
  558. createOptions []libnetwork.EndpointOption
  559. )
  560. if container.Config.ExposedPorts != nil {
  561. portSpecs = container.Config.ExposedPorts
  562. }
  563. if container.hostConfig.PortBindings != nil {
  564. for p, b := range container.hostConfig.PortBindings {
  565. bindings[p] = []nat.PortBinding{}
  566. for _, bb := range b {
  567. bindings[p] = append(bindings[p], nat.PortBinding{
  568. HostIp: bb.HostIp,
  569. HostPort: bb.HostPort,
  570. })
  571. }
  572. }
  573. }
  574. container.NetworkSettings.PortMapping = nil
  575. ports := make([]nat.Port, len(portSpecs))
  576. var i int
  577. for p := range portSpecs {
  578. ports[i] = p
  579. i++
  580. }
  581. nat.SortPortMap(ports, bindings)
  582. for _, port := range ports {
  583. expose := types.TransportPort{}
  584. expose.Proto = types.ParseProtocol(port.Proto())
  585. expose.Port = uint16(port.Int())
  586. exposeList = append(exposeList, expose)
  587. pb := types.PortBinding{Port: expose.Port, Proto: expose.Proto}
  588. binding := bindings[port]
  589. for i := 0; i < len(binding); i++ {
  590. pbCopy := pb.GetCopy()
  591. pbCopy.HostPort = uint16(nat.Port(binding[i].HostPort).Int())
  592. pbCopy.HostIP = net.ParseIP(binding[i].HostIp)
  593. pbList = append(pbList, pbCopy)
  594. }
  595. if container.hostConfig.PublishAllPorts && len(binding) == 0 {
  596. pbList = append(pbList, pb)
  597. }
  598. }
  599. createOptions = append(createOptions,
  600. libnetwork.CreateOptionPortMapping(pbList),
  601. libnetwork.CreateOptionExposedPorts(exposeList))
  602. if container.Config.MacAddress != "" {
  603. mac, err := net.ParseMAC(container.Config.MacAddress)
  604. if err != nil {
  605. return nil, err
  606. }
  607. genericOption := options.Generic{
  608. netlabel.MacAddress: mac,
  609. }
  610. createOptions = append(createOptions, libnetwork.EndpointOptionGeneric(genericOption))
  611. }
  612. return createOptions, nil
  613. }
  614. func parseService(controller libnetwork.NetworkController, service string) (string, string, string) {
  615. dn := controller.Config().Daemon.DefaultNetwork
  616. dd := controller.Config().Daemon.DefaultDriver
  617. snd := strings.Split(service, ".")
  618. if len(snd) > 2 {
  619. return strings.Join(snd[:len(snd)-2], "."), snd[len(snd)-2], snd[len(snd)-1]
  620. }
  621. if len(snd) > 1 {
  622. return snd[0], snd[1], dd
  623. }
  624. return snd[0], dn, dd
  625. }
  626. func createNetwork(controller libnetwork.NetworkController, dnet string, driver string) (libnetwork.Network, error) {
  627. createOptions := []libnetwork.NetworkOption{}
  628. genericOption := options.Generic{}
  629. // Bridge driver is special due to legacy reasons
  630. if runconfig.NetworkMode(driver).IsBridge() {
  631. genericOption[netlabel.GenericData] = map[string]interface{}{
  632. "BridgeName": dnet,
  633. "AllowNonDefaultBridge": "true",
  634. }
  635. networkOption := libnetwork.NetworkOptionGeneric(genericOption)
  636. createOptions = append(createOptions, networkOption)
  637. }
  638. return controller.NewNetwork(driver, dnet, createOptions...)
  639. }
  640. func (container *Container) secondaryNetworkRequired(primaryNetworkType string) bool {
  641. switch primaryNetworkType {
  642. case "bridge", "none", "host", "container":
  643. return false
  644. }
  645. if container.Config.ExposedPorts != nil && len(container.Config.ExposedPorts) > 0 {
  646. return true
  647. }
  648. if container.hostConfig.PortBindings != nil && len(container.hostConfig.PortBindings) > 0 {
  649. return true
  650. }
  651. return false
  652. }
  653. func (container *Container) AllocateNetwork() error {
  654. mode := container.hostConfig.NetworkMode
  655. controller := container.daemon.netController
  656. if container.Config.NetworkDisabled || mode.IsContainer() {
  657. return nil
  658. }
  659. networkDriver := string(mode)
  660. service := container.Config.PublishService
  661. networkName := mode.NetworkName()
  662. if mode.IsDefault() {
  663. if service != "" {
  664. service, networkName, networkDriver = parseService(controller, service)
  665. } else {
  666. networkName = controller.Config().Daemon.DefaultNetwork
  667. networkDriver = controller.Config().Daemon.DefaultDriver
  668. }
  669. } else if service != "" {
  670. return fmt.Errorf("conflicting options: publishing a service and network mode")
  671. }
  672. if service == "" {
  673. // dot character "." has a special meaning to support SERVICE[.NETWORK] format.
  674. // For backward compatiblity, replacing "." with "-", instead of failing
  675. service = strings.Replace(container.Name, ".", "-", -1)
  676. // Service names dont like "/" in them. removing it instead of failing for backward compatibility
  677. service = strings.Replace(service, "/", "", -1)
  678. }
  679. if container.secondaryNetworkRequired(networkDriver) {
  680. // Configure Bridge as secondary network for port binding purposes
  681. if err := container.configureNetwork("bridge", service, "bridge", false); err != nil {
  682. return err
  683. }
  684. }
  685. if err := container.configureNetwork(networkName, service, networkDriver, mode.IsDefault()); err != nil {
  686. return err
  687. }
  688. return container.WriteHostConfig()
  689. }
  690. func (container *Container) configureNetwork(networkName, service, networkDriver string, canCreateNetwork bool) error {
  691. controller := container.daemon.netController
  692. n, err := controller.NetworkByName(networkName)
  693. if err != nil {
  694. if _, ok := err.(libnetwork.ErrNoSuchNetwork); !ok || !canCreateNetwork {
  695. return err
  696. }
  697. if n, err = createNetwork(controller, networkName, networkDriver); err != nil {
  698. return err
  699. }
  700. }
  701. ep, err := n.EndpointByName(service)
  702. if err != nil {
  703. if _, ok := err.(libnetwork.ErrNoSuchEndpoint); !ok {
  704. return err
  705. }
  706. createOptions, err := container.buildCreateEndpointOptions()
  707. if err != nil {
  708. return err
  709. }
  710. ep, err = n.CreateEndpoint(service, createOptions...)
  711. if err != nil {
  712. return err
  713. }
  714. }
  715. if err := container.updateNetworkSettings(n, ep); err != nil {
  716. return err
  717. }
  718. joinOptions, err := container.buildJoinOptions()
  719. if err != nil {
  720. return err
  721. }
  722. if err := ep.Join(container.ID, joinOptions...); err != nil {
  723. return err
  724. }
  725. if err := container.updateJoinInfo(ep); err != nil {
  726. return fmt.Errorf("Updating join info failed: %v", err)
  727. }
  728. return nil
  729. }
  730. func (container *Container) initializeNetworking() error {
  731. var err error
  732. // Make sure NetworkMode has an acceptable value before
  733. // initializing networking.
  734. if container.hostConfig.NetworkMode == runconfig.NetworkMode("") {
  735. container.hostConfig.NetworkMode = runconfig.NetworkMode("default")
  736. }
  737. if container.hostConfig.NetworkMode.IsContainer() {
  738. // we need to get the hosts files from the container to join
  739. nc, err := container.getNetworkedContainer()
  740. if err != nil {
  741. return err
  742. }
  743. container.HostnamePath = nc.HostnamePath
  744. container.HostsPath = nc.HostsPath
  745. container.ResolvConfPath = nc.ResolvConfPath
  746. container.Config.Hostname = nc.Config.Hostname
  747. container.Config.Domainname = nc.Config.Domainname
  748. return nil
  749. }
  750. if container.daemon.config.DisableNetwork {
  751. container.Config.NetworkDisabled = true
  752. }
  753. if container.hostConfig.NetworkMode.IsHost() {
  754. container.Config.Hostname, err = os.Hostname()
  755. if err != nil {
  756. return err
  757. }
  758. parts := strings.SplitN(container.Config.Hostname, ".", 2)
  759. if len(parts) > 1 {
  760. container.Config.Hostname = parts[0]
  761. container.Config.Domainname = parts[1]
  762. }
  763. }
  764. if err := container.AllocateNetwork(); err != nil {
  765. return err
  766. }
  767. return container.buildHostnameFile()
  768. }
  769. func (container *Container) ExportRw() (archive.Archive, error) {
  770. if container.daemon == nil {
  771. return nil, fmt.Errorf("Can't load storage driver for unregistered container %s", container.ID)
  772. }
  773. archive, err := container.daemon.Diff(container)
  774. if err != nil {
  775. return nil, err
  776. }
  777. return ioutils.NewReadCloserWrapper(archive, func() error {
  778. err := archive.Close()
  779. return err
  780. }),
  781. nil
  782. }
  783. func (container *Container) getIpcContainer() (*Container, error) {
  784. containerID := container.hostConfig.IpcMode.Container()
  785. c, err := container.daemon.Get(containerID)
  786. if err != nil {
  787. return nil, err
  788. }
  789. if !c.IsRunning() {
  790. return nil, fmt.Errorf("cannot join IPC of a non running container: %s", containerID)
  791. }
  792. return c, nil
  793. }
  794. func (container *Container) setupWorkingDirectory() error {
  795. if container.Config.WorkingDir != "" {
  796. container.Config.WorkingDir = filepath.Clean(container.Config.WorkingDir)
  797. pth, err := container.GetResourcePath(container.Config.WorkingDir)
  798. if err != nil {
  799. return err
  800. }
  801. pthInfo, err := os.Stat(pth)
  802. if err != nil {
  803. if !os.IsNotExist(err) {
  804. return err
  805. }
  806. if err := os.MkdirAll(pth, 0755); err != nil {
  807. return err
  808. }
  809. }
  810. if pthInfo != nil && !pthInfo.IsDir() {
  811. return fmt.Errorf("Cannot mkdir: %s is not a directory", container.Config.WorkingDir)
  812. }
  813. }
  814. return nil
  815. }
  816. func (container *Container) getNetworkedContainer() (*Container, error) {
  817. parts := strings.SplitN(string(container.hostConfig.NetworkMode), ":", 2)
  818. switch parts[0] {
  819. case "container":
  820. if len(parts) != 2 {
  821. return nil, fmt.Errorf("no container specified to join network")
  822. }
  823. nc, err := container.daemon.Get(parts[1])
  824. if err != nil {
  825. return nil, err
  826. }
  827. if container == nc {
  828. return nil, fmt.Errorf("cannot join own network")
  829. }
  830. if !nc.IsRunning() {
  831. return nil, fmt.Errorf("cannot join network of a non running container: %s", parts[1])
  832. }
  833. return nc, nil
  834. default:
  835. return nil, fmt.Errorf("network mode not set to container")
  836. }
  837. }
  838. func (container *Container) ReleaseNetwork() {
  839. if container.hostConfig.NetworkMode.IsContainer() || container.daemon.config.DisableNetwork {
  840. return
  841. }
  842. err := container.daemon.netController.LeaveAll(container.ID)
  843. if err != nil {
  844. logrus.Errorf("Leave all failed for %s: %v", container.ID, err)
  845. return
  846. }
  847. eid := container.NetworkSettings.EndpointID
  848. nid := container.NetworkSettings.NetworkID
  849. container.NetworkSettings = &network.Settings{}
  850. // In addition to leaving all endpoints, delete implicitly created endpoint
  851. if container.Config.PublishService == "" && eid != "" && nid != "" {
  852. n, err := container.daemon.netController.NetworkByID(nid)
  853. if err != nil {
  854. logrus.Errorf("error locating network id %s: %v", nid, err)
  855. return
  856. }
  857. ep, err := n.EndpointByID(eid)
  858. if err != nil {
  859. logrus.Errorf("error locating endpoint id %s: %v", eid, err)
  860. return
  861. }
  862. if err := ep.Delete(); err != nil {
  863. logrus.Errorf("deleting endpoint failed: %v", err)
  864. }
  865. }
  866. }
  867. func disableAllActiveLinks(container *Container) {
  868. if container.activeLinks != nil {
  869. for _, link := range container.activeLinks {
  870. link.Disable()
  871. }
  872. }
  873. }
  874. func (container *Container) DisableLink(name string) {
  875. if container.activeLinks != nil {
  876. if link, exists := container.activeLinks[name]; exists {
  877. link.Disable()
  878. delete(container.activeLinks, name)
  879. if err := container.UpdateNetwork(); err != nil {
  880. logrus.Debugf("Could not update network to remove link: %v", err)
  881. }
  882. } else {
  883. logrus.Debugf("Could not find active link for %s", name)
  884. }
  885. }
  886. }
  887. func (container *Container) UnmountVolumes(forceSyscall bool) error {
  888. var volumeMounts []mountPoint
  889. for _, mntPoint := range container.MountPoints {
  890. dest, err := container.GetResourcePath(mntPoint.Destination)
  891. if err != nil {
  892. return err
  893. }
  894. volumeMounts = append(volumeMounts, mountPoint{Destination: dest, Volume: mntPoint.Volume})
  895. }
  896. for _, mnt := range container.networkMounts() {
  897. dest, err := container.GetResourcePath(mnt.Destination)
  898. if err != nil {
  899. return err
  900. }
  901. volumeMounts = append(volumeMounts, mountPoint{Destination: dest})
  902. }
  903. for _, volumeMount := range volumeMounts {
  904. if forceSyscall {
  905. syscall.Unmount(volumeMount.Destination, 0)
  906. }
  907. if volumeMount.Volume != nil {
  908. if err := volumeMount.Volume.Unmount(); err != nil {
  909. return err
  910. }
  911. }
  912. }
  913. return nil
  914. }