bridge.go 39 KB

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