bridge.go 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523
  1. //go:build linux
  2. // +build linux
  3. package bridge
  4. import (
  5. "errors"
  6. "fmt"
  7. "net"
  8. "os"
  9. "os/exec"
  10. "strconv"
  11. "sync"
  12. "github.com/docker/docker/libnetwork/datastore"
  13. "github.com/docker/docker/libnetwork/discoverapi"
  14. "github.com/docker/docker/libnetwork/driverapi"
  15. "github.com/docker/docker/libnetwork/iptables"
  16. "github.com/docker/docker/libnetwork/netlabel"
  17. "github.com/docker/docker/libnetwork/netutils"
  18. "github.com/docker/docker/libnetwork/ns"
  19. "github.com/docker/docker/libnetwork/options"
  20. "github.com/docker/docker/libnetwork/portallocator"
  21. "github.com/docker/docker/libnetwork/portmapper"
  22. "github.com/docker/docker/libnetwork/types"
  23. "github.com/sirupsen/logrus"
  24. "github.com/vishvananda/netlink"
  25. )
  26. const (
  27. networkType = "bridge"
  28. vethPrefix = "veth"
  29. vethLen = len(vethPrefix) + 7
  30. defaultContainerVethPrefix = "eth"
  31. maxAllocatePortAttempts = 10
  32. )
  33. const (
  34. // DefaultGatewayV4AuxKey represents the default-gateway configured by the user
  35. DefaultGatewayV4AuxKey = "DefaultGatewayIPv4"
  36. // DefaultGatewayV6AuxKey represents the ipv6 default-gateway configured by the user
  37. DefaultGatewayV6AuxKey = "DefaultGatewayIPv6"
  38. )
  39. type defaultBridgeNetworkConflict struct {
  40. ID string
  41. }
  42. func (d defaultBridgeNetworkConflict) Error() string {
  43. return fmt.Sprintf("Stale default bridge network %s", d.ID)
  44. }
  45. type iptableCleanFunc func() error
  46. type iptablesCleanFuncs []iptableCleanFunc
  47. // configuration info for the "bridge" driver.
  48. type configuration struct {
  49. EnableIPForwarding bool
  50. EnableIPTables bool
  51. EnableIP6Tables bool
  52. EnableUserlandProxy bool
  53. UserlandProxyPath string
  54. }
  55. // networkConfiguration for network specific configuration
  56. type networkConfiguration struct {
  57. ID string
  58. BridgeName string
  59. EnableIPv6 bool
  60. EnableIPMasquerade bool
  61. EnableICC bool
  62. InhibitIPv4 bool
  63. Mtu int
  64. DefaultBindingIP net.IP
  65. DefaultBridge bool
  66. HostIP net.IP
  67. ContainerIfacePrefix string
  68. // Internal fields set after ipam data parsing
  69. AddressIPv4 *net.IPNet
  70. AddressIPv6 *net.IPNet
  71. DefaultGatewayIPv4 net.IP
  72. DefaultGatewayIPv6 net.IP
  73. dbIndex uint64
  74. dbExists bool
  75. Internal bool
  76. BridgeIfaceCreator ifaceCreator
  77. }
  78. // ifaceCreator represents how the bridge interface was created
  79. type ifaceCreator int8
  80. const (
  81. ifaceCreatorUnknown ifaceCreator = iota
  82. ifaceCreatedByLibnetwork
  83. ifaceCreatedByUser
  84. )
  85. // endpointConfiguration represents the user specified configuration for the sandbox endpoint
  86. type endpointConfiguration struct {
  87. MacAddress net.HardwareAddr
  88. }
  89. // containerConfiguration represents the user specified configuration for a container
  90. type containerConfiguration struct {
  91. ParentEndpoints []string
  92. ChildEndpoints []string
  93. }
  94. // connectivityConfiguration represents the user specified configuration regarding the external connectivity
  95. type connectivityConfiguration struct {
  96. PortBindings []types.PortBinding
  97. ExposedPorts []types.TransportPort
  98. }
  99. type bridgeEndpoint struct {
  100. id string
  101. nid string
  102. srcName string
  103. addr *net.IPNet
  104. addrv6 *net.IPNet
  105. macAddress net.HardwareAddr
  106. config *endpointConfiguration // User specified parameters
  107. containerConfig *containerConfiguration
  108. extConnConfig *connectivityConfiguration
  109. portMapping []types.PortBinding // Operation port bindings
  110. dbIndex uint64
  111. dbExists bool
  112. }
  113. type bridgeNetwork struct {
  114. id string
  115. bridge *bridgeInterface // The bridge's L3 interface
  116. config *networkConfiguration
  117. endpoints map[string]*bridgeEndpoint // key: endpoint id
  118. portMapper *portmapper.PortMapper
  119. portMapperV6 *portmapper.PortMapper
  120. driver *driver // The network's driver
  121. iptCleanFuncs iptablesCleanFuncs
  122. sync.Mutex
  123. }
  124. type driver struct {
  125. config configuration
  126. natChain *iptables.ChainInfo
  127. filterChain *iptables.ChainInfo
  128. isolationChain1 *iptables.ChainInfo
  129. isolationChain2 *iptables.ChainInfo
  130. natChainV6 *iptables.ChainInfo
  131. filterChainV6 *iptables.ChainInfo
  132. isolationChain1V6 *iptables.ChainInfo
  133. isolationChain2V6 *iptables.ChainInfo
  134. networks map[string]*bridgeNetwork
  135. store datastore.DataStore
  136. nlh *netlink.Handle
  137. configNetwork sync.Mutex
  138. portAllocator *portallocator.PortAllocator // Overridable for tests.
  139. sync.Mutex
  140. }
  141. // New constructs a new bridge driver
  142. func newDriver() *driver {
  143. return &driver{
  144. networks: map[string]*bridgeNetwork{},
  145. portAllocator: portallocator.Get(),
  146. }
  147. }
  148. // Register registers a new instance of bridge driver.
  149. func Register(r driverapi.Registerer, config map[string]interface{}) error {
  150. d := newDriver()
  151. if err := d.configure(config); err != nil {
  152. return err
  153. }
  154. c := driverapi.Capability{
  155. DataScope: datastore.LocalScope,
  156. ConnectivityScope: datastore.LocalScope,
  157. }
  158. return r.RegisterDriver(networkType, d, c)
  159. }
  160. // Validate performs a static validation on the network configuration parameters.
  161. // Whatever can be assessed a priori before attempting any programming.
  162. func (c *networkConfiguration) Validate() error {
  163. if c.Mtu < 0 {
  164. return ErrInvalidMtu(c.Mtu)
  165. }
  166. // If bridge v4 subnet is specified
  167. if c.AddressIPv4 != nil {
  168. // If default gw is specified, it must be part of bridge subnet
  169. if c.DefaultGatewayIPv4 != nil {
  170. if !c.AddressIPv4.Contains(c.DefaultGatewayIPv4) {
  171. return &ErrInvalidGateway{}
  172. }
  173. }
  174. }
  175. // If default v6 gw is specified, AddressIPv6 must be specified and gw must belong to AddressIPv6 subnet
  176. if c.EnableIPv6 && c.DefaultGatewayIPv6 != nil {
  177. if c.AddressIPv6 == nil || !c.AddressIPv6.Contains(c.DefaultGatewayIPv6) {
  178. return &ErrInvalidGateway{}
  179. }
  180. }
  181. return nil
  182. }
  183. // Conflicts check if two NetworkConfiguration objects overlap
  184. func (c *networkConfiguration) Conflicts(o *networkConfiguration) error {
  185. if o == nil {
  186. return errors.New("same configuration")
  187. }
  188. // Also empty, because only one network with empty name is allowed
  189. if c.BridgeName == o.BridgeName {
  190. return errors.New("networks have same bridge name")
  191. }
  192. // They must be in different subnets
  193. if (c.AddressIPv4 != nil && o.AddressIPv4 != nil) &&
  194. (c.AddressIPv4.Contains(o.AddressIPv4.IP) || o.AddressIPv4.Contains(c.AddressIPv4.IP)) {
  195. return errors.New("networks have overlapping IPv4")
  196. }
  197. // They must be in different v6 subnets
  198. if (c.AddressIPv6 != nil && o.AddressIPv6 != nil) &&
  199. (c.AddressIPv6.Contains(o.AddressIPv6.IP) || o.AddressIPv6.Contains(c.AddressIPv6.IP)) {
  200. return errors.New("networks have overlapping IPv6")
  201. }
  202. return nil
  203. }
  204. func (c *networkConfiguration) fromLabels(labels map[string]string) error {
  205. var err error
  206. for label, value := range labels {
  207. switch label {
  208. case BridgeName:
  209. c.BridgeName = value
  210. case netlabel.DriverMTU:
  211. if c.Mtu, err = strconv.Atoi(value); err != nil {
  212. return parseErr(label, value, err.Error())
  213. }
  214. case netlabel.EnableIPv6:
  215. if c.EnableIPv6, err = strconv.ParseBool(value); err != nil {
  216. return parseErr(label, value, err.Error())
  217. }
  218. case EnableIPMasquerade:
  219. if c.EnableIPMasquerade, err = strconv.ParseBool(value); err != nil {
  220. return parseErr(label, value, err.Error())
  221. }
  222. case EnableICC:
  223. if c.EnableICC, err = strconv.ParseBool(value); err != nil {
  224. return parseErr(label, value, err.Error())
  225. }
  226. case InhibitIPv4:
  227. if c.InhibitIPv4, err = strconv.ParseBool(value); err != nil {
  228. return parseErr(label, value, err.Error())
  229. }
  230. case DefaultBridge:
  231. if c.DefaultBridge, err = strconv.ParseBool(value); err != nil {
  232. return parseErr(label, value, err.Error())
  233. }
  234. case DefaultBindingIP:
  235. if c.DefaultBindingIP = net.ParseIP(value); c.DefaultBindingIP == nil {
  236. return parseErr(label, value, "nil ip")
  237. }
  238. case netlabel.ContainerIfacePrefix:
  239. c.ContainerIfacePrefix = value
  240. case netlabel.HostIP:
  241. if c.HostIP = net.ParseIP(value); c.HostIP == nil {
  242. return parseErr(label, value, "nil ip")
  243. }
  244. }
  245. }
  246. return nil
  247. }
  248. func parseErr(label, value, errString string) error {
  249. return types.BadRequestErrorf("failed to parse %s value: %v (%s)", label, value, errString)
  250. }
  251. func (n *bridgeNetwork) registerIptCleanFunc(clean iptableCleanFunc) {
  252. n.iptCleanFuncs = append(n.iptCleanFuncs, clean)
  253. }
  254. func (n *bridgeNetwork) getDriverChains(version iptables.IPVersion) (*iptables.ChainInfo, *iptables.ChainInfo, *iptables.ChainInfo, *iptables.ChainInfo, error) {
  255. n.Lock()
  256. defer n.Unlock()
  257. if n.driver == nil {
  258. return nil, nil, nil, nil, types.BadRequestErrorf("no driver found")
  259. }
  260. if version == iptables.IPv6 {
  261. return n.driver.natChainV6, n.driver.filterChainV6, n.driver.isolationChain1V6, n.driver.isolationChain2V6, nil
  262. }
  263. return n.driver.natChain, n.driver.filterChain, n.driver.isolationChain1, n.driver.isolationChain2, nil
  264. }
  265. func (n *bridgeNetwork) getNetworkBridgeName() string {
  266. n.Lock()
  267. config := n.config
  268. n.Unlock()
  269. return config.BridgeName
  270. }
  271. func (n *bridgeNetwork) getEndpoint(eid string) (*bridgeEndpoint, error) {
  272. n.Lock()
  273. defer n.Unlock()
  274. if eid == "" {
  275. return nil, InvalidEndpointIDError(eid)
  276. }
  277. if ep, ok := n.endpoints[eid]; ok {
  278. return ep, nil
  279. }
  280. return nil, nil
  281. }
  282. // Install/Removes the iptables rules needed to isolate this network
  283. // from each of the other networks
  284. func (n *bridgeNetwork) isolateNetwork(enable bool) error {
  285. n.Lock()
  286. thisConfig := n.config
  287. n.Unlock()
  288. if thisConfig.Internal {
  289. return nil
  290. }
  291. // Install the rules to isolate this network against each of the other networks
  292. if n.driver.config.EnableIP6Tables {
  293. err := setINC(iptables.IPv6, thisConfig.BridgeName, enable)
  294. if err != nil {
  295. return err
  296. }
  297. }
  298. if n.driver.config.EnableIPTables {
  299. return setINC(iptables.IPv4, thisConfig.BridgeName, enable)
  300. }
  301. return nil
  302. }
  303. func (d *driver) configure(option map[string]interface{}) error {
  304. var (
  305. config configuration
  306. err error
  307. natChain *iptables.ChainInfo
  308. filterChain *iptables.ChainInfo
  309. isolationChain1 *iptables.ChainInfo
  310. isolationChain2 *iptables.ChainInfo
  311. natChainV6 *iptables.ChainInfo
  312. filterChainV6 *iptables.ChainInfo
  313. isolationChain1V6 *iptables.ChainInfo
  314. isolationChain2V6 *iptables.ChainInfo
  315. )
  316. switch opt := option[netlabel.GenericData].(type) {
  317. case options.Generic:
  318. opaqueConfig, err := options.GenerateFromModel(opt, &configuration{})
  319. if err != nil {
  320. return err
  321. }
  322. config = *opaqueConfig.(*configuration)
  323. case *configuration:
  324. config = *opt
  325. case nil:
  326. // No GenericData option set. Use defaults.
  327. default:
  328. return &ErrInvalidDriverConfig{}
  329. }
  330. if config.EnableIPTables || config.EnableIP6Tables {
  331. if _, err := os.Stat("/proc/sys/net/bridge"); err != nil {
  332. if out, err := exec.Command("modprobe", "-va", "bridge", "br_netfilter").CombinedOutput(); err != nil {
  333. logrus.Warnf("Running modprobe bridge br_netfilter failed with message: %s, error: %v", out, err)
  334. }
  335. }
  336. }
  337. if config.EnableIPTables {
  338. removeIPChains(iptables.IPv4)
  339. natChain, filterChain, isolationChain1, isolationChain2, err = setupIPChains(config, iptables.IPv4)
  340. if err != nil {
  341. return err
  342. }
  343. // Make sure on firewall reload, first thing being re-played is chains creation
  344. iptables.OnReloaded(func() {
  345. logrus.Debugf("Recreating iptables chains on firewall reload")
  346. if _, _, _, _, err := setupIPChains(config, iptables.IPv4); err != nil {
  347. logrus.WithError(err).Error("Error reloading iptables chains")
  348. }
  349. })
  350. }
  351. if config.EnableIP6Tables {
  352. removeIPChains(iptables.IPv6)
  353. natChainV6, filterChainV6, isolationChain1V6, isolationChain2V6, err = setupIPChains(config, iptables.IPv6)
  354. if err != nil {
  355. return err
  356. }
  357. // Make sure on firewall reload, first thing being re-played is chains creation
  358. iptables.OnReloaded(func() {
  359. logrus.Debugf("Recreating ip6tables chains on firewall reload")
  360. if _, _, _, _, err := setupIPChains(config, iptables.IPv6); err != nil {
  361. logrus.WithError(err).Error("Error reloading ip6tables chains")
  362. }
  363. })
  364. }
  365. if config.EnableIPForwarding {
  366. err = setupIPForwarding(config.EnableIPTables, config.EnableIP6Tables)
  367. if err != nil {
  368. logrus.Warn(err)
  369. return err
  370. }
  371. }
  372. d.Lock()
  373. d.natChain = natChain
  374. d.filterChain = filterChain
  375. d.isolationChain1 = isolationChain1
  376. d.isolationChain2 = isolationChain2
  377. d.natChainV6 = natChainV6
  378. d.filterChainV6 = filterChainV6
  379. d.isolationChain1V6 = isolationChain1V6
  380. d.isolationChain2V6 = isolationChain2V6
  381. d.config = config
  382. d.Unlock()
  383. err = d.initStore(option)
  384. if err != nil {
  385. return err
  386. }
  387. return nil
  388. }
  389. func (d *driver) getNetwork(id string) (*bridgeNetwork, error) {
  390. d.Lock()
  391. defer d.Unlock()
  392. if id == "" {
  393. return nil, types.BadRequestErrorf("invalid network id: %s", id)
  394. }
  395. if nw, ok := d.networks[id]; ok {
  396. return nw, nil
  397. }
  398. return nil, types.NotFoundErrorf("network not found: %s", id)
  399. }
  400. func parseNetworkGenericOptions(data interface{}) (*networkConfiguration, error) {
  401. var (
  402. err error
  403. config *networkConfiguration
  404. )
  405. switch opt := data.(type) {
  406. case *networkConfiguration:
  407. config = opt
  408. case map[string]string:
  409. config = &networkConfiguration{
  410. EnableICC: true,
  411. EnableIPMasquerade: true,
  412. }
  413. err = config.fromLabels(opt)
  414. case options.Generic:
  415. var opaqueConfig interface{}
  416. if opaqueConfig, err = options.GenerateFromModel(opt, config); err == nil {
  417. config = opaqueConfig.(*networkConfiguration)
  418. }
  419. default:
  420. err = types.BadRequestErrorf("do not recognize network configuration format: %T", opt)
  421. }
  422. return config, err
  423. }
  424. func (c *networkConfiguration) processIPAM(id string, ipamV4Data, ipamV6Data []driverapi.IPAMData) error {
  425. if len(ipamV4Data) > 1 || len(ipamV6Data) > 1 {
  426. return types.ForbiddenErrorf("bridge driver doesn't support multiple subnets")
  427. }
  428. if len(ipamV4Data) == 0 {
  429. return types.BadRequestErrorf("bridge network %s requires ipv4 configuration", id)
  430. }
  431. if ipamV4Data[0].Gateway != nil {
  432. c.AddressIPv4 = types.GetIPNetCopy(ipamV4Data[0].Gateway)
  433. }
  434. if gw, ok := ipamV4Data[0].AuxAddresses[DefaultGatewayV4AuxKey]; ok {
  435. c.DefaultGatewayIPv4 = gw.IP
  436. }
  437. if len(ipamV6Data) > 0 {
  438. c.AddressIPv6 = ipamV6Data[0].Pool
  439. if ipamV6Data[0].Gateway != nil {
  440. c.AddressIPv6 = types.GetIPNetCopy(ipamV6Data[0].Gateway)
  441. }
  442. if gw, ok := ipamV6Data[0].AuxAddresses[DefaultGatewayV6AuxKey]; ok {
  443. c.DefaultGatewayIPv6 = gw.IP
  444. }
  445. }
  446. return nil
  447. }
  448. func parseNetworkOptions(id string, option options.Generic) (*networkConfiguration, error) {
  449. var (
  450. err error
  451. config = &networkConfiguration{}
  452. )
  453. // Parse generic label first, config will be re-assigned
  454. if genData, ok := option[netlabel.GenericData]; ok && genData != nil {
  455. if config, err = parseNetworkGenericOptions(genData); err != nil {
  456. return nil, err
  457. }
  458. }
  459. // Process well-known labels next
  460. if val, ok := option[netlabel.EnableIPv6]; ok {
  461. config.EnableIPv6 = val.(bool)
  462. }
  463. if val, ok := option[netlabel.Internal]; ok {
  464. if internal, ok := val.(bool); ok && internal {
  465. config.Internal = true
  466. }
  467. }
  468. // Finally validate the configuration
  469. if err = config.Validate(); err != nil {
  470. return nil, err
  471. }
  472. if config.BridgeName == "" && !config.DefaultBridge {
  473. config.BridgeName = "br-" + id[:12]
  474. }
  475. exists, err := bridgeInterfaceExists(config.BridgeName)
  476. if err != nil {
  477. return nil, err
  478. }
  479. if !exists {
  480. config.BridgeIfaceCreator = ifaceCreatedByLibnetwork
  481. } else {
  482. config.BridgeIfaceCreator = ifaceCreatedByUser
  483. }
  484. config.ID = id
  485. return config, nil
  486. }
  487. // Return a slice of networks over which caller can iterate safely
  488. func (d *driver) getNetworks() []*bridgeNetwork {
  489. d.Lock()
  490. defer d.Unlock()
  491. ls := make([]*bridgeNetwork, 0, len(d.networks))
  492. for _, nw := range d.networks {
  493. ls = append(ls, nw)
  494. }
  495. return ls
  496. }
  497. func (d *driver) NetworkAllocate(id string, option map[string]string, ipV4Data, ipV6Data []driverapi.IPAMData) (map[string]string, error) {
  498. return nil, types.NotImplementedErrorf("not implemented")
  499. }
  500. func (d *driver) NetworkFree(id string) error {
  501. return types.NotImplementedErrorf("not implemented")
  502. }
  503. func (d *driver) EventNotify(etype driverapi.EventType, nid, tableName, key string, value []byte) {
  504. }
  505. func (d *driver) DecodeTableEntry(tablename string, key string, value []byte) (string, map[string]string) {
  506. return "", nil
  507. }
  508. // Create a new network using bridge plugin
  509. func (d *driver) CreateNetwork(id string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error {
  510. if len(ipV4Data) == 0 || ipV4Data[0].Pool.String() == "0.0.0.0/0" {
  511. return types.BadRequestErrorf("ipv4 pool is empty")
  512. }
  513. // Sanity checks
  514. d.Lock()
  515. if _, ok := d.networks[id]; ok {
  516. d.Unlock()
  517. return types.ForbiddenErrorf("network %s exists", id)
  518. }
  519. d.Unlock()
  520. // Parse and validate the config. It should not be conflict with existing networks' config
  521. config, err := parseNetworkOptions(id, option)
  522. if err != nil {
  523. return err
  524. }
  525. if err = config.processIPAM(id, ipV4Data, ipV6Data); err != nil {
  526. return err
  527. }
  528. // start the critical section, from this point onward we are dealing with the list of networks
  529. // so to be consistent we cannot allow that the list changes
  530. d.configNetwork.Lock()
  531. defer d.configNetwork.Unlock()
  532. // check network conflicts
  533. if err = d.checkConflict(config); err != nil {
  534. nerr, ok := err.(defaultBridgeNetworkConflict)
  535. if !ok {
  536. return err
  537. }
  538. // Got a conflict with a stale default network, clean that up and continue
  539. logrus.Warn(nerr)
  540. if err := d.deleteNetwork(nerr.ID); err != nil {
  541. logrus.WithError(err).Debug("Error while cleaning up network on conflict")
  542. }
  543. }
  544. // there is no conflict, now create the network
  545. if err = d.createNetwork(config); err != nil {
  546. return err
  547. }
  548. return d.storeUpdate(config)
  549. }
  550. func (d *driver) checkConflict(config *networkConfiguration) error {
  551. networkList := d.getNetworks()
  552. for _, nw := range networkList {
  553. nw.Lock()
  554. nwConfig := nw.config
  555. nw.Unlock()
  556. if err := nwConfig.Conflicts(config); err != nil {
  557. if nwConfig.DefaultBridge {
  558. // We encountered and identified a stale default network
  559. // We must delete it as libnetwork is the source of truth
  560. // The default network being created must be the only one
  561. // This can happen only from docker 1.12 on ward
  562. logrus.Infof("Found stale default bridge network %s (%s)", nwConfig.ID, nwConfig.BridgeName)
  563. return defaultBridgeNetworkConflict{nwConfig.ID}
  564. }
  565. return types.ForbiddenErrorf("cannot create network %s (%s): conflicts with network %s (%s): %s",
  566. config.ID, config.BridgeName, nwConfig.ID, nwConfig.BridgeName, err.Error())
  567. }
  568. }
  569. return nil
  570. }
  571. func (d *driver) createNetwork(config *networkConfiguration) (err error) {
  572. // Initialize handle when needed
  573. d.Lock()
  574. if d.nlh == nil {
  575. d.nlh = ns.NlHandle()
  576. }
  577. d.Unlock()
  578. // Create or retrieve the bridge L3 interface
  579. bridgeIface, err := newInterface(d.nlh, config)
  580. if err != nil {
  581. return err
  582. }
  583. // Create and set network handler in driver
  584. network := &bridgeNetwork{
  585. id: config.ID,
  586. endpoints: make(map[string]*bridgeEndpoint),
  587. config: config,
  588. portMapper: portmapper.NewWithPortAllocator(d.portAllocator, d.config.UserlandProxyPath),
  589. portMapperV6: portmapper.NewWithPortAllocator(d.portAllocator, d.config.UserlandProxyPath),
  590. bridge: bridgeIface,
  591. driver: d,
  592. }
  593. d.Lock()
  594. d.networks[config.ID] = network
  595. d.Unlock()
  596. // On failure make sure to reset driver network handler to nil
  597. defer func() {
  598. if err != nil {
  599. d.Lock()
  600. delete(d.networks, config.ID)
  601. d.Unlock()
  602. }
  603. }()
  604. // Add inter-network communication rules.
  605. setupNetworkIsolationRules := func(config *networkConfiguration, i *bridgeInterface) error {
  606. if err := network.isolateNetwork(true); err != nil {
  607. if err = network.isolateNetwork(false); err != nil {
  608. logrus.Warnf("Failed on removing the inter-network iptables rules on cleanup: %v", err)
  609. }
  610. return err
  611. }
  612. // register the cleanup function
  613. network.registerIptCleanFunc(func() error {
  614. return network.isolateNetwork(false)
  615. })
  616. return nil
  617. }
  618. // Prepare the bridge setup configuration
  619. bridgeSetup := newBridgeSetup(config, bridgeIface)
  620. // If the bridge interface doesn't exist, we need to start the setup steps
  621. // by creating a new device and assigning it an IPv4 address.
  622. bridgeAlreadyExists := bridgeIface.exists()
  623. if !bridgeAlreadyExists {
  624. bridgeSetup.queueStep(setupDevice)
  625. bridgeSetup.queueStep(setupDefaultSysctl)
  626. }
  627. // For the default bridge, set expected sysctls
  628. if config.DefaultBridge {
  629. bridgeSetup.queueStep(setupDefaultSysctl)
  630. }
  631. // Even if a bridge exists try to setup IPv4.
  632. bridgeSetup.queueStep(setupBridgeIPv4)
  633. enableIPv6Forwarding := d.config.EnableIPForwarding && config.AddressIPv6 != nil
  634. // Conditionally queue setup steps depending on configuration values.
  635. for _, step := range []struct {
  636. Condition bool
  637. Fn setupStep
  638. }{
  639. // Enable IPv6 on the bridge if required. We do this even for a
  640. // previously existing bridge, as it may be here from a previous
  641. // installation where IPv6 wasn't supported yet and needs to be
  642. // assigned an IPv6 link-local address.
  643. {config.EnableIPv6, setupBridgeIPv6},
  644. // We ensure that the bridge has the expectedIPv4 and IPv6 addresses in
  645. // the case of a previously existing device.
  646. {bridgeAlreadyExists && !config.InhibitIPv4, setupVerifyAndReconcile},
  647. // Enable IPv6 Forwarding
  648. {enableIPv6Forwarding, setupIPv6Forwarding},
  649. // Setup Loopback Addresses Routing
  650. {!d.config.EnableUserlandProxy, setupLoopbackAddressesRouting},
  651. // Setup IPTables.
  652. {d.config.EnableIPTables, network.setupIP4Tables},
  653. // Setup IP6Tables.
  654. {config.EnableIPv6 && d.config.EnableIP6Tables, network.setupIP6Tables},
  655. // We want to track firewalld configuration so that
  656. // if it is started/reloaded, the rules can be applied correctly
  657. {d.config.EnableIPTables, network.setupFirewalld},
  658. // same for IPv6
  659. {config.EnableIPv6 && d.config.EnableIP6Tables, network.setupFirewalld6},
  660. // Setup DefaultGatewayIPv4
  661. {config.DefaultGatewayIPv4 != nil, setupGatewayIPv4},
  662. // Setup DefaultGatewayIPv6
  663. {config.DefaultGatewayIPv6 != nil, setupGatewayIPv6},
  664. // Add inter-network communication rules.
  665. {d.config.EnableIPTables, setupNetworkIsolationRules},
  666. // Configure bridge networking filtering if ICC is off and IP tables are enabled
  667. {!config.EnableICC && d.config.EnableIPTables, setupBridgeNetFiltering},
  668. } {
  669. if step.Condition {
  670. bridgeSetup.queueStep(step.Fn)
  671. }
  672. }
  673. // Apply the prepared list of steps, and abort at the first error.
  674. bridgeSetup.queueStep(setupDeviceUp)
  675. return bridgeSetup.apply()
  676. }
  677. func (d *driver) DeleteNetwork(nid string) error {
  678. d.configNetwork.Lock()
  679. defer d.configNetwork.Unlock()
  680. return d.deleteNetwork(nid)
  681. }
  682. func (d *driver) deleteNetwork(nid string) error {
  683. var err error
  684. // Get network handler and remove it from driver
  685. d.Lock()
  686. n, ok := d.networks[nid]
  687. d.Unlock()
  688. if !ok {
  689. return types.InternalMaskableErrorf("network %s does not exist", nid)
  690. }
  691. n.Lock()
  692. config := n.config
  693. n.Unlock()
  694. // delele endpoints belong to this network
  695. for _, ep := range n.endpoints {
  696. if err := n.releasePorts(ep); err != nil {
  697. logrus.Warn(err)
  698. }
  699. if link, err := d.nlh.LinkByName(ep.srcName); err == nil {
  700. if err := d.nlh.LinkDel(link); err != nil {
  701. logrus.WithError(err).Errorf("Failed to delete interface (%s)'s link on endpoint (%s) delete", ep.srcName, ep.id)
  702. }
  703. }
  704. if err := d.storeDelete(ep); err != nil {
  705. logrus.Warnf("Failed to remove bridge endpoint %.7s from store: %v", ep.id, err)
  706. }
  707. }
  708. d.Lock()
  709. delete(d.networks, nid)
  710. d.Unlock()
  711. // On failure set network handler back in driver, but
  712. // only if is not already taken over by some other thread
  713. defer func() {
  714. if err != nil {
  715. d.Lock()
  716. if _, ok := d.networks[nid]; !ok {
  717. d.networks[nid] = n
  718. }
  719. d.Unlock()
  720. }
  721. }()
  722. switch config.BridgeIfaceCreator {
  723. case ifaceCreatedByLibnetwork, ifaceCreatorUnknown:
  724. // We only delete the bridge if it was created by the bridge driver and
  725. // it is not the default one (to keep the backward compatible behavior.)
  726. if !config.DefaultBridge {
  727. if err := d.nlh.LinkDel(n.bridge.Link); err != nil {
  728. logrus.Warnf("Failed to remove bridge interface %s on network %s delete: %v", config.BridgeName, nid, err)
  729. }
  730. }
  731. case ifaceCreatedByUser:
  732. // Don't delete the bridge interface if it was not created by libnetwork.
  733. }
  734. // clean all relevant iptables rules
  735. for _, cleanFunc := range n.iptCleanFuncs {
  736. if errClean := cleanFunc(); errClean != nil {
  737. logrus.Warnf("Failed to clean iptables rules for bridge network: %v", errClean)
  738. }
  739. }
  740. return d.storeDelete(config)
  741. }
  742. func addToBridge(nlh *netlink.Handle, ifaceName, bridgeName string) error {
  743. lnk, err := nlh.LinkByName(ifaceName)
  744. if err != nil {
  745. return fmt.Errorf("could not find interface %s: %v", ifaceName, err)
  746. }
  747. if err := nlh.LinkSetMaster(lnk, &netlink.Bridge{LinkAttrs: netlink.LinkAttrs{Name: bridgeName}}); err != nil {
  748. logrus.WithError(err).Errorf("Failed to add %s to bridge via netlink", ifaceName)
  749. return err
  750. }
  751. return nil
  752. }
  753. func setHairpinMode(nlh *netlink.Handle, link netlink.Link, enable bool) error {
  754. err := nlh.LinkSetHairpin(link, enable)
  755. if err != nil {
  756. return fmt.Errorf("unable to set hairpin mode on %s via netlink: %v",
  757. link.Attrs().Name, err)
  758. }
  759. return nil
  760. }
  761. func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo, epOptions map[string]interface{}) error {
  762. if ifInfo == nil {
  763. return errors.New("invalid interface info passed")
  764. }
  765. // Get the network handler and make sure it exists
  766. d.Lock()
  767. n, ok := d.networks[nid]
  768. dconfig := d.config
  769. d.Unlock()
  770. if !ok {
  771. return types.NotFoundErrorf("network %s does not exist", nid)
  772. }
  773. if n == nil {
  774. return driverapi.ErrNoNetwork(nid)
  775. }
  776. // Sanity check
  777. n.Lock()
  778. if n.id != nid {
  779. n.Unlock()
  780. return InvalidNetworkIDError(nid)
  781. }
  782. n.Unlock()
  783. // Check if endpoint id is good and retrieve correspondent endpoint
  784. ep, err := n.getEndpoint(eid)
  785. if err != nil {
  786. return err
  787. }
  788. // Endpoint with that id exists either on desired or other sandbox
  789. if ep != nil {
  790. return driverapi.ErrEndpointExists(eid)
  791. }
  792. // Try to convert the options to endpoint configuration
  793. epConfig, err := parseEndpointOptions(epOptions)
  794. if err != nil {
  795. return err
  796. }
  797. // Create and add the endpoint
  798. n.Lock()
  799. endpoint := &bridgeEndpoint{id: eid, nid: nid, config: epConfig}
  800. n.endpoints[eid] = endpoint
  801. n.Unlock()
  802. // On failure make sure to remove the endpoint
  803. defer func() {
  804. if err != nil {
  805. n.Lock()
  806. delete(n.endpoints, eid)
  807. n.Unlock()
  808. }
  809. }()
  810. // Generate a name for what will be the host side pipe interface
  811. hostIfName, err := netutils.GenerateIfaceName(d.nlh, vethPrefix, vethLen)
  812. if err != nil {
  813. return err
  814. }
  815. // Generate a name for what will be the sandbox side pipe interface
  816. containerIfName, err := netutils.GenerateIfaceName(d.nlh, vethPrefix, vethLen)
  817. if err != nil {
  818. return err
  819. }
  820. // Generate and add the interface pipe host <-> sandbox
  821. veth := &netlink.Veth{
  822. LinkAttrs: netlink.LinkAttrs{Name: hostIfName, TxQLen: 0},
  823. PeerName: containerIfName}
  824. if err = d.nlh.LinkAdd(veth); err != nil {
  825. return types.InternalErrorf("failed to add the host (%s) <=> sandbox (%s) pair interfaces: %v", hostIfName, containerIfName, err)
  826. }
  827. // Get the host side pipe interface handler
  828. host, err := d.nlh.LinkByName(hostIfName)
  829. if err != nil {
  830. return types.InternalErrorf("failed to find host side interface %s: %v", hostIfName, err)
  831. }
  832. defer func() {
  833. if err != nil {
  834. if err := d.nlh.LinkDel(host); err != nil {
  835. logrus.WithError(err).Warnf("Failed to delete host side interface (%s)'s link", hostIfName)
  836. }
  837. }
  838. }()
  839. // Get the sandbox side pipe interface handler
  840. sbox, err := d.nlh.LinkByName(containerIfName)
  841. if err != nil {
  842. return types.InternalErrorf("failed to find sandbox side interface %s: %v", containerIfName, err)
  843. }
  844. defer func() {
  845. if err != nil {
  846. if err := d.nlh.LinkDel(sbox); err != nil {
  847. logrus.WithError(err).Warnf("Failed to delete sandbox side interface (%s)'s link", containerIfName)
  848. }
  849. }
  850. }()
  851. n.Lock()
  852. config := n.config
  853. n.Unlock()
  854. // Add bridge inherited attributes to pipe interfaces
  855. if config.Mtu != 0 {
  856. err = d.nlh.LinkSetMTU(host, config.Mtu)
  857. if err != nil {
  858. return types.InternalErrorf("failed to set MTU on host interface %s: %v", hostIfName, err)
  859. }
  860. err = d.nlh.LinkSetMTU(sbox, config.Mtu)
  861. if err != nil {
  862. return types.InternalErrorf("failed to set MTU on sandbox interface %s: %v", containerIfName, err)
  863. }
  864. }
  865. // Attach host side pipe interface into the bridge
  866. if err = addToBridge(d.nlh, hostIfName, config.BridgeName); err != nil {
  867. return fmt.Errorf("adding interface %s to bridge %s failed: %v", hostIfName, config.BridgeName, err)
  868. }
  869. if !dconfig.EnableUserlandProxy {
  870. err = setHairpinMode(d.nlh, host, true)
  871. if err != nil {
  872. return err
  873. }
  874. }
  875. // Store the sandbox side pipe interface parameters
  876. endpoint.srcName = containerIfName
  877. endpoint.macAddress = ifInfo.MacAddress()
  878. endpoint.addr = ifInfo.Address()
  879. endpoint.addrv6 = ifInfo.AddressIPv6()
  880. // Set the sbox's MAC if not provided. If specified, use the one configured by user, otherwise generate one based on IP.
  881. if endpoint.macAddress == nil {
  882. endpoint.macAddress = electMacAddress(epConfig, endpoint.addr.IP)
  883. if err = ifInfo.SetMacAddress(endpoint.macAddress); err != nil {
  884. return err
  885. }
  886. }
  887. // Up the host interface after finishing all netlink configuration
  888. if err = d.nlh.LinkSetUp(host); err != nil {
  889. return fmt.Errorf("could not set link up for host interface %s: %v", hostIfName, err)
  890. }
  891. if endpoint.addrv6 == nil && config.EnableIPv6 {
  892. var ip6 net.IP
  893. network := n.bridge.bridgeIPv6
  894. if config.AddressIPv6 != nil {
  895. network = config.AddressIPv6
  896. }
  897. ones, _ := network.Mask.Size()
  898. if ones > 80 {
  899. err = types.ForbiddenErrorf("Cannot self generate an IPv6 address on network %v: At least 48 host bits are needed.", network)
  900. return err
  901. }
  902. ip6 = make(net.IP, len(network.IP))
  903. copy(ip6, network.IP)
  904. for i, h := range endpoint.macAddress {
  905. ip6[i+10] = h
  906. }
  907. endpoint.addrv6 = &net.IPNet{IP: ip6, Mask: network.Mask}
  908. if err = ifInfo.SetIPAddress(endpoint.addrv6); err != nil {
  909. return err
  910. }
  911. }
  912. if err = d.storeUpdate(endpoint); err != nil {
  913. return fmt.Errorf("failed to save bridge endpoint %.7s to store: %v", endpoint.id, err)
  914. }
  915. return nil
  916. }
  917. func (d *driver) DeleteEndpoint(nid, eid string) error {
  918. var err error
  919. // Get the network handler and make sure it exists
  920. d.Lock()
  921. n, ok := d.networks[nid]
  922. d.Unlock()
  923. if !ok {
  924. return types.InternalMaskableErrorf("network %s does not exist", nid)
  925. }
  926. if n == nil {
  927. return driverapi.ErrNoNetwork(nid)
  928. }
  929. // Sanity Check
  930. n.Lock()
  931. if n.id != nid {
  932. n.Unlock()
  933. return InvalidNetworkIDError(nid)
  934. }
  935. n.Unlock()
  936. // Check endpoint id and if an endpoint is actually there
  937. ep, err := n.getEndpoint(eid)
  938. if err != nil {
  939. return err
  940. }
  941. if ep == nil {
  942. return EndpointNotFoundError(eid)
  943. }
  944. // Remove it
  945. n.Lock()
  946. delete(n.endpoints, eid)
  947. n.Unlock()
  948. // On failure make sure to set back ep in n.endpoints, but only
  949. // if it hasn't been taken over already by some other thread.
  950. defer func() {
  951. if err != nil {
  952. n.Lock()
  953. if _, ok := n.endpoints[eid]; !ok {
  954. n.endpoints[eid] = ep
  955. }
  956. n.Unlock()
  957. }
  958. }()
  959. // Try removal of link. Discard error: it is a best effort.
  960. // Also make sure defer does not see this error either.
  961. if link, err := d.nlh.LinkByName(ep.srcName); err == nil {
  962. if err := d.nlh.LinkDel(link); err != nil {
  963. logrus.WithError(err).Errorf("Failed to delete interface (%s)'s link on endpoint (%s) delete", ep.srcName, ep.id)
  964. }
  965. }
  966. if err := d.storeDelete(ep); err != nil {
  967. logrus.Warnf("Failed to remove bridge endpoint %.7s from store: %v", ep.id, err)
  968. }
  969. return nil
  970. }
  971. func (d *driver) EndpointOperInfo(nid, eid string) (map[string]interface{}, error) {
  972. // Get the network handler and make sure it exists
  973. d.Lock()
  974. n, ok := d.networks[nid]
  975. d.Unlock()
  976. if !ok {
  977. return nil, types.NotFoundErrorf("network %s does not exist", nid)
  978. }
  979. if n == nil {
  980. return nil, driverapi.ErrNoNetwork(nid)
  981. }
  982. // Sanity check
  983. n.Lock()
  984. if n.id != nid {
  985. n.Unlock()
  986. return nil, InvalidNetworkIDError(nid)
  987. }
  988. n.Unlock()
  989. // Check if endpoint id is good and retrieve correspondent endpoint
  990. ep, err := n.getEndpoint(eid)
  991. if err != nil {
  992. return nil, err
  993. }
  994. if ep == nil {
  995. return nil, driverapi.ErrNoEndpoint(eid)
  996. }
  997. m := make(map[string]interface{})
  998. if ep.extConnConfig != nil && ep.extConnConfig.ExposedPorts != nil {
  999. // Return a copy of the config data
  1000. epc := make([]types.TransportPort, 0, len(ep.extConnConfig.ExposedPorts))
  1001. for _, tp := range ep.extConnConfig.ExposedPorts {
  1002. epc = append(epc, tp.GetCopy())
  1003. }
  1004. m[netlabel.ExposedPorts] = epc
  1005. }
  1006. if ep.portMapping != nil {
  1007. // Return a copy of the operational data
  1008. pmc := make([]types.PortBinding, 0, len(ep.portMapping))
  1009. for _, pm := range ep.portMapping {
  1010. pmc = append(pmc, pm.GetCopy())
  1011. }
  1012. m[netlabel.PortMap] = pmc
  1013. }
  1014. if len(ep.macAddress) != 0 {
  1015. m[netlabel.MacAddress] = ep.macAddress
  1016. }
  1017. return m, nil
  1018. }
  1019. // Join method is invoked when a Sandbox is attached to an endpoint.
  1020. func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error {
  1021. network, err := d.getNetwork(nid)
  1022. if err != nil {
  1023. return err
  1024. }
  1025. endpoint, err := network.getEndpoint(eid)
  1026. if err != nil {
  1027. return err
  1028. }
  1029. if endpoint == nil {
  1030. return EndpointNotFoundError(eid)
  1031. }
  1032. endpoint.containerConfig, err = parseContainerOptions(options)
  1033. if err != nil {
  1034. return err
  1035. }
  1036. iNames := jinfo.InterfaceName()
  1037. containerVethPrefix := defaultContainerVethPrefix
  1038. if network.config.ContainerIfacePrefix != "" {
  1039. containerVethPrefix = network.config.ContainerIfacePrefix
  1040. }
  1041. err = iNames.SetNames(endpoint.srcName, containerVethPrefix)
  1042. if err != nil {
  1043. return err
  1044. }
  1045. err = jinfo.SetGateway(network.bridge.gatewayIPv4)
  1046. if err != nil {
  1047. return err
  1048. }
  1049. err = jinfo.SetGatewayIPv6(network.bridge.gatewayIPv6)
  1050. if err != nil {
  1051. return err
  1052. }
  1053. return nil
  1054. }
  1055. // Leave method is invoked when a Sandbox detaches from an endpoint.
  1056. func (d *driver) Leave(nid, eid string) error {
  1057. network, err := d.getNetwork(nid)
  1058. if err != nil {
  1059. return types.InternalMaskableErrorf("%s", err)
  1060. }
  1061. endpoint, err := network.getEndpoint(eid)
  1062. if err != nil {
  1063. return err
  1064. }
  1065. if endpoint == nil {
  1066. return EndpointNotFoundError(eid)
  1067. }
  1068. if !network.config.EnableICC {
  1069. if err = d.link(network, endpoint, false); err != nil {
  1070. return err
  1071. }
  1072. }
  1073. return nil
  1074. }
  1075. func (d *driver) ProgramExternalConnectivity(nid, eid string, options map[string]interface{}) error {
  1076. network, err := d.getNetwork(nid)
  1077. if err != nil {
  1078. return err
  1079. }
  1080. endpoint, err := network.getEndpoint(eid)
  1081. if err != nil {
  1082. return err
  1083. }
  1084. if endpoint == nil {
  1085. return EndpointNotFoundError(eid)
  1086. }
  1087. endpoint.extConnConfig, err = parseConnectivityOptions(options)
  1088. if err != nil {
  1089. return err
  1090. }
  1091. // Program any required port mapping and store them in the endpoint
  1092. endpoint.portMapping, err = network.allocatePorts(endpoint, network.config.DefaultBindingIP, d.config.EnableUserlandProxy)
  1093. if err != nil {
  1094. return err
  1095. }
  1096. defer func() {
  1097. if err != nil {
  1098. if e := network.releasePorts(endpoint); e != nil {
  1099. logrus.Errorf("Failed to release ports allocated for the bridge endpoint %s on failure %v because of %v",
  1100. eid, err, e)
  1101. }
  1102. endpoint.portMapping = nil
  1103. }
  1104. }()
  1105. // Clean the connection tracker state of the host for the specific endpoint. This is needed because some flows may
  1106. // be bound to the local proxy, or to the host (for UDP packets), and won't be redirected to the new endpoints.
  1107. clearConntrackEntries(d.nlh, endpoint)
  1108. if err = d.storeUpdate(endpoint); err != nil {
  1109. return fmt.Errorf("failed to update bridge endpoint %.7s to store: %v", endpoint.id, err)
  1110. }
  1111. if !network.config.EnableICC {
  1112. return d.link(network, endpoint, true)
  1113. }
  1114. return nil
  1115. }
  1116. func (d *driver) RevokeExternalConnectivity(nid, eid string) error {
  1117. network, err := d.getNetwork(nid)
  1118. if err != nil {
  1119. return err
  1120. }
  1121. endpoint, err := network.getEndpoint(eid)
  1122. if err != nil {
  1123. return err
  1124. }
  1125. if endpoint == nil {
  1126. return EndpointNotFoundError(eid)
  1127. }
  1128. err = network.releasePorts(endpoint)
  1129. if err != nil {
  1130. logrus.Warn(err)
  1131. }
  1132. endpoint.portMapping = nil
  1133. // Clean the connection tracker state of the host for the specific endpoint. This is a precautionary measure to
  1134. // avoid new endpoints getting the same IP address to receive unexpected packets due to bad conntrack state leading
  1135. // to bad NATing.
  1136. clearConntrackEntries(d.nlh, endpoint)
  1137. if err = d.storeUpdate(endpoint); err != nil {
  1138. return fmt.Errorf("failed to update bridge endpoint %.7s to store: %v", endpoint.id, err)
  1139. }
  1140. return nil
  1141. }
  1142. func (d *driver) link(network *bridgeNetwork, endpoint *bridgeEndpoint, enable bool) error {
  1143. var err error
  1144. cc := endpoint.containerConfig
  1145. if cc == nil {
  1146. return nil
  1147. }
  1148. ec := endpoint.extConnConfig
  1149. if ec == nil {
  1150. return nil
  1151. }
  1152. if ec.ExposedPorts != nil {
  1153. for _, p := range cc.ParentEndpoints {
  1154. var parentEndpoint *bridgeEndpoint
  1155. parentEndpoint, err = network.getEndpoint(p)
  1156. if err != nil {
  1157. return err
  1158. }
  1159. if parentEndpoint == nil {
  1160. err = InvalidEndpointIDError(p)
  1161. return err
  1162. }
  1163. l := newLink(parentEndpoint.addr.IP.String(),
  1164. endpoint.addr.IP.String(),
  1165. ec.ExposedPorts, network.config.BridgeName)
  1166. if enable {
  1167. err = l.Enable()
  1168. if err != nil {
  1169. return err
  1170. }
  1171. defer func() {
  1172. if err != nil {
  1173. l.Disable()
  1174. }
  1175. }()
  1176. } else {
  1177. l.Disable()
  1178. }
  1179. }
  1180. }
  1181. for _, c := range cc.ChildEndpoints {
  1182. var childEndpoint *bridgeEndpoint
  1183. childEndpoint, err = network.getEndpoint(c)
  1184. if err != nil {
  1185. return err
  1186. }
  1187. if childEndpoint == nil {
  1188. err = InvalidEndpointIDError(c)
  1189. return err
  1190. }
  1191. if childEndpoint.extConnConfig == nil || childEndpoint.extConnConfig.ExposedPorts == nil {
  1192. continue
  1193. }
  1194. l := newLink(endpoint.addr.IP.String(),
  1195. childEndpoint.addr.IP.String(),
  1196. childEndpoint.extConnConfig.ExposedPorts, network.config.BridgeName)
  1197. if enable {
  1198. err = l.Enable()
  1199. if err != nil {
  1200. return err
  1201. }
  1202. defer func() {
  1203. if err != nil {
  1204. l.Disable()
  1205. }
  1206. }()
  1207. } else {
  1208. l.Disable()
  1209. }
  1210. }
  1211. return nil
  1212. }
  1213. func (d *driver) Type() string {
  1214. return networkType
  1215. }
  1216. func (d *driver) IsBuiltIn() bool {
  1217. return true
  1218. }
  1219. // DiscoverNew is a notification for a new discovery event, such as a new node joining a cluster
  1220. func (d *driver) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error {
  1221. return nil
  1222. }
  1223. // DiscoverDelete is a notification for a discovery delete event, such as a node leaving a cluster
  1224. func (d *driver) DiscoverDelete(dType discoverapi.DiscoveryType, data interface{}) error {
  1225. return nil
  1226. }
  1227. func parseEndpointOptions(epOptions map[string]interface{}) (*endpointConfiguration, error) {
  1228. if epOptions == nil {
  1229. return nil, nil
  1230. }
  1231. ec := &endpointConfiguration{}
  1232. if opt, ok := epOptions[netlabel.MacAddress]; ok {
  1233. if mac, ok := opt.(net.HardwareAddr); ok {
  1234. ec.MacAddress = mac
  1235. } else {
  1236. return nil, &ErrInvalidEndpointConfig{}
  1237. }
  1238. }
  1239. return ec, nil
  1240. }
  1241. func parseContainerOptions(cOptions map[string]interface{}) (*containerConfiguration, error) {
  1242. if cOptions == nil {
  1243. return nil, nil
  1244. }
  1245. genericData := cOptions[netlabel.GenericData]
  1246. if genericData == nil {
  1247. return nil, nil
  1248. }
  1249. switch opt := genericData.(type) {
  1250. case options.Generic:
  1251. opaqueConfig, err := options.GenerateFromModel(opt, &containerConfiguration{})
  1252. if err != nil {
  1253. return nil, err
  1254. }
  1255. return opaqueConfig.(*containerConfiguration), nil
  1256. case *containerConfiguration:
  1257. return opt, nil
  1258. default:
  1259. return nil, nil
  1260. }
  1261. }
  1262. func parseConnectivityOptions(cOptions map[string]interface{}) (*connectivityConfiguration, error) {
  1263. if cOptions == nil {
  1264. return nil, nil
  1265. }
  1266. cc := &connectivityConfiguration{}
  1267. if opt, ok := cOptions[netlabel.PortMap]; ok {
  1268. if pb, ok := opt.([]types.PortBinding); ok {
  1269. cc.PortBindings = pb
  1270. } else {
  1271. return nil, types.BadRequestErrorf("Invalid port mapping data in connectivity configuration: %v", opt)
  1272. }
  1273. }
  1274. if opt, ok := cOptions[netlabel.ExposedPorts]; ok {
  1275. if ports, ok := opt.([]types.TransportPort); ok {
  1276. cc.ExposedPorts = ports
  1277. } else {
  1278. return nil, types.BadRequestErrorf("Invalid exposed ports data in connectivity configuration: %v", opt)
  1279. }
  1280. }
  1281. return cc, nil
  1282. }
  1283. func electMacAddress(epConfig *endpointConfiguration, ip net.IP) net.HardwareAddr {
  1284. if epConfig != nil && epConfig.MacAddress != nil {
  1285. return epConfig.MacAddress
  1286. }
  1287. return netutils.GenerateMACFromIP(ip)
  1288. }