bridge.go 40 KB

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