bridge_linux.go 41 KB

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