bridge.go 38 KB

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