bridge.go 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426
  1. package bridge
  2. import (
  3. "errors"
  4. "fmt"
  5. "io/ioutil"
  6. "net"
  7. "os"
  8. "os/exec"
  9. "path/filepath"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "syscall"
  14. "github.com/Sirupsen/logrus"
  15. "github.com/docker/libnetwork/driverapi"
  16. "github.com/docker/libnetwork/ipallocator"
  17. "github.com/docker/libnetwork/iptables"
  18. "github.com/docker/libnetwork/netlabel"
  19. "github.com/docker/libnetwork/netutils"
  20. "github.com/docker/libnetwork/options"
  21. "github.com/docker/libnetwork/portmapper"
  22. "github.com/docker/libnetwork/types"
  23. "github.com/vishvananda/netlink"
  24. )
  25. const (
  26. networkType = "bridge"
  27. vethPrefix = "veth"
  28. vethLen = 7
  29. containerVethPrefix = "eth"
  30. maxAllocatePortAttempts = 10
  31. ifaceID = 1
  32. )
  33. var (
  34. ipAllocator *ipallocator.IPAllocator
  35. )
  36. // configuration info for the "bridge" driver.
  37. type configuration struct {
  38. EnableIPForwarding bool
  39. EnableIPTables bool
  40. EnableUserlandProxy bool
  41. }
  42. // networkConfiguration for network specific configuration
  43. type networkConfiguration struct {
  44. BridgeName string
  45. AddressIPv4 *net.IPNet
  46. FixedCIDR *net.IPNet
  47. FixedCIDRv6 *net.IPNet
  48. EnableIPv6 bool
  49. EnableIPMasquerade bool
  50. EnableICC bool
  51. Mtu int
  52. DefaultGatewayIPv4 net.IP
  53. DefaultGatewayIPv6 net.IP
  54. DefaultBindingIP net.IP
  55. AllowNonDefaultBridge bool
  56. }
  57. // endpointConfiguration represents the user specified configuration for the sandbox endpoint
  58. type endpointConfiguration struct {
  59. MacAddress net.HardwareAddr
  60. PortBindings []types.PortBinding
  61. ExposedPorts []types.TransportPort
  62. }
  63. // containerConfiguration represents the user specified configuration for a container
  64. type containerConfiguration struct {
  65. ParentEndpoints []string
  66. ChildEndpoints []string
  67. }
  68. type bridgeEndpoint struct {
  69. id string
  70. srcName string
  71. addr *net.IPNet
  72. addrv6 *net.IPNet
  73. macAddress net.HardwareAddr
  74. config *endpointConfiguration // User specified parameters
  75. containerConfig *containerConfiguration
  76. portMapping []types.PortBinding // Operation port bindings
  77. }
  78. type bridgeNetwork struct {
  79. id string
  80. bridge *bridgeInterface // The bridge's L3 interface
  81. config *networkConfiguration
  82. endpoints map[string]*bridgeEndpoint // key: endpoint id
  83. portMapper *portmapper.PortMapper
  84. driver *driver // The network's driver
  85. sync.Mutex
  86. }
  87. type driver struct {
  88. config *configuration
  89. network *bridgeNetwork
  90. natChain *iptables.ChainInfo
  91. filterChain *iptables.ChainInfo
  92. networks map[string]*bridgeNetwork
  93. sync.Mutex
  94. }
  95. // New constructs a new bridge driver
  96. func newDriver() driverapi.Driver {
  97. ipAllocator = ipallocator.New()
  98. return &driver{networks: map[string]*bridgeNetwork{}}
  99. }
  100. // Init registers a new instance of bridge driver
  101. func Init(dc driverapi.DriverCallback) error {
  102. if _, err := os.Stat("/proc/sys/net/bridge"); err != nil {
  103. if out, err := exec.Command("modprobe", "-va", "bridge", "br_netfilter").CombinedOutput(); err != nil {
  104. logrus.Warnf("Running modprobe bridge br_netfilter failed with message: %s, error: %v", out, err)
  105. }
  106. }
  107. if out, err := exec.Command("modprobe", "-va", "nf_nat").CombinedOutput(); err != nil {
  108. logrus.Warnf("Running modprobe nf_nat failed with message: `%s`, error: %v", strings.TrimSpace(string(out)), err)
  109. }
  110. if err := iptables.FirewalldInit(); err != nil {
  111. logrus.Debugf("Fail to initialize firewalld: %v, using raw iptables instead", err)
  112. }
  113. if err := iptables.RemoveExistingChain(DockerChain, iptables.Nat); err != nil {
  114. logrus.Warnf("Failed to remove existing iptables entries in %s : %v", DockerChain, err)
  115. }
  116. c := driverapi.Capability{
  117. Scope: driverapi.LocalScope,
  118. }
  119. return dc.RegisterDriver(networkType, newDriver(), c)
  120. }
  121. // Validate performs a static validation on the network configuration parameters.
  122. // Whatever can be assessed a priori before attempting any programming.
  123. func (c *networkConfiguration) Validate() error {
  124. if c.Mtu < 0 {
  125. return ErrInvalidMtu(c.Mtu)
  126. }
  127. // If bridge v4 subnet is specified
  128. if c.AddressIPv4 != nil {
  129. // If Container restricted subnet is specified, it must be a subset of bridge subnet
  130. if c.FixedCIDR != nil {
  131. // Check Network address
  132. if !c.AddressIPv4.Contains(c.FixedCIDR.IP) {
  133. return &ErrInvalidContainerSubnet{}
  134. }
  135. // Check it is effectively a subset
  136. brNetLen, _ := c.AddressIPv4.Mask.Size()
  137. cnNetLen, _ := c.FixedCIDR.Mask.Size()
  138. if brNetLen > cnNetLen {
  139. return &ErrInvalidContainerSubnet{}
  140. }
  141. }
  142. // If default gw is specified, it must be part of bridge subnet
  143. if c.DefaultGatewayIPv4 != nil {
  144. if !c.AddressIPv4.Contains(c.DefaultGatewayIPv4) {
  145. return &ErrInvalidGateway{}
  146. }
  147. }
  148. }
  149. // If default v6 gw is specified, FixedCIDRv6 must be specified and gw must belong to FixedCIDRv6 subnet
  150. if c.EnableIPv6 && c.DefaultGatewayIPv6 != nil {
  151. if c.FixedCIDRv6 == nil || !c.FixedCIDRv6.Contains(c.DefaultGatewayIPv6) {
  152. return &ErrInvalidGateway{}
  153. }
  154. }
  155. return nil
  156. }
  157. // Conflicts check if two NetworkConfiguration objects overlap
  158. func (c *networkConfiguration) Conflicts(o *networkConfiguration) bool {
  159. if o == nil {
  160. return false
  161. }
  162. // Also empty, becasue only one network with empty name is allowed
  163. if c.BridgeName == o.BridgeName {
  164. return true
  165. }
  166. // They must be in different subnets
  167. if (c.AddressIPv4 != nil && o.AddressIPv4 != nil) &&
  168. (c.AddressIPv4.Contains(o.AddressIPv4.IP) || o.AddressIPv4.Contains(c.AddressIPv4.IP)) {
  169. return true
  170. }
  171. return false
  172. }
  173. // fromMap retrieve the configuration data from the map form.
  174. func (c *networkConfiguration) fromMap(data map[string]interface{}) error {
  175. var err error
  176. if i, ok := data["BridgeName"]; ok && i != nil {
  177. if c.BridgeName, ok = i.(string); !ok {
  178. return types.BadRequestErrorf("invalid type for BridgeName value")
  179. }
  180. }
  181. if i, ok := data["Mtu"]; ok && i != nil {
  182. if s, ok := i.(string); ok {
  183. if c.Mtu, err = strconv.Atoi(s); err != nil {
  184. return types.BadRequestErrorf("failed to parse Mtu value: %s", err.Error())
  185. }
  186. } else {
  187. return types.BadRequestErrorf("invalid type for Mtu value")
  188. }
  189. }
  190. if i, ok := data["EnableIPv6"]; ok && i != nil {
  191. if s, ok := i.(string); ok {
  192. if c.EnableIPv6, err = strconv.ParseBool(s); err != nil {
  193. return types.BadRequestErrorf("failed to parse EnableIPv6 value: %s", err.Error())
  194. }
  195. } else {
  196. return types.BadRequestErrorf("invalid type for EnableIPv6 value")
  197. }
  198. }
  199. if i, ok := data["EnableIPMasquerade"]; ok && i != nil {
  200. if s, ok := i.(string); ok {
  201. if c.EnableIPMasquerade, err = strconv.ParseBool(s); err != nil {
  202. return types.BadRequestErrorf("failed to parse EnableIPMasquerade value: %s", err.Error())
  203. }
  204. } else {
  205. return types.BadRequestErrorf("invalid type for EnableIPMasquerade value")
  206. }
  207. }
  208. if i, ok := data["EnableICC"]; ok && i != nil {
  209. if s, ok := i.(string); ok {
  210. if c.EnableICC, err = strconv.ParseBool(s); err != nil {
  211. return types.BadRequestErrorf("failed to parse EnableICC value: %s", err.Error())
  212. }
  213. } else {
  214. return types.BadRequestErrorf("invalid type for EnableICC value")
  215. }
  216. }
  217. if i, ok := data["AllowNonDefaultBridge"]; ok && i != nil {
  218. if s, ok := i.(string); ok {
  219. if c.AllowNonDefaultBridge, err = strconv.ParseBool(s); err != nil {
  220. return types.BadRequestErrorf("failed to parse AllowNonDefaultBridge value: %s", err.Error())
  221. }
  222. } else {
  223. return types.BadRequestErrorf("invalid type for AllowNonDefaultBridge value")
  224. }
  225. }
  226. if i, ok := data["AddressIPv4"]; ok && i != nil {
  227. if s, ok := i.(string); ok {
  228. if ip, nw, e := net.ParseCIDR(s); e == nil {
  229. nw.IP = ip
  230. c.AddressIPv4 = nw
  231. } else {
  232. return types.BadRequestErrorf("failed to parse AddressIPv4 value")
  233. }
  234. } else {
  235. return types.BadRequestErrorf("invalid type for AddressIPv4 value")
  236. }
  237. }
  238. if i, ok := data["FixedCIDR"]; ok && i != nil {
  239. if s, ok := i.(string); ok {
  240. if ip, nw, e := net.ParseCIDR(s); e == nil {
  241. nw.IP = ip
  242. c.FixedCIDR = nw
  243. } else {
  244. return types.BadRequestErrorf("failed to parse FixedCIDR value")
  245. }
  246. } else {
  247. return types.BadRequestErrorf("invalid type for FixedCIDR value")
  248. }
  249. }
  250. if i, ok := data["FixedCIDRv6"]; ok && i != nil {
  251. if s, ok := i.(string); ok {
  252. if ip, nw, e := net.ParseCIDR(s); e == nil {
  253. nw.IP = ip
  254. c.FixedCIDRv6 = nw
  255. } else {
  256. return types.BadRequestErrorf("failed to parse FixedCIDRv6 value")
  257. }
  258. } else {
  259. return types.BadRequestErrorf("invalid type for FixedCIDRv6 value")
  260. }
  261. }
  262. if i, ok := data["DefaultGatewayIPv4"]; ok && i != nil {
  263. if s, ok := i.(string); ok {
  264. if c.DefaultGatewayIPv4 = net.ParseIP(s); c.DefaultGatewayIPv4 == nil {
  265. return types.BadRequestErrorf("failed to parse DefaultGatewayIPv4 value")
  266. }
  267. } else {
  268. return types.BadRequestErrorf("invalid type for DefaultGatewayIPv4 value")
  269. }
  270. }
  271. if i, ok := data["DefaultGatewayIPv6"]; ok && i != nil {
  272. if s, ok := i.(string); ok {
  273. if c.DefaultGatewayIPv6 = net.ParseIP(s); c.DefaultGatewayIPv6 == nil {
  274. return types.BadRequestErrorf("failed to parse DefaultGatewayIPv6 value")
  275. }
  276. } else {
  277. return types.BadRequestErrorf("invalid type for DefaultGatewayIPv6 value")
  278. }
  279. }
  280. if i, ok := data["DefaultBindingIP"]; ok && i != nil {
  281. if s, ok := i.(string); ok {
  282. if c.DefaultBindingIP = net.ParseIP(s); c.DefaultBindingIP == nil {
  283. return types.BadRequestErrorf("failed to parse DefaultBindingIP value")
  284. }
  285. } else {
  286. return types.BadRequestErrorf("invalid type for DefaultBindingIP value")
  287. }
  288. }
  289. return nil
  290. }
  291. func (n *bridgeNetwork) getDriverChains() (*iptables.ChainInfo, *iptables.ChainInfo, error) {
  292. n.Lock()
  293. defer n.Unlock()
  294. if n.driver == nil {
  295. return nil, nil, types.BadRequestErrorf("no driver found")
  296. }
  297. return n.driver.natChain, n.driver.filterChain, nil
  298. }
  299. func (n *bridgeNetwork) getNetworkBridgeName() string {
  300. n.Lock()
  301. config := n.config
  302. n.Unlock()
  303. return config.BridgeName
  304. }
  305. func (n *bridgeNetwork) getEndpoint(eid string) (*bridgeEndpoint, error) {
  306. n.Lock()
  307. defer n.Unlock()
  308. if eid == "" {
  309. return nil, InvalidEndpointIDError(eid)
  310. }
  311. if ep, ok := n.endpoints[eid]; ok {
  312. return ep, nil
  313. }
  314. return nil, nil
  315. }
  316. // Install/Removes the iptables rules needed to isolate this network
  317. // from each of the other networks
  318. func (n *bridgeNetwork) isolateNetwork(others []*bridgeNetwork, enable bool) error {
  319. n.Lock()
  320. thisV4 := n.bridge.bridgeIPv4
  321. thisV6 := getV6Network(n.config, n.bridge)
  322. n.Unlock()
  323. // Install the rules to isolate this networks against each of the other networks
  324. for _, o := range others {
  325. o.Lock()
  326. otherV4 := o.bridge.bridgeIPv4
  327. otherV6 := getV6Network(o.config, o.bridge)
  328. o.Unlock()
  329. if !types.CompareIPNet(thisV4, otherV4) {
  330. // It's ok to pass a.b.c.d/x, iptables will ignore the host subnet bits
  331. if err := setINC(thisV4.String(), otherV4.String(), enable); err != nil {
  332. return err
  333. }
  334. }
  335. if thisV6 != nil && otherV6 != nil && !types.CompareIPNet(thisV6, otherV6) {
  336. if err := setINC(thisV6.String(), otherV6.String(), enable); err != nil {
  337. return err
  338. }
  339. }
  340. }
  341. return nil
  342. }
  343. // Checks whether this network's configuration for the network with this id conflicts with any of the passed networks
  344. func (c *networkConfiguration) conflictsWithNetworks(id string, others []*bridgeNetwork) error {
  345. for _, nw := range others {
  346. nw.Lock()
  347. nwID := nw.id
  348. nwConfig := nw.config
  349. nwBridge := nw.bridge
  350. nw.Unlock()
  351. if nwID == id {
  352. continue
  353. }
  354. // Verify the name (which may have been set by newInterface()) does not conflict with
  355. // existing bridge interfaces. Ironically the system chosen name gets stored in the config...
  356. // Basically we are checking if the two original configs were both empty.
  357. if nwConfig.BridgeName == c.BridgeName {
  358. return types.ForbiddenErrorf("conflicts with network %s (%s) by bridge name", nwID, nwConfig.BridgeName)
  359. }
  360. // If this network config specifies the AddressIPv4, we need
  361. // to make sure it does not conflict with any previously allocated
  362. // bridges. This could not be completely caught by the config conflict
  363. // check, because networks which config does not specify the AddressIPv4
  364. // get their address and subnet selected by the driver (see electBridgeIPv4())
  365. if c.AddressIPv4 != nil {
  366. if nwBridge.bridgeIPv4.Contains(c.AddressIPv4.IP) ||
  367. c.AddressIPv4.Contains(nwBridge.bridgeIPv4.IP) {
  368. return types.ForbiddenErrorf("conflicts with network %s (%s) by ip network", nwID, nwConfig.BridgeName)
  369. }
  370. }
  371. }
  372. return nil
  373. }
  374. func (d *driver) Config(option map[string]interface{}) error {
  375. var config *configuration
  376. var err error
  377. d.Lock()
  378. defer d.Unlock()
  379. if d.config != nil {
  380. return &ErrConfigExists{}
  381. }
  382. genericData, ok := option[netlabel.GenericData]
  383. if ok && genericData != nil {
  384. switch opt := genericData.(type) {
  385. case options.Generic:
  386. opaqueConfig, err := options.GenerateFromModel(opt, &configuration{})
  387. if err != nil {
  388. return err
  389. }
  390. config = opaqueConfig.(*configuration)
  391. case *configuration:
  392. config = opt
  393. default:
  394. return &ErrInvalidDriverConfig{}
  395. }
  396. d.config = config
  397. } else {
  398. config = &configuration{}
  399. d.config = config
  400. }
  401. if config.EnableIPForwarding {
  402. err = setupIPForwarding()
  403. if err != nil {
  404. return err
  405. }
  406. }
  407. if config.EnableIPTables {
  408. d.natChain, d.filterChain, err = setupIPChains(config)
  409. return err
  410. }
  411. return nil
  412. }
  413. func (d *driver) getNetwork(id string) (*bridgeNetwork, error) {
  414. d.Lock()
  415. defer d.Unlock()
  416. if id == "" {
  417. return nil, types.BadRequestErrorf("invalid network id: %s", id)
  418. }
  419. if nw, ok := d.networks[id]; ok {
  420. return nw, nil
  421. }
  422. return nil, types.NotFoundErrorf("network not found: %s", id)
  423. }
  424. func parseNetworkGenericOptions(data interface{}) (*networkConfiguration, error) {
  425. var (
  426. err error
  427. config *networkConfiguration
  428. )
  429. switch opt := data.(type) {
  430. case *networkConfiguration:
  431. config = opt
  432. case map[string]interface{}:
  433. config = &networkConfiguration{
  434. EnableICC: true,
  435. EnableIPMasquerade: true,
  436. }
  437. err = config.fromMap(opt)
  438. case options.Generic:
  439. var opaqueConfig interface{}
  440. if opaqueConfig, err = options.GenerateFromModel(opt, config); err == nil {
  441. config = opaqueConfig.(*networkConfiguration)
  442. }
  443. default:
  444. err = types.BadRequestErrorf("do not recognize network configuration format: %T", opt)
  445. }
  446. return config, err
  447. }
  448. func parseNetworkOptions(option options.Generic) (*networkConfiguration, error) {
  449. var err error
  450. config := &networkConfiguration{}
  451. // Parse generic label first, config will be re-assigned
  452. if genData, ok := option[netlabel.GenericData]; ok && genData != nil {
  453. if config, err = parseNetworkGenericOptions(genData); err != nil {
  454. return nil, err
  455. }
  456. }
  457. // Process well-known labels next
  458. if _, ok := option[netlabel.EnableIPv6]; ok {
  459. config.EnableIPv6 = option[netlabel.EnableIPv6].(bool)
  460. }
  461. // Finally validate the configuration
  462. if err = config.Validate(); err != nil {
  463. return nil, err
  464. }
  465. return config, nil
  466. }
  467. // Returns the non link-local IPv6 subnet for the containers attached to this bridge if found, nil otherwise
  468. func getV6Network(config *networkConfiguration, i *bridgeInterface) *net.IPNet {
  469. if config.FixedCIDRv6 != nil {
  470. return config.FixedCIDRv6
  471. }
  472. if i.bridgeIPv6 != nil && i.bridgeIPv6.IP != nil && !i.bridgeIPv6.IP.IsLinkLocalUnicast() {
  473. return i.bridgeIPv6
  474. }
  475. return nil
  476. }
  477. // Return a slice of networks over which caller can iterate safely
  478. func (d *driver) getNetworks() []*bridgeNetwork {
  479. d.Lock()
  480. defer d.Unlock()
  481. ls := make([]*bridgeNetwork, 0, len(d.networks))
  482. for _, nw := range d.networks {
  483. ls = append(ls, nw)
  484. }
  485. return ls
  486. }
  487. // Create a new network using bridge plugin
  488. func (d *driver) CreateNetwork(id string, option map[string]interface{}) error {
  489. var err error
  490. // Sanity checks
  491. d.Lock()
  492. if _, ok := d.networks[id]; ok {
  493. d.Unlock()
  494. return types.ForbiddenErrorf("network %s exists", id)
  495. }
  496. d.Unlock()
  497. // Parse and validate the config. It should not conflict with existing networks' config
  498. config, err := parseNetworkOptions(option)
  499. if err != nil {
  500. return err
  501. }
  502. networkList := d.getNetworks()
  503. for _, nw := range networkList {
  504. nw.Lock()
  505. nwConfig := nw.config
  506. nw.Unlock()
  507. if nwConfig.Conflicts(config) {
  508. return types.ForbiddenErrorf("conflicts with network %s (%s)", nw.id, nw.config.BridgeName)
  509. }
  510. }
  511. // Create and set network handler in driver
  512. network := &bridgeNetwork{
  513. id: id,
  514. endpoints: make(map[string]*bridgeEndpoint),
  515. config: config,
  516. portMapper: portmapper.New(),
  517. driver: d,
  518. }
  519. d.Lock()
  520. d.networks[id] = network
  521. d.Unlock()
  522. // On failure make sure to reset driver network handler to nil
  523. defer func() {
  524. if err != nil {
  525. d.Lock()
  526. delete(d.networks, id)
  527. d.Unlock()
  528. }
  529. }()
  530. // Create or retrieve the bridge L3 interface
  531. bridgeIface := newInterface(config)
  532. network.bridge = bridgeIface
  533. // Verify the network configuration does not conflict with previously installed
  534. // networks. This step is needed now because driver might have now set the bridge
  535. // name on this config struct. And because we need to check for possible address
  536. // conflicts, so we need to check against operationa lnetworks.
  537. if err = config.conflictsWithNetworks(id, networkList); err != nil {
  538. return err
  539. }
  540. setupNetworkIsolationRules := func(config *networkConfiguration, i *bridgeInterface) error {
  541. if err := network.isolateNetwork(networkList, true); err != nil {
  542. if err := network.isolateNetwork(networkList, false); err != nil {
  543. logrus.Warnf("Failed on removing the inter-network iptables rules on cleanup: %v", err)
  544. }
  545. return err
  546. }
  547. return nil
  548. }
  549. // Prepare the bridge setup configuration
  550. bridgeSetup := newBridgeSetup(config, bridgeIface)
  551. // If the bridge interface doesn't exist, we need to start the setup steps
  552. // by creating a new device and assigning it an IPv4 address.
  553. bridgeAlreadyExists := bridgeIface.exists()
  554. if !bridgeAlreadyExists {
  555. bridgeSetup.queueStep(setupDevice)
  556. }
  557. // Even if a bridge exists try to setup IPv4.
  558. bridgeSetup.queueStep(setupBridgeIPv4)
  559. enableIPv6Forwarding := false
  560. if d.config != nil && d.config.EnableIPForwarding && config.FixedCIDRv6 != nil {
  561. enableIPv6Forwarding = true
  562. }
  563. // Conditionally queue setup steps depending on configuration values.
  564. for _, step := range []struct {
  565. Condition bool
  566. Fn setupStep
  567. }{
  568. // Enable IPv6 on the bridge if required. We do this even for a
  569. // previously existing bridge, as it may be here from a previous
  570. // installation where IPv6 wasn't supported yet and needs to be
  571. // assigned an IPv6 link-local address.
  572. {config.EnableIPv6, setupBridgeIPv6},
  573. // We ensure that the bridge has the expectedIPv4 and IPv6 addresses in
  574. // the case of a previously existing device.
  575. {bridgeAlreadyExists, setupVerifyAndReconcile},
  576. // Setup the bridge to allocate containers IPv4 addresses in the
  577. // specified subnet.
  578. {config.FixedCIDR != nil, setupFixedCIDRv4},
  579. // Setup the bridge to allocate containers global IPv6 addresses in the
  580. // specified subnet.
  581. {config.FixedCIDRv6 != nil, setupFixedCIDRv6},
  582. // Enable IPv6 Forwarding
  583. {enableIPv6Forwarding, setupIPv6Forwarding},
  584. // Setup Loopback Adresses Routing
  585. {!d.config.EnableUserlandProxy, setupLoopbackAdressesRouting},
  586. // Setup IPTables.
  587. {d.config.EnableIPTables, network.setupIPTables},
  588. //We want to track firewalld configuration so that
  589. //if it is started/reloaded, the rules can be applied correctly
  590. {d.config.EnableIPTables, network.setupFirewalld},
  591. // Setup DefaultGatewayIPv4
  592. {config.DefaultGatewayIPv4 != nil, setupGatewayIPv4},
  593. // Setup DefaultGatewayIPv6
  594. {config.DefaultGatewayIPv6 != nil, setupGatewayIPv6},
  595. // Add inter-network communication rules.
  596. {d.config.EnableIPTables, setupNetworkIsolationRules},
  597. //Configure bridge networking filtering if ICC is off and IP tables are enabled
  598. {!config.EnableICC && d.config.EnableIPTables, setupBridgeNetFiltering},
  599. } {
  600. if step.Condition {
  601. bridgeSetup.queueStep(step.Fn)
  602. }
  603. }
  604. // Block bridge IP from being allocated.
  605. bridgeSetup.queueStep(allocateBridgeIP)
  606. // Apply the prepared list of steps, and abort at the first error.
  607. bridgeSetup.queueStep(setupDeviceUp)
  608. if err = bridgeSetup.apply(); err != nil {
  609. return err
  610. }
  611. return nil
  612. }
  613. func (d *driver) DeleteNetwork(nid string) error {
  614. var err error
  615. // Get network handler and remove it from driver
  616. d.Lock()
  617. n, ok := d.networks[nid]
  618. d.Unlock()
  619. if !ok {
  620. return types.InternalMaskableErrorf("network %s does not exist", nid)
  621. }
  622. n.Lock()
  623. config := n.config
  624. n.Unlock()
  625. if config.BridgeName == DefaultBridgeName {
  626. return types.ForbiddenErrorf("default network of type \"%s\" cannot be deleted", networkType)
  627. }
  628. d.Lock()
  629. delete(d.networks, nid)
  630. d.Unlock()
  631. // On failure set network handler back in driver, but
  632. // only if is not already taken over by some other thread
  633. defer func() {
  634. if err != nil {
  635. d.Lock()
  636. if _, ok := d.networks[nid]; !ok {
  637. d.networks[nid] = n
  638. }
  639. d.Unlock()
  640. }
  641. }()
  642. // Sanity check
  643. if n == nil {
  644. err = driverapi.ErrNoNetwork(nid)
  645. return err
  646. }
  647. // Cannot remove network if endpoints are still present
  648. if len(n.endpoints) != 0 {
  649. err = ActiveEndpointsError(n.id)
  650. return err
  651. }
  652. // In case of failures after this point, restore the network isolation rules
  653. nwList := d.getNetworks()
  654. defer func() {
  655. if err != nil {
  656. if err := n.isolateNetwork(nwList, true); err != nil {
  657. logrus.Warnf("Failed on restoring the inter-network iptables rules on cleanup: %v", err)
  658. }
  659. }
  660. }()
  661. // Remove inter-network communication rules.
  662. err = n.isolateNetwork(nwList, false)
  663. if err != nil {
  664. return err
  665. }
  666. // Programming
  667. err = netlink.LinkDel(n.bridge.Link)
  668. // Release ip addresses (ignore errors)
  669. if config.FixedCIDR == nil || config.FixedCIDR.Contains(config.DefaultGatewayIPv4) {
  670. if e := ipAllocator.ReleaseIP(n.bridge.bridgeIPv4, n.bridge.gatewayIPv4); e != nil {
  671. logrus.Warnf("Failed to release default gateway address %s: %v", n.bridge.gatewayIPv4.String(), e)
  672. }
  673. }
  674. if config.FixedCIDR == nil || config.FixedCIDR.Contains(n.bridge.bridgeIPv4.IP) {
  675. if e := ipAllocator.ReleaseIP(n.bridge.bridgeIPv4, n.bridge.bridgeIPv4.IP); e != nil {
  676. logrus.Warnf("Failed to release bridge IP %s: %v", n.bridge.bridgeIPv4.IP.String(), e)
  677. }
  678. }
  679. return err
  680. }
  681. func addToBridge(ifaceName, bridgeName string) error {
  682. link, err := netlink.LinkByName(ifaceName)
  683. if err != nil {
  684. return fmt.Errorf("could not find interface %s: %v", ifaceName, err)
  685. }
  686. if err = netlink.LinkSetMaster(link,
  687. &netlink.Bridge{LinkAttrs: netlink.LinkAttrs{Name: bridgeName}}); err != nil {
  688. logrus.Debugf("Failed to add %s to bridge via netlink.Trying ioctl: %v", ifaceName, err)
  689. iface, err := net.InterfaceByName(ifaceName)
  690. if err != nil {
  691. return fmt.Errorf("could not find network interface %s: %v", ifaceName, err)
  692. }
  693. master, err := net.InterfaceByName(bridgeName)
  694. if err != nil {
  695. return fmt.Errorf("could not find bridge %s: %v", bridgeName, err)
  696. }
  697. return ioctlAddToBridge(iface, master)
  698. }
  699. return nil
  700. }
  701. func setHairpinMode(link netlink.Link, enable bool) error {
  702. err := netlink.LinkSetHairpin(link, enable)
  703. if err != nil && err != syscall.EINVAL {
  704. // If error is not EINVAL something else went wrong, bail out right away
  705. return fmt.Errorf("unable to set hairpin mode on %s via netlink: %v",
  706. link.Attrs().Name, err)
  707. }
  708. // Hairpin mode successfully set up
  709. if err == nil {
  710. return nil
  711. }
  712. // The netlink method failed with EINVAL which is probably because of an older
  713. // kernel. Try one more time via the sysfs method.
  714. path := filepath.Join("/sys/class/net", link.Attrs().Name, "brport/hairpin_mode")
  715. var val []byte
  716. if enable {
  717. val = []byte{'1', '\n'}
  718. } else {
  719. val = []byte{'0', '\n'}
  720. }
  721. if err := ioutil.WriteFile(path, val, 0644); err != nil {
  722. return fmt.Errorf("unable to set hairpin mode on %s via sysfs: %v", link.Attrs().Name, err)
  723. }
  724. return nil
  725. }
  726. func (d *driver) CreateEndpoint(nid, eid string, epInfo driverapi.EndpointInfo, epOptions map[string]interface{}) error {
  727. var (
  728. ipv6Addr *net.IPNet
  729. err error
  730. )
  731. if epInfo == nil {
  732. return errors.New("invalid endpoint info passed")
  733. }
  734. if len(epInfo.Interfaces()) != 0 {
  735. return errors.New("non empty interface list passed to bridge(local) driver")
  736. }
  737. // Get the network handler and make sure it exists
  738. d.Lock()
  739. n, ok := d.networks[nid]
  740. dconfig := d.config
  741. d.Unlock()
  742. if !ok {
  743. return types.NotFoundErrorf("network %s does not exist", nid)
  744. }
  745. if n == nil {
  746. return driverapi.ErrNoNetwork(nid)
  747. }
  748. // Sanity check
  749. n.Lock()
  750. if n.id != nid {
  751. n.Unlock()
  752. return InvalidNetworkIDError(nid)
  753. }
  754. n.Unlock()
  755. // Check if endpoint id is good and retrieve correspondent endpoint
  756. ep, err := n.getEndpoint(eid)
  757. if err != nil {
  758. return err
  759. }
  760. // Endpoint with that id exists either on desired or other sandbox
  761. if ep != nil {
  762. return driverapi.ErrEndpointExists(eid)
  763. }
  764. // Try to convert the options to endpoint configuration
  765. epConfig, err := parseEndpointOptions(epOptions)
  766. if err != nil {
  767. return err
  768. }
  769. // Create and add the endpoint
  770. n.Lock()
  771. endpoint := &bridgeEndpoint{id: eid, config: epConfig}
  772. n.endpoints[eid] = endpoint
  773. n.Unlock()
  774. // On failure make sure to remove the endpoint
  775. defer func() {
  776. if err != nil {
  777. n.Lock()
  778. delete(n.endpoints, eid)
  779. n.Unlock()
  780. }
  781. }()
  782. // Generate a name for what will be the host side pipe interface
  783. hostIfName, err := netutils.GenerateIfaceName(vethPrefix, vethLen)
  784. if err != nil {
  785. return err
  786. }
  787. // Generate a name for what will be the sandbox side pipe interface
  788. containerIfName, err := netutils.GenerateIfaceName(vethPrefix, vethLen)
  789. if err != nil {
  790. return err
  791. }
  792. // Generate and add the interface pipe host <-> sandbox
  793. veth := &netlink.Veth{
  794. LinkAttrs: netlink.LinkAttrs{Name: hostIfName, TxQLen: 0},
  795. PeerName: containerIfName}
  796. if err = netlink.LinkAdd(veth); err != nil {
  797. return types.InternalErrorf("failed to add the host (%s) <=> sandbox (%s) pair interfaces: %v", hostIfName, containerIfName, err)
  798. }
  799. // Get the host side pipe interface handler
  800. host, err := netlink.LinkByName(hostIfName)
  801. if err != nil {
  802. return types.InternalErrorf("failed to find host side interface %s: %v", hostIfName, err)
  803. }
  804. defer func() {
  805. if err != nil {
  806. netlink.LinkDel(host)
  807. }
  808. }()
  809. // Get the sandbox side pipe interface handler
  810. sbox, err := netlink.LinkByName(containerIfName)
  811. if err != nil {
  812. return types.InternalErrorf("failed to find sandbox side interface %s: %v", containerIfName, err)
  813. }
  814. defer func() {
  815. if err != nil {
  816. netlink.LinkDel(sbox)
  817. }
  818. }()
  819. n.Lock()
  820. config := n.config
  821. n.Unlock()
  822. // Add bridge inherited attributes to pipe interfaces
  823. if config.Mtu != 0 {
  824. err = netlink.LinkSetMTU(host, config.Mtu)
  825. if err != nil {
  826. return types.InternalErrorf("failed to set MTU on host interface %s: %v", hostIfName, err)
  827. }
  828. err = netlink.LinkSetMTU(sbox, config.Mtu)
  829. if err != nil {
  830. return types.InternalErrorf("failed to set MTU on sandbox interface %s: %v", containerIfName, err)
  831. }
  832. }
  833. // Attach host side pipe interface into the bridge
  834. if err = addToBridge(hostIfName, config.BridgeName); err != nil {
  835. return fmt.Errorf("adding interface %s to bridge %s failed: %v", hostIfName, config.BridgeName, err)
  836. }
  837. if !dconfig.EnableUserlandProxy {
  838. err = setHairpinMode(host, true)
  839. if err != nil {
  840. return err
  841. }
  842. }
  843. // v4 address for the sandbox side pipe interface
  844. ip4, err := ipAllocator.RequestIP(n.bridge.bridgeIPv4, nil)
  845. if err != nil {
  846. return err
  847. }
  848. ipv4Addr := &net.IPNet{IP: ip4, Mask: n.bridge.bridgeIPv4.Mask}
  849. // Down the interface before configuring mac address.
  850. if err = netlink.LinkSetDown(sbox); err != nil {
  851. return fmt.Errorf("could not set link down for container interface %s: %v", containerIfName, err)
  852. }
  853. // Set the sbox's MAC. If specified, use the one configured by user, otherwise generate one based on IP.
  854. mac := electMacAddress(epConfig, ip4)
  855. err = netlink.LinkSetHardwareAddr(sbox, mac)
  856. if err != nil {
  857. return fmt.Errorf("could not set mac address for container interface %s: %v", containerIfName, err)
  858. }
  859. endpoint.macAddress = mac
  860. // Up the host interface after finishing all netlink configuration
  861. if err = netlink.LinkSetUp(host); err != nil {
  862. return fmt.Errorf("could not set link up for host interface %s: %v", hostIfName, err)
  863. }
  864. // v6 address for the sandbox side pipe interface
  865. ipv6Addr = &net.IPNet{}
  866. if config.EnableIPv6 {
  867. var ip6 net.IP
  868. network := n.bridge.bridgeIPv6
  869. if config.FixedCIDRv6 != nil {
  870. network = config.FixedCIDRv6
  871. }
  872. ones, _ := network.Mask.Size()
  873. if ones <= 80 {
  874. ip6 = make(net.IP, len(network.IP))
  875. copy(ip6, network.IP)
  876. for i, h := range mac {
  877. ip6[i+10] = h
  878. }
  879. }
  880. ip6, err := ipAllocator.RequestIP(network, ip6)
  881. if err != nil {
  882. return err
  883. }
  884. ipv6Addr = &net.IPNet{IP: ip6, Mask: network.Mask}
  885. }
  886. // Create the sandbox side pipe interface
  887. endpoint.srcName = containerIfName
  888. endpoint.addr = ipv4Addr
  889. if config.EnableIPv6 {
  890. endpoint.addrv6 = ipv6Addr
  891. }
  892. err = epInfo.AddInterface(ifaceID, endpoint.macAddress, *ipv4Addr, *ipv6Addr)
  893. if err != nil {
  894. return err
  895. }
  896. // Program any required port mapping and store them in the endpoint
  897. endpoint.portMapping, err = n.allocatePorts(epConfig, endpoint, config.DefaultBindingIP, d.config.EnableUserlandProxy)
  898. if err != nil {
  899. return err
  900. }
  901. return nil
  902. }
  903. func (d *driver) DeleteEndpoint(nid, eid string) error {
  904. var err error
  905. // Get the network handler and make sure it exists
  906. d.Lock()
  907. n, ok := d.networks[nid]
  908. d.Unlock()
  909. if !ok {
  910. return types.NotFoundErrorf("network %s does not exist", nid)
  911. }
  912. if n == nil {
  913. return driverapi.ErrNoNetwork(nid)
  914. }
  915. // Sanity Check
  916. n.Lock()
  917. if n.id != nid {
  918. n.Unlock()
  919. return InvalidNetworkIDError(nid)
  920. }
  921. n.Unlock()
  922. // Check endpoint id and if an endpoint is actually there
  923. ep, err := n.getEndpoint(eid)
  924. if err != nil {
  925. return err
  926. }
  927. if ep == nil {
  928. return EndpointNotFoundError(eid)
  929. }
  930. // Remove it
  931. n.Lock()
  932. delete(n.endpoints, eid)
  933. n.Unlock()
  934. // On failure make sure to set back ep in n.endpoints, but only
  935. // if it hasn't been taken over already by some other thread.
  936. defer func() {
  937. if err != nil {
  938. n.Lock()
  939. if _, ok := n.endpoints[eid]; !ok {
  940. n.endpoints[eid] = ep
  941. }
  942. n.Unlock()
  943. }
  944. }()
  945. // Remove port mappings. Do not stop endpoint delete on unmap failure
  946. n.releasePorts(ep)
  947. // Release the v4 address allocated to this endpoint's sandbox interface
  948. err = ipAllocator.ReleaseIP(n.bridge.bridgeIPv4, ep.addr.IP)
  949. if err != nil {
  950. return err
  951. }
  952. n.Lock()
  953. config := n.config
  954. n.Unlock()
  955. // Release the v6 address allocated to this endpoint's sandbox interface
  956. if config.EnableIPv6 {
  957. network := n.bridge.bridgeIPv6
  958. if config.FixedCIDRv6 != nil {
  959. network = config.FixedCIDRv6
  960. }
  961. err := ipAllocator.ReleaseIP(network, ep.addrv6.IP)
  962. if err != nil {
  963. return err
  964. }
  965. }
  966. // Try removal of link. Discard error: link pair might have
  967. // already been deleted by sandbox delete. Make sure defer
  968. // does not see this error either.
  969. if link, err := netlink.LinkByName(ep.srcName); err == nil {
  970. netlink.LinkDel(link)
  971. }
  972. return nil
  973. }
  974. func (d *driver) EndpointOperInfo(nid, eid string) (map[string]interface{}, error) {
  975. // Get the network handler and make sure it exists
  976. d.Lock()
  977. n, ok := d.networks[nid]
  978. d.Unlock()
  979. if !ok {
  980. return nil, types.NotFoundErrorf("network %s does not exist", nid)
  981. }
  982. if n == nil {
  983. return nil, driverapi.ErrNoNetwork(nid)
  984. }
  985. // Sanity check
  986. n.Lock()
  987. if n.id != nid {
  988. n.Unlock()
  989. return nil, InvalidNetworkIDError(nid)
  990. }
  991. n.Unlock()
  992. // Check if endpoint id is good and retrieve correspondent endpoint
  993. ep, err := n.getEndpoint(eid)
  994. if err != nil {
  995. return nil, err
  996. }
  997. if ep == nil {
  998. return nil, driverapi.ErrNoEndpoint(eid)
  999. }
  1000. m := make(map[string]interface{})
  1001. if ep.config.ExposedPorts != nil {
  1002. // Return a copy of the config data
  1003. epc := make([]types.TransportPort, 0, len(ep.config.ExposedPorts))
  1004. for _, tp := range ep.config.ExposedPorts {
  1005. epc = append(epc, tp.GetCopy())
  1006. }
  1007. m[netlabel.ExposedPorts] = epc
  1008. }
  1009. if ep.portMapping != nil {
  1010. // Return a copy of the operational data
  1011. pmc := make([]types.PortBinding, 0, len(ep.portMapping))
  1012. for _, pm := range ep.portMapping {
  1013. pmc = append(pmc, pm.GetCopy())
  1014. }
  1015. m[netlabel.PortMap] = pmc
  1016. }
  1017. if len(ep.macAddress) != 0 {
  1018. m[netlabel.MacAddress] = ep.macAddress
  1019. }
  1020. return m, nil
  1021. }
  1022. // Join method is invoked when a Sandbox is attached to an endpoint.
  1023. func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error {
  1024. network, err := d.getNetwork(nid)
  1025. if err != nil {
  1026. return err
  1027. }
  1028. endpoint, err := network.getEndpoint(eid)
  1029. if err != nil {
  1030. return err
  1031. }
  1032. if endpoint == nil {
  1033. return EndpointNotFoundError(eid)
  1034. }
  1035. for _, iNames := range jinfo.InterfaceNames() {
  1036. // Make sure to set names on the correct interface ID.
  1037. if iNames.ID() == ifaceID {
  1038. err = iNames.SetNames(endpoint.srcName, containerVethPrefix)
  1039. if err != nil {
  1040. return err
  1041. }
  1042. }
  1043. }
  1044. err = jinfo.SetGateway(network.bridge.gatewayIPv4)
  1045. if err != nil {
  1046. return err
  1047. }
  1048. err = jinfo.SetGatewayIPv6(network.bridge.gatewayIPv6)
  1049. if err != nil {
  1050. return err
  1051. }
  1052. if !network.config.EnableICC {
  1053. return d.link(network, endpoint, options, true)
  1054. }
  1055. return nil
  1056. }
  1057. // Leave method is invoked when a Sandbox detaches from an endpoint.
  1058. func (d *driver) Leave(nid, eid string) error {
  1059. network, err := d.getNetwork(nid)
  1060. if err != nil {
  1061. return err
  1062. }
  1063. endpoint, err := network.getEndpoint(eid)
  1064. if err != nil {
  1065. return err
  1066. }
  1067. if endpoint == nil {
  1068. return EndpointNotFoundError(eid)
  1069. }
  1070. if !network.config.EnableICC {
  1071. return d.link(network, endpoint, nil, false)
  1072. }
  1073. return nil
  1074. }
  1075. func (d *driver) link(network *bridgeNetwork, endpoint *bridgeEndpoint, options map[string]interface{}, enable bool) error {
  1076. var (
  1077. cc *containerConfiguration
  1078. err error
  1079. )
  1080. if enable {
  1081. cc, err = parseContainerOptions(options)
  1082. if err != nil {
  1083. return err
  1084. }
  1085. } else {
  1086. cc = endpoint.containerConfig
  1087. }
  1088. if cc == nil {
  1089. return nil
  1090. }
  1091. if endpoint.config != nil && endpoint.config.ExposedPorts != nil {
  1092. for _, p := range cc.ParentEndpoints {
  1093. var parentEndpoint *bridgeEndpoint
  1094. parentEndpoint, err = network.getEndpoint(p)
  1095. if err != nil {
  1096. return err
  1097. }
  1098. if parentEndpoint == nil {
  1099. err = InvalidEndpointIDError(p)
  1100. return err
  1101. }
  1102. l := newLink(parentEndpoint.addr.IP.String(),
  1103. endpoint.addr.IP.String(),
  1104. endpoint.config.ExposedPorts, network.config.BridgeName)
  1105. if enable {
  1106. err = l.Enable()
  1107. if err != nil {
  1108. return err
  1109. }
  1110. defer func() {
  1111. if err != nil {
  1112. l.Disable()
  1113. }
  1114. }()
  1115. } else {
  1116. l.Disable()
  1117. }
  1118. }
  1119. }
  1120. for _, c := range cc.ChildEndpoints {
  1121. var childEndpoint *bridgeEndpoint
  1122. childEndpoint, err = network.getEndpoint(c)
  1123. if err != nil {
  1124. return err
  1125. }
  1126. if childEndpoint == nil {
  1127. err = InvalidEndpointIDError(c)
  1128. return err
  1129. }
  1130. if childEndpoint.config == nil || childEndpoint.config.ExposedPorts == nil {
  1131. continue
  1132. }
  1133. l := newLink(endpoint.addr.IP.String(),
  1134. childEndpoint.addr.IP.String(),
  1135. childEndpoint.config.ExposedPorts, network.config.BridgeName)
  1136. if enable {
  1137. err = l.Enable()
  1138. if err != nil {
  1139. return err
  1140. }
  1141. defer func() {
  1142. if err != nil {
  1143. l.Disable()
  1144. }
  1145. }()
  1146. } else {
  1147. l.Disable()
  1148. }
  1149. }
  1150. if enable {
  1151. endpoint.containerConfig = cc
  1152. }
  1153. return nil
  1154. }
  1155. func (d *driver) Type() string {
  1156. return networkType
  1157. }
  1158. func parseEndpointOptions(epOptions map[string]interface{}) (*endpointConfiguration, error) {
  1159. if epOptions == nil {
  1160. return nil, nil
  1161. }
  1162. ec := &endpointConfiguration{}
  1163. if opt, ok := epOptions[netlabel.MacAddress]; ok {
  1164. if mac, ok := opt.(net.HardwareAddr); ok {
  1165. ec.MacAddress = mac
  1166. } else {
  1167. return nil, &ErrInvalidEndpointConfig{}
  1168. }
  1169. }
  1170. if opt, ok := epOptions[netlabel.PortMap]; ok {
  1171. if bs, ok := opt.([]types.PortBinding); ok {
  1172. ec.PortBindings = bs
  1173. } else {
  1174. return nil, &ErrInvalidEndpointConfig{}
  1175. }
  1176. }
  1177. if opt, ok := epOptions[netlabel.ExposedPorts]; ok {
  1178. if ports, ok := opt.([]types.TransportPort); ok {
  1179. ec.ExposedPorts = ports
  1180. } else {
  1181. return nil, &ErrInvalidEndpointConfig{}
  1182. }
  1183. }
  1184. return ec, nil
  1185. }
  1186. func parseContainerOptions(cOptions map[string]interface{}) (*containerConfiguration, error) {
  1187. if cOptions == nil {
  1188. return nil, nil
  1189. }
  1190. genericData := cOptions[netlabel.GenericData]
  1191. if genericData == nil {
  1192. return nil, nil
  1193. }
  1194. switch opt := genericData.(type) {
  1195. case options.Generic:
  1196. opaqueConfig, err := options.GenerateFromModel(opt, &containerConfiguration{})
  1197. if err != nil {
  1198. return nil, err
  1199. }
  1200. return opaqueConfig.(*containerConfiguration), nil
  1201. case *containerConfiguration:
  1202. return opt, nil
  1203. default:
  1204. return nil, nil
  1205. }
  1206. }
  1207. func electMacAddress(epConfig *endpointConfiguration, ip net.IP) net.HardwareAddr {
  1208. if epConfig != nil && epConfig.MacAddress != nil {
  1209. return epConfig.MacAddress
  1210. }
  1211. return netutils.GenerateMACFromIP(ip)
  1212. }