ffho_net.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886
  1. #!/usr/bin/python
  2. import re
  3. mac_prefix = "f2"
  4. vrf_info = {
  5. 'vrf_external' : {
  6. 'table' : 1023,
  7. 'fwmark' : [ '0x1', '0x1023' ],
  8. },
  9. }
  10. sites = None
  11. def _get_site_no (sites_config, site_name):
  12. global sites
  13. if sites == None:
  14. sites = {}
  15. for site in sites_config:
  16. if site.startswith ("_"):
  17. continue
  18. sites[site] = sites_config[site].get ("site_no", -2)
  19. return sites.get (site_name, -1)
  20. #
  21. # Generate a MAC address after the format f2:dd:dd:ss:nn:nn where
  22. # dd:dd is the hexadecimal reprensentation of the nodes device_id
  23. # ff:ff representing the gluon nodes
  24. #
  25. # ss is the hexadecimal reprensentation of the site_id the interface is connected to
  26. #
  27. # nn:nn is the decimal representation of the network the interface is connected to, with
  28. # 00:00 being the dummy interface
  29. # 00:0f being the VEth internal side interface
  30. # 00:e0 being an external instance dummy interface
  31. # 00:e1 being an inter-gw-vpn interface
  32. # 00:e4 being an nodes fastd tunnel interface of IPv4 transport
  33. # 00:e6 being an nodes fastd tunnel interface of IPv6 transport
  34. # 00:ef being an extenral instance VEth interface side
  35. # 02:xx being a connection to local Vlan 2xx
  36. # 1b:24 being the ibss 2.4GHz bssid
  37. # 1b:05 being the ibss 5GHz bssid
  38. # ff:ff being the gluon next-node interface
  39. # xx:xx being a VXLAN tunnel for site ss, with xx being a the underlay VLAN ID (1xyz, 2xyz)
  40. def gen_batman_iface_mac (site_no, device_no, network):
  41. net_type_map = {
  42. 'dummy' : "00:00",
  43. 'int2ext' : "00:0f",
  44. 'dummy-e' : "00:e0",
  45. 'intergw' : "00:e1",
  46. 'nodes4' : "00:e4",
  47. 'nodes6' : "00:e6",
  48. 'ext2int' : "00:ef",
  49. }
  50. # Well-known network type?
  51. if network in net_type_map:
  52. last = net_type_map[network]
  53. elif type (network) == int:
  54. last = re.sub (r'(\d{2})(\d{2})', '\g<1>:\g<2>', "%04d" % network)
  55. else:
  56. last = "ee:ee"
  57. # Convert device_no to hex, format number to 4 digits with leading zeros and : betwwen 2nd and 3rd digit
  58. device_no_hex = re.sub (r'([0-9a-fA-F]{2})([0-9a-fA-F]{2})', '\g<1>:\g<2>', "%04x" % int (device_no))
  59. # Format site_no to two digit number with leading zero
  60. site_no_hex = "%02d" % int (site_no)
  61. return "%s:%s:%s:%s" % (mac_prefix, device_no_hex, site_no_hex, last)
  62. #
  63. # Default parameters added to any given bonding/bridge interface,
  64. # if not specified at the interface configuration.
  65. default_bond_config = {
  66. 'bond-mode': '802.3ad',
  67. 'bond-min-links': '1',
  68. 'bond-xmit-hash-policy': 'layer3+4'
  69. }
  70. default_bridge_config = {
  71. 'bridge-fd' : '0',
  72. 'bridge-stp' : 'no'
  73. }
  74. #
  75. # Hop penalty to set if none is explicitly specified
  76. # Check if one of these roles is configured for any given node, use first match.
  77. default_hop_penalty_by_role = {
  78. 'bbr' : 5,
  79. 'bras' : 50,
  80. 'batman_gw' : 50,
  81. }
  82. batman_role_evaluation_order = [ 'bbr', 'batman_gw', 'bras' ]
  83. # Gather B.A.T.M.A.N. related config options for real batman devices (e.g. bat0)
  84. # as well as for batman member interfaces (e.g. eth0.100, fastd ifaces etc.)
  85. def _update_batman_config (node_config, iface, sites_config):
  86. try:
  87. node_batman_hop_penalty = int (node_config['batman']['hop-penalty'])
  88. except KeyError,ValueError:
  89. node_batman_hop_penalty = None
  90. iface_config = node_config['ifaces'][iface]
  91. iface_type = iface_config.get ('type', 'inet')
  92. batman_config = {}
  93. for item, value in iface_config.items ():
  94. if item.startswith ('batman-'):
  95. batman_config[item] = value
  96. iface_config.pop (item)
  97. # B.A.T.M.A.N. device (e.g. bat0)
  98. if iface_type == 'batman':
  99. if 'batman-hop-penalty' not in batman_config:
  100. # If there's a hop penalty set for the node, but not for the interface
  101. # apply the nodes hop penalty
  102. if node_batman_hop_penalty:
  103. batman_config['batman-hop-penalty'] = node_batman_hop_penalty
  104. # If there's no hop penalty set for the node, use a default hop penalty
  105. # for the roles the node might have, if any
  106. else:
  107. node_roles = node_config.get ('roles', [])
  108. for role in batman_role_evaluation_order:
  109. if role in node_roles:
  110. batman_config['batman-hop-penalty'] = default_hop_penalty_by_role[role]
  111. # If batman ifaces were specified as a list - which they should -
  112. # generate a sorted list of interface names as string representation
  113. if 'batman-ifaces' in batman_config and type (batman_config['batman-ifaces']) == list:
  114. batman_iface_str = " ".join (sorted (batman_config['batman-ifaces']))
  115. batman_config['batman-ifaces'] = batman_iface_str
  116. # B.A.T.M.A.N. member interface (e.g. eth.100, fastd ifaces, etc.)
  117. elif iface_type == 'batman_iface':
  118. # Generate unique MAC address for every batman iface, as B.A.T.M.A.N.
  119. # will get puzzled with multiple interfaces having the same MAC and
  120. # do nasty things.
  121. site = iface_config.get ('site')
  122. site_no = _get_site_no (sites_config, site)
  123. device_no = node_config.get ('id')
  124. network = 1234
  125. # Generate a unique BATMAN-MAC for this interfaces
  126. match = re.search (r'^vlan(\d+)', iface)
  127. if match:
  128. network = int (match.group (1))
  129. iface_config['hwaddress'] = gen_batman_iface_mac (site_no, device_no, network)
  130. iface_config['batman'] = batman_config
  131. # Mangle bond specific config items with default values and store them in
  132. # separate sub-dict for easier access and configuration.
  133. def _update_bond_config (config):
  134. bond_config = default_bond_config.copy ()
  135. for item, value in config.items ():
  136. if item.startswith ('bond-'):
  137. bond_config[item] = value
  138. config.pop (item)
  139. if bond_config['bond-mode'] not in ['2', 'balance-xor', '4', '802.3ad']:
  140. bond_config.pop ('bond-xmit-hash-policy')
  141. config['bond'] = bond_config
  142. # Mangle bridge specific config items with default values and store them in
  143. # separate sub-dict for easier access and configuration.
  144. def _update_bridge_config (config):
  145. bridge_config = default_bridge_config.copy ()
  146. for item, value in config.items ():
  147. if item.startswith ('bridge-'):
  148. bridge_config[item] = value
  149. config.pop (item)
  150. # Fix and salt mangled string interpretation back to real string.
  151. if type (value) == bool:
  152. bridge_config[item] = "yes" if value else "no"
  153. # If bridge ports were specified as a list - which they should -
  154. # generate a sorted list of interface names as string representation
  155. if 'bridge-ports' in bridge_config and type (bridge_config['bridge-ports']) == list:
  156. bridge_ports_str = " ".join (sorted (bridge_config['bridge-ports']))
  157. bridge_config['bridge-ports'] = bridge_ports_str
  158. config['bridge'] = bridge_config
  159. # Move vlan specific config items into a sub-dict for easier access and pretty-printing
  160. # in the configuration file
  161. def _update_vlan_config (config):
  162. vlan_config = {}
  163. for item, value in config.items ():
  164. if item.startswith ('vlan-'):
  165. vlan_config[item] = value
  166. config.pop (item)
  167. config['vlan'] = vlan_config
  168. # Pimp Veth interfaces
  169. # * Add peer interface name IF not present
  170. # * Add link-type veth IF not present
  171. def _update_veth_config (interface, config):
  172. veth_peer_name = {
  173. 'veth_ext2int' : 'veth_int2ext',
  174. 'veth_int2ext' : 'veth_ext2int'
  175. }
  176. if interface not in veth_peer_name:
  177. return
  178. if 'link-type' not in config:
  179. config['link-type'] = 'veth'
  180. if 'veth-peer-name' not in config:
  181. config['veth-peer-name'] = veth_peer_name[interface]
  182. # Generate configuration entries for any batman related interfaces not
  183. # configured explicitly, but asked for implicitly by role batman and a
  184. # (list of) site(s) specified in the node config.
  185. def _generate_batman_interface_config (node_config, ifaces, sites_config):
  186. # No role 'batman', nothing to do
  187. roles = node_config.get ('roles', [])
  188. if 'batman' not in roles:
  189. return
  190. # Should there be a 2nd external BATMAN instance?
  191. batman_ext = 'batman_ext' in roles or 'bras' in roles
  192. device_no = node_config.get ('id', -1)
  193. for site in node_config.get ('sites', []):
  194. site_no = _get_site_no (sites_config, site)
  195. # Predefine interface names for regular/external BATMAN instance
  196. # and possible VEth link pair for connecting both instances.
  197. bat_site_if = "bat-%s" % site
  198. dummy_site_if = "dummy-%s" % site
  199. bat_site_if_ext = "bat-%s-ext" % site
  200. dummy_site_if_ext = "dummy-%s-e" % site
  201. int2ext_site_if = "i2e-%s" % site
  202. ext2int_site_if = "e2i-%s" % site
  203. site_ifaces = {
  204. # Regular BATMAN interface, always present
  205. bat_site_if : {
  206. 'type' : 'batman',
  207. # int2ext_site_if will be added automagically if requred
  208. 'batman-ifaces' : [ dummy_site_if ],
  209. 'batman-ifaces-ignore-regex': '.*_.*',
  210. },
  211. # Dummy interface always present in regular BATMAN instance
  212. dummy_site_if : {
  213. 'link-type' : 'dummy',
  214. 'hwaddress' : gen_batman_iface_mac (site_no, device_no, 'dummy'),
  215. },
  216. # Optional 2nd "external" BATMAN instance
  217. bat_site_if_ext : {
  218. 'type' : 'batman',
  219. 'batman-ifaces' : [ dummy_site_if_ext, ext2int_site_if ],
  220. 'batman-ifaces-ignore-regex': '.*_.*',
  221. 'ext_only' : True,
  222. },
  223. # Optional dummy interface always present in 2nd "external" BATMAN instance
  224. dummy_site_if_ext : {
  225. 'link-type' : 'dummy',
  226. 'hwaddress' : gen_batman_iface_mac (site_no, device_no, 'dummy-e'),
  227. 'ext_only' : True,
  228. },
  229. # Optional VEth interface pair - internal side
  230. int2ext_site_if : {
  231. 'link-type' : 'veth',
  232. 'veth-peer-name' : ext2int_site_if,
  233. 'hwaddress' : gen_batman_iface_mac (site_no, device_no, 'int2ext'),
  234. 'ext_only' : True,
  235. },
  236. # Optional VEth interface pair - "external" side
  237. ext2int_site_if : {
  238. 'link-type' : 'veth',
  239. 'veth-peer-name' : int2ext_site_if,
  240. 'hwaddress' : gen_batman_iface_mac (site_no, device_no, 'ext2int'),
  241. 'ext_only' : True,
  242. },
  243. }
  244. for iface, iface_config_tmpl in site_ifaces.items ():
  245. # Ignore any interface only relevant when role batman_ext is set
  246. # but it isn't
  247. if not batman_ext and iface_config_tmpl.get ('ext_only', False):
  248. continue
  249. # Remove ext_only key so we don't leak it into ifaces dict
  250. if 'ext_only' in iface_config_tmpl:
  251. del iface_config_tmpl['ext_only']
  252. # If there is no trace of the desired iface config yet...
  253. if iface not in ifaces:
  254. # ... just place our template there.
  255. ifaces[iface] = iface_config_tmpl
  256. # If there should be an 2nd external BATMAN instance make sure
  257. # the internal side of the VEth iface pair is connected to the
  258. # internal BATMAN instance.
  259. if batman_ext and iface == bat_site_if:
  260. iface_config_tmpl['batman-ifaces'].append (int2ext_site_if)
  261. # If there already is an interface configuration try to enhance it with
  262. # meaningful values from our template and force correct hwaddress to be
  263. # used.
  264. else:
  265. iface_config = ifaces[iface]
  266. # Force hwaddress to be what we expect.
  267. if 'hwaddress' in iface_config_tmpl:
  268. iface_config['hwaddress'] = iface_config_tmpl['hwaddress']
  269. # Copy every attribute of the config template missing in iface config
  270. for attr in iface_config_tmpl:
  271. if attr not in iface_config:
  272. iface_config[attr] = iface_config_tmpl[attr]
  273. # Make sure there is a bridge present for every site where a mesh_breakout
  274. # interface should be configured.
  275. for iface, config in ifaces.items ():
  276. iface_type = config.get ('type', 'inet')
  277. if iface_type not in ['mesh_breakout', 'batman_iface']:
  278. continue
  279. site = config.get ('site')
  280. site_bridge = "br-%s" % site
  281. batman_site_if = "bat-%s" % site
  282. if iface_type == 'mesh_breakout':
  283. # If the bridge has already been defined (with an IP maybe) make
  284. # sure that the corresbonding batman device is part of the bridge-
  285. # ports.
  286. if site_bridge in ifaces:
  287. bridge_config = ifaces.get (site_bridge)
  288. # If there already is/are (a) bridge-port(s) defined, add
  289. # the batman and the breakout interfaces if not present...
  290. bridge_ports = bridge_config.get ('bridge-ports', None)
  291. if bridge_ports:
  292. for dev in (batman_site_if, iface):
  293. if not dev in bridge_ports:
  294. if type (bridge_ports) == list:
  295. bridge_ports.append (dev)
  296. else:
  297. bridge_config['bridge-ports'] += ' ' + dev
  298. # ...if there is no bridge-port defined yet, just used
  299. # the batman and breakout iface.
  300. else:
  301. bridge_config['bridge-ports'] = [ iface, batman_site_if ]
  302. # If the bridge isn't present alltogether, add it.
  303. else:
  304. ifaces[site_bridge] = {
  305. 'bridge-ports' : [ iface, batman_site_if ],
  306. }
  307. elif iface_type == 'batman_iface':
  308. batman_ifaces = ifaces[bat_site_if]['batman-ifaces']
  309. if iface not in batman_ifaces:
  310. if type (batman_ifaces) == list:
  311. batman_ifaces.append (iface)
  312. else:
  313. batman_ifaces += ' ' + iface
  314. ## Generate VXLAN tunnels for every configured batman peer for every site
  315. ## configured on this and the peer node.
  316. #def _generate_vxlan_interface_config_complex (node_config, ifaces, node_id, nodes_config):
  317. # # No role 'batman', nothing to do
  318. # if 'batman' not in node_config.get ('roles', []):
  319. # return
  320. #
  321. # # No batman peers configred, nothing to do
  322. # try:
  323. # peers = node_config['batman']['peers']
  324. # if type (peers) != list:
  325. # return
  326. # except KeyError:
  327. # return
  328. #
  329. # # Sites configured on this node. Nothing to do, if none.
  330. # my_sites = node_config.get ('sites', [])
  331. # if len (my_sites) == 0:
  332. # return
  333. #
  334. # device_no = node_config.get ('id', -1)
  335. #
  336. # # ...
  337. # for peer in peers:
  338. # try:
  339. # # Try to get node config of peer
  340. # peer_config = nodes_config.get (peer)
  341. #
  342. # # Not a batman node?
  343. # if not 'batman' in peer_config['roles']:
  344. # continue
  345. #
  346. # # Verify we are in peers list of peer
  347. # peers_of_peer = peer_config['batman']['peers']
  348. # if type (peers_of_peer) != list:
  349. # continue
  350. # if node_id not in peers_of_peer:
  351. # continue
  352. #
  353. # # Get sites configured on peers
  354. # sites_of_peer = peer_config.get ('sites')
  355. # except KeyError:
  356. # continue
  357. #
  358. # for site in my_sites:
  359. # if site not in sites_of_peer:
  360. # continue
  361. #
  362. # # Build tunnel here
  363. def _generate_vxlan_interface_config (node_config, ifaces, sites_config):
  364. # No role 'batman', nothing to do
  365. if 'batman' not in node_config.get ('roles', []):
  366. return
  367. # Sites configured on this node. Nothing to do, if none.
  368. my_sites = node_config.get ('sites', [])
  369. if len (my_sites) == 0:
  370. return
  371. # As we're still here we can now safely assume that a B.A.T.M.A.N.
  372. # device has been configured for every site specified in sites list.
  373. device_no = node_config.get ('id', -1)
  374. for iface, iface_config in ifaces.items ():
  375. batman_connect_sites = iface_config.get ('batman_connect_sites', [])
  376. # If we got a string, convert it to a list with a single element
  377. if type (batman_connect_sites) == str:
  378. batman_connect_sites = [ batman_connect_sites ]
  379. # If the string 'all' is part of the list, blindly use all sites configured for this node
  380. if 'all' in batman_connect_sites:
  381. batman_connect_sites = my_sites
  382. for site in batman_connect_sites:
  383. # Silenty ignore sites not configured on this node
  384. if site not in my_sites:
  385. continue
  386. # iface_name := vx_<last 5 chars of underlay iface>_<site> stripped to 15 chars
  387. vx_iface = "vx_%s_%s" % (re.sub ('vlan', 'v', iface)[-5:], site)[:15]
  388. site_no = _get_site_no (sites_config, site)
  389. vni = 100 + site_no
  390. bat_iface = "bat-%s" % site
  391. try:
  392. iface_id = int (re.sub ('vlan', '', iface))
  393. # Gather interface specific mcast address.
  394. # The address is derived from the vlan-id of the underlying interface,
  395. # assuming that it in fact is a vlan interface.
  396. # Mangle the vlan-id into two 2 digit values, eliminating any leading zeros.
  397. iface_id_4digit = "%04d" % iface_id
  398. octet2 = int (iface_id_4digit[0:2])
  399. octet3 = int (iface_id_4digit[2:4])
  400. mcast_ip = "225.%s.%s.%s" % (octet2, octet3, site_no)
  401. vni = octet2 * 256 * 256 + octet3 * 256 + site_no
  402. except ValueError:
  403. iface_id = 9999
  404. mcast_ip = "225.0.0.%s" % site_no
  405. vni = site_no
  406. # bail out if VXLAN tunnel already configured
  407. if vx_iface in ifaces:
  408. continue
  409. # If there's no batman interface for this site, there's no point
  410. # in setting up a VXLAN interfaces
  411. if bat_iface not in ifaces:
  412. continue
  413. # Add the VXLAN interface
  414. ifaces[vx_iface] = {
  415. 'vxlan' : {
  416. 'vxlan-id' : vni,
  417. 'vxlan-svcnodeip' : mcast_ip,
  418. 'vxlan-physdev' : iface,
  419. },
  420. 'hwaddress' : gen_batman_iface_mac (site_no, device_no, iface_id),
  421. }
  422. # If the batman interface for this site doesn't have any interfaces
  423. # set up - which basicly cannot happen - add this VXLAN tunnel as
  424. # the first in the list.
  425. if not 'batman-ifaces' in ifaces[bat_iface]:
  426. ifaces[bat_iface]['batman-ifaces'] = [ vx_iface ]
  427. continue
  428. # In the hope there already are interfaces for batman set up already
  429. # add this VXLAN tunnel to the list
  430. batman_ifaces = ifaces[bat_iface]['batman-ifaces']
  431. if vx_iface not in batman_ifaces:
  432. if type (batman_ifaces) == list:
  433. batman_ifaces.append (vx_iface)
  434. else:
  435. batman_ifaces += ' ' + vx_iface
  436. def _generate_vrfs (ifaces):
  437. for iface, iface_config in ifaces.items ():
  438. vrf = iface_config.get ('vrf', None)
  439. if vrf and vrf not in ifaces:
  440. conf = vrf_info.get (vrf, {})
  441. table = conf.get ('table', 1234)
  442. fwmark = conf.get ('fwmark', None)
  443. ifaces[vrf] = {
  444. 'vrf-table' : table,
  445. }
  446. # Create ip rule's for any fwmarks defined
  447. if fwmark:
  448. up = []
  449. # Make sure we are dealing with a list even if there is only one mark to be set up
  450. if type (fwmark) in (str, int):
  451. fwmark = [ fwmark ]
  452. # Create ip rule entries for IPv4 and IPv6 for every fwmark
  453. for mark in fwmark:
  454. up.append ("ip rule add fwmark %s table %s" % (mark, table))
  455. up.append ("ip -6 rule add fwmark %s table %s" % (mark, table))
  456. ifaces[vrf]['up'] = up
  457. GRE_FFRL_attrs = {
  458. 'mode' : 'gre',
  459. 'method' : 'tunnel',
  460. 'mtu' : '1400',
  461. 'ttl' : '64',
  462. }
  463. def _generate_ffrl_gre_tunnels (ifaces):
  464. for iface, iface_config in ifaces.items ():
  465. # We only care for GRE_FFRL type interfaces
  466. if iface_config.get ('type', '') != 'GRE_FFRL':
  467. continue
  468. # Copy default values to interface config
  469. for attr, val in GRE_FFRL_attrs.items ():
  470. if not attr in iface_config:
  471. iface_config[attr] = val
  472. # Guesstimate local IPv4 tunnel endpoint address from tunnel-physdev
  473. if not 'local' in iface_config and 'tunnel-physdev' in iface_config:
  474. try:
  475. physdev_prefixes = [p.split ('/')[0] for p in ifaces[iface_config['tunnel-physdev']]['prefixes'] if '.' in p]
  476. if len (physdev_prefixes) == 1:
  477. iface_config['local'] = physdev_prefixes[0]
  478. except KeyError:
  479. pass
  480. def get_interface_config (node_config, sites_config, node_id = ""):
  481. # Get config of this node and dict of all configured ifaces
  482. ifaces = node_config.get ('ifaces', {})
  483. # Generate configuration entries for any batman related interfaces not
  484. # configured explicitly, but asked for implicitly by role <batman> and
  485. # a (list of) site(s) specified in the node config.
  486. _generate_batman_interface_config (node_config, ifaces, sites_config)
  487. # Generate VXLAN tunnels for every interfaces specifying 'batman_connect_sites'
  488. _generate_vxlan_interface_config (node_config, ifaces, sites_config)
  489. # Enhance ifaces configuration with some meaningful defaults for
  490. # bonding, bridge and vlan interfaces, MAC address for batman ifaces, etc.
  491. for interface, config in ifaces.items ():
  492. if type (config) != dict:
  493. raise Exception ("Configuration for interface %s on node %s seems broken!" % (interface, node_id))
  494. iface_type = config.get ('type', 'inet')
  495. if 'batman-ifaces' in config or iface_type.startswith ('batman'):
  496. _update_batman_config (node_config, interface, sites_config)
  497. if 'bond-slaves' in config:
  498. _update_bond_config (config)
  499. # FIXME: This maybe will not match on bridges without any member ports configured!
  500. if 'bridge-ports' in config or interface.startswith ('br-'):
  501. _update_bridge_config (config)
  502. if 'vlan-raw-device' in config or 'vlan-id' in config:
  503. _update_vlan_config (config)
  504. # Pimp configuration for VEth link pairs
  505. if interface.startswith ('veth_'):
  506. _update_veth_config (interface, config)
  507. # Auto generated VRF devices for any VRF found in ifaces and not already configured.
  508. _generate_vrfs (ifaces)
  509. # Pimp GRE_FFRL type inteface configuration with default values
  510. _generate_ffrl_gre_tunnels (ifaces)
  511. # Drop any config parameters used in node interface configuration not
  512. # relevant anymore for config file generation.
  513. for interface, config in ifaces.items ():
  514. for key in [ 'batman_connect_sites', 'ospf', 'site', 'type' ]:
  515. if key in config:
  516. config.pop (key)
  517. # This leaves 'auto', 'prefixes' and 'desc' as keys which should not be directly
  518. # printed into the remaining configuration. These are handled within the jinja
  519. # interface template.
  520. return ifaces
  521. # Generate entries for /etc/bat-hosts for every batman interface we will configure on any node.
  522. # For readability purposes superflous/redundant information is being stripped/supressed.
  523. # As these names will only show up in batctl calls with a specific site, site_names in interfaces
  524. # are stripped. Dummy interfaces are stripped as well.
  525. def gen_bat_hosts (nodes_config, sites_config):
  526. bat_hosts = {}
  527. for node_id in sorted (nodes_config.keys ()):
  528. node_config = nodes_config.get (node_id)
  529. node_name = node_id.split ('.')[0]
  530. ifaces = get_interface_config (node_config, sites_config, node_id)
  531. for iface in sorted (ifaces):
  532. iface_config = ifaces.get (iface)
  533. hwaddress = iface_config.get ('hwaddress', None)
  534. if hwaddress == None:
  535. continue
  536. entry_name = node_name
  537. match = re.search (r'^dummy-(.+)(-e)?$', iface)
  538. if match:
  539. if match.group (2):
  540. entry_name += "-e"
  541. # Append site to make name unique
  542. entry_name += "/%s" % match.group (1)
  543. else:
  544. entry_name += "/%s" % re.sub (r'^(vx_.*|i2e|e2i)[_-](.*)$', '\g<1>/\g<2>', iface)
  545. bat_hosts[hwaddress] = entry_name
  546. if 'fastd' in node_config.get ('roles', []):
  547. device_no = node_config.get ('id')
  548. for site in node_config.get ('sites', []):
  549. site_no = _get_site_no (sites_config, site)
  550. for network in ('intergw', 'nodes4', 'nodes6'):
  551. hwaddress = gen_batman_iface_mac (site_no, device_no, network)
  552. bat_hosts[hwaddress] = "%s/%s/%s" % (node_name, network, site)
  553. return bat_hosts
  554. # Generate eBGP session parameters for FFRL Transit from nodes pillar information.
  555. def get_ffrl_bgp_config (ifaces, proto):
  556. from ipcalc import IP
  557. _generate_ffrl_gre_tunnels (ifaces)
  558. sessions = {}
  559. for iface in sorted (ifaces):
  560. # We only care for GRE tunnels to the FFRL Backbone
  561. if not iface.startswith ('gre_ffrl_'):
  562. continue
  563. iface_config = ifaces.get (iface)
  564. # Search for IPv4/IPv6 prefix as defined by proto parameter
  565. local = None
  566. neighbor = None
  567. for prefix in iface_config.get ('prefixes', []):
  568. if (proto == 'v4' and '.' in prefix) or (proto == 'v6' and ':' in prefix):
  569. local = prefix.split ('/')[0]
  570. # Calculate neighbor IP as <local IP> - 1
  571. if proto == 'v4':
  572. neighbor = str (IP (int (IP (local)) - 1, version = 4))
  573. else:
  574. neighbor = str (IP (int (IP (local)) - 1, version = 6))
  575. break
  576. # Strip gre_ prefix iface name and use it as identifier for the eBGP session.
  577. name = re.sub ('gre_ffrl_', 'ffrl_', iface)
  578. sessions[name] = {
  579. 'local' : local,
  580. 'neighbor' : neighbor,
  581. 'bgp_local_pref' : iface_config.get ('bgp_local_pref', None),
  582. }
  583. return sessions
  584. # Get list of IP address configured on given interface on given node.
  585. #
  586. # @param: node_config Pillar node configuration (as dict)
  587. # @param: iface_name Name of the interface defined in pillar node config
  588. # OR name of VRF ("vrf_<something>") whichs ifaces are
  589. # to be examined.
  590. def get_node_iface_ips (node_config, iface_name):
  591. ips = {
  592. 'v4' : [],
  593. 'v6' : [],
  594. }
  595. ifaces = node_config.get ('ifaces', {})
  596. ifaces_names = [ iface_name ]
  597. if iface_name.startswith ('vrf_'):
  598. # Reset list of ifaces_names to consider
  599. ifaces_names = []
  600. vrf = iface_name
  601. for iface, iface_config in ifaces.items ():
  602. # Ignore any iface NOT in the given VRF
  603. if iface_config.get ('vrf', None) != vrf:
  604. continue
  605. # Ignore any VEth pairs
  606. if iface.startswith ('veth'):
  607. continue
  608. ifaces_names.append (iface)
  609. try:
  610. for iface in ifaces_names:
  611. for prefix in ifaces[iface]['prefixes']:
  612. ip_ver = 'v6' if ':' in prefix else 'v4'
  613. ips[ip_ver].append (prefix.split ('/')[0])
  614. except KeyError:
  615. pass
  616. return ips
  617. # Compute minions OSPF interface configuration according to FFHO routing policy
  618. # See https://wiki.ffho.net/infrastruktur:vlans for information about Vlans
  619. def get_ospf_interface_config (node_config, grains_id):
  620. ospf_node_config = node_config.get ('ospf', {})
  621. ospf_interfaces = {}
  622. for iface, iface_config in node_config.get ('ifaces', {}).items ():
  623. # By default we don't speak OSPF on interfaces
  624. ospf_on = False
  625. # Defaults for OSPF interfaces
  626. ospf_config = {
  627. 'stub' : True, # Active/Passive interface
  628. 'cost' : 12345,
  629. # 'type' # Area type
  630. }
  631. # OSPF configuration for interface given?
  632. ospf_config_pillar = iface_config.get ('ospf', {})
  633. # Local Gigabit Ethernet based connections (PTP or L2 subnets), cost 10
  634. if re.search (r'^(br-?|br\d+\.|vlan)10\d\d$', iface):
  635. ospf_on = True
  636. ospf_config['stub'] = False
  637. ospf_config['cost'] = 10
  638. ospf_config['desc'] = "Wired Gigabit connection"
  639. # AF-X based WBBL connection
  640. elif re.search (r'^vlan20\d\d$', iface):
  641. ospf_on = True
  642. ospf_config['stub'] = False
  643. ospf_config['cost'] = 100
  644. ospf_config['desc'] = "AF-X based WBBL connection"
  645. # Non-AF-X based WBBL connection
  646. elif re.search (r'^vlan22\d\d$', iface):
  647. ospf_on = True
  648. ospf_config['stub'] = False
  649. ospf_config['cost'] = 1000
  650. ospf_config['desc'] = "Non-AF-X based WBBL connection"
  651. # Management Vlans
  652. elif re.search (r'^vlan30\d\d$', iface):
  653. ospf_on = True
  654. ospf_config['stub'] = True
  655. ospf_config['cost'] = 10
  656. # Active OSPF on OpenVPN tunnels, cost 10000
  657. elif iface.startswith ('ovpn-'):
  658. ospf_on = True
  659. ospf_config['stub'] = False
  660. ospf_config['cost'] = 10000
  661. # Inter-Core links should have cost 5000
  662. if iface.startswith ('ovpn-cr') and grains_id.startswith ('cr'):
  663. ospf_config['cost'] = 5000
  664. # OpenVPN tunnels to EdgeRouters
  665. elif iface.startswith ('ovpn-er-'):
  666. ospf_config['type'] = 'broadcast'
  667. # Configure Out-of-band OpenVPN tunnels as stub interfaces,
  668. # so recursive next-hop lookups for OOB-BGP-session will work.
  669. elif iface.startswith ('oob-'):
  670. ospf_on = True
  671. ospf_config['stub'] = True
  672. ospf_config['cost'] = 1000
  673. # OSPF explicitly enabled for interface
  674. elif 'ospf' in iface_config:
  675. ospf_on = True
  676. # iface ospf parameters will be applied later
  677. # Go on if OSPF should not be actived
  678. if not ospf_on:
  679. continue
  680. # Explicit OSPF interface configuration parameters take precendence over generated ones
  681. for attr, val in ospf_config_pillar:
  682. ospf_config[attr] = val
  683. # Convert boolean values to 'yes' / 'no' string values
  684. for attr, val in ospf_config.items ():
  685. if type (val) == bool:
  686. ospf_config[attr] = 'yes' if val else 'no'
  687. # Store interface configuration
  688. ospf_interfaces[iface] = ospf_config
  689. return ospf_interfaces
  690. # Return (possibly empty) subset of Traffic Engineering entries from 'te' pillar entry
  691. # relevenant for this minion and protocol (IPv4 / IPv6)
  692. def get_te_prefixes (te_node_config, grains_id, proto):
  693. te_config = {}
  694. for prefix, prefix_config in te_node_config.get ('prefixes', {}).items ():
  695. prefix_proto = 'v6' if ':' in prefix else 'v4'
  696. # Should this TE policy be applied on this node and is the prefix
  697. # of the proto we are looking for?
  698. if grains_id in prefix_config.get ('nodes', []) and prefix_proto == proto:
  699. te_config[prefix] = prefix_config
  700. return te_config