bridge.go 36 KB

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