bridge.go 36 KB

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