bridge.go 37 KB

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