ffho_net.py 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477
  1. #!/usr/bin/python
  2. import collections
  3. from functools import cmp_to_key
  4. import ipaddress
  5. import re
  6. from copy import deepcopy
  7. mac_prefix = "f2"
  8. # VRF configuration map
  9. vrf_info = {
  10. 'vrf_external' : {
  11. 'table' : 1023,
  12. 'fwmark' : [ '0x1', '0x1023' ],
  13. },
  14. }
  15. #
  16. # Default parameters added to any given bonding interface,
  17. # if not specified at the interface configuration.
  18. default_bond_config = {
  19. 'bond-mode': '802.3ad',
  20. 'bond-min-links': '1',
  21. 'bond-xmit-hash-policy': 'layer3+4'
  22. }
  23. #
  24. # Default parameters added to any given bridge interface,
  25. # if not specified at the interface configuration.
  26. default_bridge_config = {
  27. 'bridge-fd' : '0',
  28. 'bridge-stp' : 'no',
  29. 'bridge-ports-condone-regex' : '^[a-zA-Z0-9]+_(v[0-9]{1,4}|eth[0-9])$',
  30. }
  31. #
  32. # Hop penalty to be set if none is explicitly specified.
  33. # Check if one of these roles is configured for any given node, use first match.
  34. default_hop_penalty_by_role = {
  35. 'bbr' : 5,
  36. 'bras' : 50,
  37. 'batman_gw' : 50,
  38. 'batman_ext': 50,
  39. }
  40. batman_role_evaluation_order = [ 'bbr', 'batman_gw', 'bras' ]
  41. # By default we do not set any penalty on an interface and rely on the
  42. # regular hop penalty to do the right thing. We only want set another
  43. # penalty, if there are additional paths and we want to influnce which
  44. # path is being taken. One example are routers which have a wifi link
  45. # to the local backbone as well as a VPN link to a gateway, or a fiber
  46. # link plus a wifi backup link.
  47. default_batman_iface_penalty_by_role = {
  48. 'default' : 0,
  49. 'WBBL' : 5,
  50. 'WBBL_backup' : 10,
  51. 'VPN_intergw' : 80,
  52. 'VPN_node' : 100,
  53. }
  54. #
  55. # Default interface attributes to be added to GRE interface to AS201701 when
  56. # not already present in pillar interface configuration.
  57. GRE_FFRL_attrs = {
  58. 'mode' : 'gre',
  59. 'method' : 'tunnel',
  60. 'mtu' : '1400',
  61. 'ttl' : '64',
  62. }
  63. # The IPv4/IPv6 prefix used for Loopback IPs
  64. loopback_prefix = {
  65. 'v4' : '10.132.255.',
  66. 'v6' : '2a03:2260:2342:ffff::',
  67. }
  68. # The DNS zone base names used for generating zone files from IP address
  69. # configured on nodes interfaces.
  70. DNS_zone_names = {
  71. 'forward' : 'ffho.net',
  72. 'rev_v4' : [
  73. '132.10.in-addr.arpa',
  74. '30.172.in-addr.arpa',
  75. ],
  76. 'rev_v6' : [
  77. '2.4.3.2.0.6.2.2.3.0.a.2.ip6.arpa',
  78. ]
  79. }
  80. # MTU configuration
  81. MTU = {
  82. # The default MTU for any interface which does not have a MTU configured
  83. # explicitly in the pillar node config or does not get a MTU configured
  84. # by any means of this SDN stuff here.
  85. 'default' : 1500,
  86. # A batman underlay device, probably a VXLAN or VLAN interface.
  87. #
  88. # 1500
  89. # + 60 B.A.T.M.A.N. adv header + network coding (activated by default by Debian)
  90. 'batman_underlay_iface' : 1560,
  91. # VXLAN underlay device, probably a VLAN within $POP or between two BBRs.
  92. #
  93. # 1560
  94. # + 14 Inner Ethernet Frame
  95. # + 8 VXLAN Header
  96. # + 8 UDP Header
  97. # + 20 IPv4 Header
  98. 'vxlan_underlay_iface' : 1610,
  99. }
  100. ################################################################################
  101. # #
  102. # Internal data types and functions #
  103. # #
  104. # Touching anything below will void any warranty you never had ;) #
  105. # #
  106. ################################################################################
  107. ################################################################################
  108. # Data types #
  109. ################################################################################
  110. class Prefix (object):
  111. """An internet address with a prefix length.
  112. The given address is expected to be of format ip/plen in CIDR notation.
  113. The IP as well as the prefix length and address family will be stored
  114. in attributes.
  115. .. code-block:: pycon
  116. >>> a = Prefix ('10.132.23.42/24')
  117. >>> str (a.ip)
  118. '10.132.23.42'
  119. >>> str (a.af)
  120. '4'
  121. >>> str (a.plen)
  122. '24'
  123. >>> str (a.netmask)
  124. '255.255.255.0'
  125. >>> str (a.network_address)
  126. '10.132.23.0'
  127. """
  128. def __init__ (self, prefix):
  129. self.prefix = prefix
  130. self.ip_network = ipaddress.ip_network (u'%s' % prefix, strict = False)
  131. def __eq__ (self, other):
  132. if isinstance (other, Prefix):
  133. return self.ip_network == other.ip_network
  134. return NotImplemented
  135. def __lt__ (self, other):
  136. if isinstance (other, Prefix):
  137. return self.ip_network < other.ip_network
  138. return NotImplemented
  139. def __str__ (self):
  140. return self.prefix
  141. @property
  142. def ip (self):
  143. return self.prefix.split ('/')[0]
  144. @property
  145. def af (self):
  146. return self.ip_network.version
  147. @property
  148. def plen (self):
  149. return self.ip_network.prefixlen
  150. @property
  151. def netmask (self):
  152. return self.ip_network.netmask
  153. @property
  154. def network_address (self):
  155. return self.ip_network.network_address
  156. ################################################################################
  157. # Functions #
  158. ################################################################################
  159. sites = None
  160. def _get_site_no (sites_config, site_name):
  161. global sites
  162. if sites == None:
  163. sites = {}
  164. for site in sites_config:
  165. if site.startswith ("_"):
  166. continue
  167. sites[site] = sites_config[site].get ("site_no", -2)
  168. return sites.get (site_name, -1)
  169. #
  170. # Generate a MAC address after the format f2:dd:dd:ss:nn:nn where
  171. # dd:dd is the hexadecimal reprensentation of the nodes device_id
  172. # ff:ff representing the gluon nodes
  173. #
  174. # ss is the hexadecimal reprensentation of the site_id the interface is connected to
  175. #
  176. # nn:nn is the decimal representation of the network the interface is connected to, with
  177. # 00:00 being the BATMAN interface
  178. # 00:0d being the dummy interface
  179. # 00:0f being the VEth internal side interface
  180. # 00:e0 being an external instance BATMAN interface
  181. # 00:ed being an external instance dummy interface
  182. # 00:e1 being an inter-gw-vpn interface
  183. # 00:e4 being an nodes fastd tunnel interface of IPv4 transport
  184. # 00:e6 being an nodes fastd tunnel interface of IPv6 transport
  185. # 00:ef being an extenral instance VEth interface side
  186. # 02:xx being a connection to local Vlan 2xx
  187. # xx:xx being a VXLAN tunnel for site ss, with xx being the underlay VLAN ID (1xyz, 2xyz)
  188. # ff:ff being the gluon next-node interface
  189. def gen_batman_iface_mac (site_no, device_no, network):
  190. net_type_map = {
  191. 'bat' : "00:00",
  192. 'dummy' : "00:0d",
  193. 'int2ext' : "00:0f",
  194. 'bat-e' : "00:e0",
  195. 'intergw' : "00:e1",
  196. 'nodes4' : "00:e4",
  197. 'nodes6' : "00:e6",
  198. 'dummy-e' : "00:ed",
  199. 'ext2int' : "00:ef",
  200. }
  201. # Well-known network type?
  202. if network in net_type_map:
  203. last = net_type_map[network]
  204. elif type (network) == int:
  205. last = re.sub (r'(\d{2})(\d{2})', '\g<1>:\g<2>', "%04d" % network)
  206. else:
  207. last = "ee:ee"
  208. # Convert device_no to hex, format number to 4 digits with leading zeros and : betwwen 2nd and 3rd digit
  209. device_no_hex = re.sub (r'([0-9a-fA-F]{2})([0-9a-fA-F]{2})', '\g<1>:\g<2>', "%04x" % int (device_no))
  210. # Format site_no to two digit number with leading zero
  211. site_no_hex = "%02d" % int (site_no)
  212. return "%s:%s:%s:%s" % (mac_prefix, device_no_hex, site_no_hex, last)
  213. # Gather B.A.T.M.A.N. related config options for real batman devices (e.g. bat0)
  214. # as well as for batman member interfaces (e.g. eth0.100, fastd ifaces etc.)
  215. def _update_batman_config (node_config, iface, sites_config):
  216. try:
  217. node_batman_hop_penalty = int (node_config['batman']['hop-penalty'])
  218. except (KeyError,ValueError):
  219. node_batman_hop_penalty = None
  220. iface_config = node_config['ifaces'][iface]
  221. iface_type = iface_config.get ('type', 'inet')
  222. batman_config = {}
  223. for item in list (iface_config.keys ()):
  224. value = iface_config.get (item)
  225. if item.startswith ('batman-'):
  226. batman_config[item] = value
  227. iface_config.pop (item)
  228. # B.A.T.M.A.N. device (e.g. bat0)
  229. if iface_type == 'batman':
  230. if 'batman-hop-penalty' not in batman_config:
  231. # If there's a hop penalty set for the node, but not for the interface
  232. # apply the nodes hop penalty
  233. if node_batman_hop_penalty:
  234. batman_config['batman-hop-penalty'] = node_batman_hop_penalty
  235. # If there's no hop penalty set for the node, use a default hop penalty
  236. # for the roles the node might have, if any
  237. else:
  238. node_roles = node_config.get ('roles', [])
  239. for role in batman_role_evaluation_order:
  240. if role in node_roles:
  241. batman_config['batman-hop-penalty'] = default_hop_penalty_by_role[role]
  242. break
  243. if 'batman_ext' in node_roles and iface.endswith('-ext'):
  244. batman_config['batman-hop-penalty'] = default_hop_penalty_by_role['batman_ext']
  245. # If batman ifaces were specified as a list - which they should -
  246. # generate a sorted list of interface names as string representation
  247. if 'batman-ifaces' in batman_config and type (batman_config['batman-ifaces']) == list:
  248. batman_iface_str = " ".join (sorted (batman_config['batman-ifaces']))
  249. batman_config['batman-ifaces'] = batman_iface_str
  250. # B.A.T.M.A.N. member interface (e.g. eth.100, fastd ifaces, etc.)
  251. elif iface_type == 'batman_iface':
  252. # Generate unique MAC address for every batman iface, as B.A.T.M.A.N.
  253. # will get puzzled with multiple interfaces having the same MAC and
  254. # do nasty things.
  255. site = iface_config.get ('site')
  256. site_no = _get_site_no (sites_config, site)
  257. device_no = node_config.get ('id')
  258. network = 1234
  259. # Generate a unique BATMAN-MAC for this interfaces
  260. match = re.search (r'^vlan(\d+)', iface)
  261. if match:
  262. network = int (match.group (1))
  263. iface_config['hwaddress'] = gen_batman_iface_mac (site_no, device_no, network)
  264. iface_config['batman'] = batman_config
  265. # Mangle bond specific config items with default values and store them in
  266. # separate sub-dict for easier access and configuration.
  267. def _update_bond_config (config):
  268. bond_config = default_bond_config.copy ()
  269. to_pop = []
  270. for item, value in config.items ():
  271. if item.startswith ('bond-'):
  272. bond_config[item] = value
  273. to_pop.append (item)
  274. for item in to_pop:
  275. config.pop (item)
  276. if bond_config['bond-mode'] not in ['2', 'balance-xor', '4', '802.3ad']:
  277. bond_config.pop ('bond-xmit-hash-policy')
  278. config['bond'] = bond_config
  279. # Mangle bridge specific config items with default values and store them in
  280. # separate sub-dict for easier access and configuration.
  281. def _update_bridge_config (config):
  282. bridge_config = default_bridge_config.copy ()
  283. for item in list (config.keys ()):
  284. value = config.get (item)
  285. if not item.startswith ('bridge-'):
  286. continue
  287. bridge_config[item] = value
  288. config.pop (item)
  289. # Fix any salt mangled string interpretation back to real string.
  290. if type (value) == bool:
  291. bridge_config[item] = "yes" if value else "no"
  292. # If bridge ports were specified as a list - which they should -
  293. # generate a sorted list of interface names as string representation
  294. if 'bridge-ports' in bridge_config and type (bridge_config['bridge-ports']) == list:
  295. bridge_ports_str = " ".join (sorted (bridge_config['bridge-ports']))
  296. if not bridge_ports_str:
  297. bridge_ports_str = "none"
  298. bridge_config['bridge-ports'] = bridge_ports_str
  299. config['bridge'] = bridge_config
  300. # Move vlan specific config items into a sub-dict for easier access and pretty-printing
  301. # in the configuration file
  302. def _update_vlan_config (config):
  303. vlan_config = {}
  304. for item in list (config.keys ()):
  305. value = config.get (item)
  306. if item.startswith ('vlan-'):
  307. vlan_config[item] = value
  308. config.pop (item)
  309. config['vlan'] = vlan_config
  310. # Pimp Veth interfaces
  311. # * Add peer interface name IF not present
  312. # * Add link-type veth IF not present
  313. def _update_veth_config (interface, config):
  314. veth_peer_name = {
  315. 'veth_ext2int' : 'veth_int2ext',
  316. 'veth_int2ext' : 'veth_ext2int'
  317. }
  318. if interface not in veth_peer_name:
  319. return
  320. if 'link-type' not in config:
  321. config['link-type'] = 'veth'
  322. if 'veth-peer-name' not in config:
  323. config['veth-peer-name'] = veth_peer_name[interface]
  324. # The given MTU to the given interface - presented by it's interface config dict -
  325. # IFF no MTU has already been set in the node pillar.
  326. #
  327. # @param ifaces: All interface configuration (as dict)
  328. # @param iface_name: Name of the interface to set MTU for
  329. # @param mtu: The MTU value to set (integer)
  330. # When <mtu> is <= 0, the <mtu> configured for <iface_name>
  331. # will be used to set the MTU of the upper interface, and the
  332. # default MTU if none is configured explicitly.
  333. def _set_mtu_to_iface_and_upper (ifaces, iface_name, mtu):
  334. iface_config = ifaces.get (iface_name)
  335. # By default we assume that we should set the given MTU value as the 'automtu'
  336. # attribute to allow distinction between manually set and autogenerated MTU
  337. # values.
  338. set_automtu = True
  339. # If a mtu values <= 0 is given, use the MTU configured for this interface
  340. # or, if none is set, the default value when configuring the vlan-raw-device.
  341. if mtu <= 0:
  342. set_automtu = False
  343. mtu = iface_config.get ('mtu', MTU['default'])
  344. # If this interface already has a MTU set - probably because someone manually
  345. # specified one in the node pillar - we do not touch the MTU of this interface.
  346. # Nevertheless it's worth looking at any underlying interface.
  347. if 'mtu' in iface_config:
  348. set_automtu = False
  349. # There might be - read: "we have" - a situation where on top of e.g. bond0
  350. # there are vlans holding VXLAN communicaton as well as VLANs directly carrying
  351. # BATMAN traffic. Now depending on which interface is evaluated first, the upper
  352. # MTU is either correct, or maybe to small.
  353. #
  354. # If any former autogenerated MTU is greater-or-equal than the one we want to
  355. # set now, we'll ignore it, and go for the greater one.
  356. elif 'automtu' in iface_config and iface_config['automtu'] >= mtu:
  357. set_automtu = False
  358. # If we still consider this a good move, set given MTU to this device.
  359. if set_automtu:
  360. iface_config['automtu'] = mtu
  361. # If this is a VLAN - which it probably is - fix the MTU of the underlying interface, too.
  362. # Check for 'vlan-raw-device' in iface_config and in vlan subconfig (yeah, that's not ideal).
  363. vlan_raw_device = None
  364. if 'vlan-raw-device' in iface_config:
  365. vlan_raw_device = iface_config['vlan-raw-device']
  366. elif 'vlan' in iface_config and 'vlan-raw-device' in iface_config['vlan']:
  367. vlan_raw_device = iface_config['vlan']['vlan-raw-device']
  368. if vlan_raw_device:
  369. vlan_raw_device_config = ifaces.get (vlan_raw_device, None)
  370. # vlan-raw-device might point to ethX which usually isn't configured explicitly
  371. # as ifupdown2 simply will bring it up anyway by itself. To set the MTU of such
  372. # an interface we have to add a configuration stanza for it here.
  373. if vlan_raw_device_config == None:
  374. vlan_raw_device_config = {}
  375. ifaces[vlan_raw_device] = vlan_raw_device_config
  376. # If there is a manually set MTU for this device, we don't do nothin'
  377. if 'mtu' in vlan_raw_device_config:
  378. return
  379. if 'automtu' in vlan_raw_device_config and vlan_raw_device_config['automtu'] >= mtu:
  380. return
  381. vlan_raw_device_config['automtu'] = mtu
  382. # Generate configuration entries for any batman related interfaces not
  383. # configured explicitly, but asked for implicitly by role batman and a
  384. # (list of) site(s) specified in the node config.
  385. def _generate_batman_interface_config (node_config, ifaces, sites_config):
  386. # No role 'batman', nothing to do
  387. roles = node_config.get ('roles', [])
  388. if 'batman' not in roles:
  389. return
  390. # Should there be a 2nd external BATMAN instance?
  391. batman_ext = 'batman_ext' in roles or 'bras' in roles
  392. device_no = node_config.get ('id', -1)
  393. for site in node_config.get ('sites', []):
  394. site_no = _get_site_no (sites_config, site)
  395. # Predefine interface names for regular/external BATMAN instance
  396. # and possible VEth link pair for connecting both instances.
  397. bat_site_if = "bat-%s" % site
  398. dummy_site_if = "dummy-%s" % site
  399. bat_site_if_ext = "bat-%s-ext" % site
  400. dummy_site_if_ext = "dummy-%s-e" % site
  401. int2ext_site_if = "i2e-%s" % site
  402. ext2int_site_if = "e2i-%s" % site
  403. site_ifaces = {
  404. # Regular BATMAN interface, always present
  405. bat_site_if : {
  406. 'type' : 'batman',
  407. # int2ext_site_if will be added automagically if requred
  408. 'batman-ifaces' : [ dummy_site_if ],
  409. 'batman-ifaces-ignore-regex': '.*_.*',
  410. 'hwaddress' : gen_batman_iface_mac (site_no, device_no, 'bat'),
  411. },
  412. # Dummy interface always present in regular BATMAN instance
  413. dummy_site_if : {
  414. 'link-type' : 'dummy',
  415. 'hwaddress' : gen_batman_iface_mac (site_no, device_no, 'dummy'),
  416. 'mtu' : MTU['batman_underlay_iface'],
  417. },
  418. # Optional 2nd "external" BATMAN instance
  419. bat_site_if_ext : {
  420. 'type' : 'batman',
  421. 'batman-ifaces' : [ dummy_site_if_ext, ext2int_site_if ],
  422. 'batman-ifaces-ignore-regex': '.*_.*',
  423. 'hwaddress' : gen_batman_iface_mac (site_no, device_no, 'bat-e'),
  424. 'ext_only' : True,
  425. },
  426. # Optional dummy interface always present in 2nd "external" BATMAN instance
  427. dummy_site_if_ext : {
  428. 'link-type' : 'dummy',
  429. 'hwaddress' : gen_batman_iface_mac (site_no, device_no, 'dummy-e'),
  430. 'ext_only' : True,
  431. 'mtu' : MTU['batman_underlay_iface'],
  432. },
  433. # Optional VEth interface pair - internal side
  434. int2ext_site_if : {
  435. 'link-type' : 'veth',
  436. 'veth-peer-name' : ext2int_site_if,
  437. 'hwaddress' : gen_batman_iface_mac (site_no, device_no, 'int2ext'),
  438. 'mtu' : MTU['batman_underlay_iface'],
  439. 'ext_only' : True,
  440. },
  441. # Optional VEth interface pair - "external" side
  442. ext2int_site_if : {
  443. 'link-type' : 'veth',
  444. 'veth-peer-name' : int2ext_site_if,
  445. 'hwaddress' : gen_batman_iface_mac (site_no, device_no, 'ext2int'),
  446. 'mtu' : MTU['batman_underlay_iface'],
  447. 'ext_only' : True,
  448. },
  449. }
  450. for iface, iface_config_tmpl in site_ifaces.items ():
  451. # Ignore any interface only relevant when role batman_ext is set
  452. # but it isn't
  453. if not batman_ext and iface_config_tmpl.get ('ext_only', False):
  454. continue
  455. # Remove ext_only key so we don't leak it into ifaces dict
  456. if 'ext_only' in iface_config_tmpl:
  457. del iface_config_tmpl['ext_only']
  458. # If there is no trace of the desired iface config yet...
  459. if iface not in ifaces:
  460. # ... just place our template there.
  461. ifaces[iface] = iface_config_tmpl
  462. # If there should be an 2nd external BATMAN instance make sure
  463. # the internal side of the VEth iface pair is connected to the
  464. # internal BATMAN instance.
  465. if batman_ext and iface == bat_site_if:
  466. iface_config_tmpl['batman-ifaces'].append (int2ext_site_if)
  467. # If there already is an interface configuration try to enhance it with
  468. # meaningful values from our template and force correct hwaddress to be
  469. # used.
  470. else:
  471. iface_config = ifaces[iface]
  472. # Force hwaddress to be what we expect.
  473. if 'hwaddress' in iface_config_tmpl:
  474. iface_config['hwaddress'] = iface_config_tmpl['hwaddress']
  475. # Copy every attribute of the config template missing in iface config
  476. for attr in iface_config_tmpl:
  477. if attr not in iface_config:
  478. iface_config[attr] = iface_config_tmpl[attr]
  479. # Configure bat_site_if to be part of br-<site>, if present
  480. site_bridge = "br-%s" % site
  481. if site_bridge in ifaces:
  482. bridge_config = ifaces.get (site_bridge)
  483. bridge_ports = bridge_config.get ('bridge-ports', None)
  484. # There are bridge-ports configured already, but bat_site_if is not present
  485. if bridge_ports and bat_site_if not in bridge_ports:
  486. if type (bridge_ports) == list:
  487. bridge_ports.append (bat_site_if)
  488. else:
  489. bridge_config['bridge-ports'] += ' ' + bat_site_if
  490. # There are no bridge-ports configured
  491. if not bridge_ports:
  492. bridge_config['bridge-ports'] = bat_site_if
  493. # Make sure there is a bridge present for every site where a mesh_breakout
  494. # interface should be configured.
  495. for iface in list (ifaces.keys ()):
  496. config = ifaces.get (iface)
  497. iface_type = config.get ('type', 'inet')
  498. if iface_type not in ['mesh_breakout', 'batman_iface']:
  499. continue
  500. site = config.get ('site')
  501. site_bridge = "br-%s" % site
  502. batman_site_if = "bat-%s" % site
  503. if iface_type == 'mesh_breakout':
  504. # If the bridge has already been defined (with an IP maybe) make
  505. # sure that the corresbonding batman device is part of the bridge-
  506. # ports.
  507. if site_bridge in ifaces:
  508. bridge_config = ifaces.get (site_bridge)
  509. # If there already is/are (a) bridge-port(s) defined, add
  510. # the batman and the breakout interfaces if not present...
  511. bridge_ports = bridge_config.get ('bridge-ports', None)
  512. if bridge_ports:
  513. for dev in (batman_site_if, iface):
  514. if not dev in bridge_ports:
  515. if type (bridge_ports) == list:
  516. bridge_ports.append (dev)
  517. else:
  518. bridge_config['bridge-ports'] += ' ' + dev
  519. # ...if there is no bridge-port defined yet, just used
  520. # the batman and breakout iface.
  521. else:
  522. bridge_config['bridge-ports'] = [ iface, batman_site_if ]
  523. # If the bridge isn't present alltogether, add it.
  524. else:
  525. ifaces[site_bridge] = {
  526. 'bridge-ports' : [ iface, batman_site_if ],
  527. }
  528. elif iface_type == 'batman_iface':
  529. batman_ifaces = ifaces[batman_site_if]['batman-ifaces']
  530. if iface not in batman_ifaces:
  531. if type (batman_ifaces) == list:
  532. batman_ifaces.append (iface)
  533. else:
  534. batman_ifaces += ' ' + iface
  535. # Use the MTU configured for this interface or, if none is set,
  536. # the default value for batman underlay iface.
  537. mtu = config.get('mtu', MTU['batman_underlay_iface'])
  538. _set_mtu_to_iface_and_upper (ifaces, iface, mtu)
  539. #
  540. # Generate any implicitly defined VXLAN interfaces defined in the nodes iface
  541. # defined in pillar.
  542. # The keyword "batman_connect_sites" on an interface will trigger the
  543. # generation of a VXLAN overlay interfaces.
  544. def _generate_vxlan_interface_config (node_config, ifaces, sites_config):
  545. # No role 'batman', nothing to do
  546. if 'batman' not in node_config.get ('roles', []):
  547. return
  548. # Sites configured on this node. Nothing to do, if none.
  549. my_sites = node_config.get ('sites', [])
  550. if len (my_sites) == 0:
  551. return
  552. # As we're still here we can now safely assume that a B.A.T.M.A.N.
  553. # device has been configured for every site specified in sites list.
  554. device_no = node_config.get ('id', -1)
  555. for iface in list (ifaces.keys ()):
  556. iface_config = ifaces.get (iface)
  557. batman_connect_sites = iface_config.get ('batman_connect_sites', [])
  558. iface_has_prefixes = len (iface_config.get ('prefixes', {})) != 0
  559. # If we got a string, convert it to a list with a single element
  560. if type (batman_connect_sites) == str:
  561. batman_connect_sites = [ batman_connect_sites ]
  562. # If the list of sites to connect is empty, there's nothing to do here.
  563. if len (batman_connect_sites) == 0:
  564. continue
  565. # Set the MTU of this (probably) VLAN device to the MTU required for a VXLAN underlay
  566. # device, where B.A.T.M.A.N. adv. is to be expected within the VXLAN overlay.
  567. _set_mtu_to_iface_and_upper (ifaces, iface, MTU['vxlan_underlay_iface'])
  568. # If the string 'all' is part of the list, blindly use all sites configured for this node
  569. if 'all' in batman_connect_sites:
  570. batman_connect_sites = my_sites
  571. for site in batman_connect_sites:
  572. # Silenty ignore sites not configured on this node
  573. if site not in my_sites:
  574. continue
  575. # iface_name := vx_<last 5 chars of underlay iface>_<site> stripped to 15 chars
  576. vx_iface = ("vx_%s_%s" % (re.sub ('vlan', 'v', iface)[-5:], re.sub (r'[_-]', '', site)))[:15]
  577. site_no = _get_site_no (sites_config, site)
  578. bat_iface = "bat-%s" % site
  579. # If there's no batman interface for this site, there's no point
  580. # in setting up a VXLAN interfaces
  581. if bat_iface not in ifaces:
  582. continue
  583. # bail out if VXLAN tunnel already configured
  584. if vx_iface in ifaces:
  585. continue
  586. try:
  587. iface_id = int (re.sub ('vlan', '', iface))
  588. # Gather interface specific mcast address.
  589. # The address is derived from the vlan-id of the underlying interface,
  590. # assuming that it in fact is a vlan interface.
  591. # Mangle the vlan-id into two 2 digit values, eliminating any leading zeros.
  592. iface_id_4digit = "%04d" % iface_id
  593. octet2 = int (iface_id_4digit[0:2])
  594. octet3 = int (iface_id_4digit[2:4])
  595. vni = octet2 * 256 * 256 + octet3 * 256 + site_no
  596. vtep_config = {
  597. 'vxlan-id' : vni,
  598. 'vxlan-physdev' : iface,
  599. }
  600. # If there are prefixes configured on this underlay interface go for legacy IPv4 Multicast (for now)
  601. if iface_has_prefixes:
  602. vtep_config['vxlan-svcnodeip'] = "225.%s.%s.%s" % (octet2, octet3, site_no)
  603. else:
  604. vtep_config['vxlan-remote-group'] = "ff42:%s::%s" % (iface_id, site_no)
  605. except ValueError as v:
  606. vtep_config = {
  607. 'vxlan-config-error' : str (v),
  608. }
  609. iface_id = 9999
  610. mcast_ip = "225.0.0.%s" % site_no
  611. vni = site_no
  612. # Add the VXLAN interface
  613. ifaces[vx_iface] = {
  614. 'vxlan' : vtep_config,
  615. 'hwaddress' : gen_batman_iface_mac (site_no, device_no, iface_id),
  616. 'mtu' : MTU['batman_underlay_iface'],
  617. }
  618. iface_penalty = get_batman_iface_penalty (iface)
  619. if iface_penalty:
  620. ifaces[vx_iface]['batman'] = {
  621. 'batman-hop-penalty' : iface_penalty
  622. }
  623. # If the batman interface for this site doesn't have any interfaces
  624. # set up - which basicly cannot happen - add this VXLAN tunnel as
  625. # the first in the list.
  626. if not 'batman-ifaces' in ifaces[bat_iface]:
  627. ifaces[bat_iface]['batman-ifaces'] = [ vx_iface ]
  628. continue
  629. # In the hope there already are interfaces for batman set up already
  630. # add this VXLAN tunnel to the list
  631. batman_ifaces = ifaces[bat_iface]['batman-ifaces']
  632. if vx_iface not in batman_ifaces:
  633. if type (batman_ifaces) == list:
  634. batman_ifaces.append (vx_iface)
  635. else:
  636. batman_ifaces += ' ' + vx_iface
  637. #
  638. # Generate implicitly defined VRFs according to the vrf_info dict at the top
  639. # of this file
  640. def _generate_vrfs (ifaces):
  641. for iface in list (ifaces.keys ()):
  642. iface_config = ifaces.get (iface)
  643. vrf = iface_config.get ('vrf', None)
  644. if vrf and vrf not in ifaces:
  645. conf = vrf_info.get (vrf, {})
  646. table = conf.get ('table', 1234)
  647. fwmark = conf.get ('fwmark', None)
  648. ifaces[vrf] = {
  649. 'vrf-table' : table,
  650. }
  651. # Create ip rule's for any fwmarks defined
  652. if fwmark:
  653. up = []
  654. # Make sure we are dealing with a list even if there is only one mark to be set up
  655. if type (fwmark) in (str, int):
  656. fwmark = [ fwmark ]
  657. # Create ip rule entries for IPv4 and IPv6 for every fwmark
  658. for mark in fwmark:
  659. up.append ("ip rule add fwmark %s table %s" % (mark, table))
  660. up.append ("ip -6 rule add fwmark %s table %s" % (mark, table))
  661. ifaces[vrf]['up'] = up
  662. def _generate_ffrl_gre_tunnels (ifaces):
  663. for iface, iface_config in ifaces.items ():
  664. # We only care for GRE_FFRL type interfaces
  665. if iface_config.get ('type', '') != 'GRE_FFRL':
  666. continue
  667. # Copy default values to interface config
  668. for attr, val in GRE_FFRL_attrs.items ():
  669. if not attr in iface_config:
  670. iface_config[attr] = val
  671. # Guesstimate local IPv4 tunnel endpoint address from tunnel-physdev
  672. if not 'local' in iface_config and 'tunnel-physdev' in iface_config:
  673. try:
  674. physdev_prefixes = [p.split ('/')[0] for p in ifaces[iface_config['tunnel-physdev']]['prefixes'] if '.' in p]
  675. if len (physdev_prefixes) == 1:
  676. iface_config['local'] = physdev_prefixes[0]
  677. except KeyError:
  678. pass
  679. def _generate_loopback_ips (ifaces, node_config, node_id):
  680. # If this node has primary_ips set and filled there are either IPs
  681. # configured on lo or IPs on another interface - possibly ones on
  682. # the only interface present - are considered as primary IPs.
  683. if node_config.get ('primary_ips', False):
  684. return
  685. v4_ip = "%s/32" % get_primary_ip (node_config, 'v4').ip
  686. v6_ip = "%s/128" % get_primary_ip (node_config, 'v6').ip
  687. # Interface lo already present?
  688. if 'lo' not in ifaces:
  689. ifaces['lo'] = { 'prefixes' : [] }
  690. # Add 'prefixes' list if not present
  691. if 'prefixes' not in ifaces['lo']:
  692. ifaces['lo']['prefixes'] = []
  693. prefixes = ifaces['lo']['prefixes']
  694. if v4_ip not in prefixes:
  695. prefixes.append (v4_ip)
  696. if v6_ip not in prefixes:
  697. prefixes.append (v6_ip)
  698. # Generate interface descriptions / aliases for auto generated or manually
  699. # created interfaces. Currently this only is done for bridges associated
  700. # with BATMAN instanzes.
  701. #
  702. # @param node_config: The configuration of the given node (as dict)
  703. # @param sites_config Global sites configuration (as dict)
  704. def _update_interface_desc (node_config, sites_config):
  705. # Currently we only care for nodes with batman role.
  706. if 'batman' not in node_config.get ('roles', []):
  707. return
  708. for iface, iface_config in node_config.get ('ifaces', {}).items ():
  709. if 'desc' in sites_config:
  710. continue
  711. # If the interface name looks like a bridge for a BATMAN instance
  712. # try to get the name of the corresponding site
  713. match = re.search (r'^br-([a-z_-]+)$', iface)
  714. if match and match.group (1) in sites_config:
  715. try:
  716. iface_config['desc'] = sites_config[match.group (1)]['name']
  717. except KeyError:
  718. pass
  719. ################################################################################
  720. # Public functions #
  721. ################################################################################
  722. # Generate network interface configuration for given node.
  723. #
  724. # This function will read the network configuration from pillar and will
  725. # * enhance it with all default values configured at the top this file
  726. # * auto generate any implicitly configured
  727. # * VRFs
  728. # * B.A.T.M.A.N. instances and interfaces
  729. # * VXLAN interfaces to connect B.A.T.M.A.N. sites
  730. # * Loopback IPs derived from numeric node ID
  731. #
  732. # @param: node_config Pillar node configuration (as dict)
  733. # @param: sites_config Pillar sites configuration (as dict)
  734. # @param: node_id Minion name / Pillar node configuration key
  735. def get_interface_config (node_config, sites_config, node_id = ""):
  736. # Make a copy of the node_config dictionary to suppress side-effects.
  737. # This function deletes some keys from the node_config which will break
  738. # any re-run of this function or other functions relying on the node_config
  739. # to be complete.
  740. node_config = deepcopy (node_config)
  741. # Get config of this node and dict of all configured ifaces
  742. ifaces = node_config.get ('ifaces', {})
  743. # Generate configuration entries for any batman related interfaces not
  744. # configured explicitly, but asked for implicitly by role <batman> and
  745. # a (list of) site(s) specified in the node config.
  746. _generate_batman_interface_config (node_config, ifaces, sites_config)
  747. # Generate VXLAN tunnels for every interfaces specifying 'batman_connect_sites'
  748. _generate_vxlan_interface_config (node_config, ifaces, sites_config)
  749. # Enhance ifaces configuration with some meaningful defaults for
  750. # bonding, bridge and vlan interfaces, MAC address for batman ifaces, etc.
  751. for interface in list (ifaces.keys ()):
  752. config = ifaces.get (interface)
  753. iface_type = config.get ('type', 'inet')
  754. # Remove any disable interfaces here as they aren't relevant for /e/n/i
  755. if config.get ('enabled', True) == False:
  756. del ifaces[interface]
  757. continue
  758. if 'batman-ifaces' in config or iface_type.startswith ('batman'):
  759. _update_batman_config (node_config, interface, sites_config)
  760. if 'bond-slaves' in config:
  761. _update_bond_config (config)
  762. # FIXME: This maybe will not match on bridges without any member ports configured!
  763. if 'bridge-ports' in config or interface.startswith ('br-'):
  764. _update_bridge_config (config)
  765. if 'vlan-raw-device' in config or 'vlan-id' in config:
  766. _update_vlan_config (config)
  767. _set_mtu_to_iface_and_upper (ifaces, interface, 0)
  768. # Pimp configuration for VEth link pairs
  769. if interface.startswith ('veth_'):
  770. _update_veth_config (interface, config)
  771. # Auto generate Loopback IPs IFF not present
  772. _generate_loopback_ips (ifaces, node_config, node_id)
  773. # Auto generated VRF devices for any VRF found in ifaces and not already configured.
  774. _generate_vrfs (ifaces)
  775. # Pimp GRE_FFRL type inteface configuration with default values
  776. _generate_ffrl_gre_tunnels (ifaces)
  777. # Drop any config parameters used in node interface configuration not
  778. # relevant anymore for config file generation.
  779. for interface, config in ifaces.items ():
  780. # Set default MTU if not already set manually or by any earlier function
  781. if interface != 'lo' and ('mtu' not in config):
  782. # Set the MTU value of this interface to the autogenerated value (if any)
  783. # or set the default, when no automtu is present.
  784. config['mtu'] = config.get ('automtu', MTU['default'])
  785. for key in [ 'automtu', 'enabled', 'batman_connect_sites', 'has_gateway', 'ospf', 'site', 'type', 'tagged_vlans' ]:
  786. if key in config:
  787. config.pop (key)
  788. # Remove route metric on non-router nodes
  789. if 'metric' in config and not 'router' in node_config.get ('roles', []):
  790. config.pop ('metric')
  791. # This leaves 'auto', 'prefixes' and 'desc' as keys which should not be directly
  792. # printed into the remaining configuration. These are handled within the jinja
  793. # interface template.
  794. # Generate meaningful interface descriptions / aliases where useful
  795. _update_interface_desc (node_config, sites_config)
  796. return ifaces
  797. vlan_vxlan_iface_re = re.compile (r'^vlan(\d+)|^vx_v(\d+)_(\w+)')
  798. def _cmp (x, y):
  799. if x < y:
  800. return -1
  801. elif x == y:
  802. return 0
  803. else:
  804. return 1
  805. def _iface_sort (iface_a, iface_b):
  806. a = vlan_vxlan_iface_re.search (iface_a)
  807. b = vlan_vxlan_iface_re.search (iface_b)
  808. # At least one interface didn't match, do regular comparison
  809. if not a or not b:
  810. return _cmp (iface_a, iface_b)
  811. # Extract VLAN ID from VLAN interface (if given) or VXLAN
  812. vid_a = a.group (1) if a.group (1) else a.group (2)
  813. vid_b = b.group (1) if b.group (1) else b.group (2)
  814. # If it's different type of interfaces (one VLAN, one VXLAN), do regular comparison
  815. if (a.group (1) == None) != (b.group (1) == None):
  816. return _cmp (iface_a, iface_b)
  817. # Ok, t's two VLAN or two VXLAN interfaces
  818. # If it's VXLAN interfaces and the VLAN ID is the same, sort by site name
  819. if a.group (2) and vid_a == vid_b:
  820. return _cmp (a.groups (2), b.groups (2))
  821. # If it's two VLANs or two VXLANs with different VLAN IDs, sort by VLAN ID
  822. else:
  823. return _cmp (int (vid_a), int (vid_b))
  824. def get_interface_list (ifaces):
  825. iface_list = []
  826. for iface in sorted (ifaces.keys (), key = cmp_to_key (_iface_sort)):
  827. iface_list.append (iface)
  828. return iface_list
  829. # Generate entries for /etc/bat-hosts for every batman interface we will configure on any node.
  830. # For readability purposes superflous/redundant information is being stripped/supressed.
  831. # As these names will only show up in batctl calls with a specific site, site_names in interfaces
  832. # are stripped. Dummy interfaces are stripped as well.
  833. def gen_bat_hosts (nodes_config, sites_config):
  834. bat_hosts = {}
  835. for node_id in sorted (nodes_config.keys ()):
  836. node_config = nodes_config.get (node_id)
  837. node_name = node_id.split ('.')[0]
  838. if 'batman' not in node_config['roles']:
  839. continue
  840. ifaces = get_interface_config (node_config, sites_config, node_id)
  841. for iface in sorted (ifaces):
  842. iface_config = ifaces.get (iface)
  843. hwaddress = iface_config.get ('hwaddress', None)
  844. if hwaddress == None:
  845. continue
  846. entry_name = node_name
  847. match = re.search (r'^dummy-(.+)(-e)?$', iface)
  848. if match:
  849. if match.group (2):
  850. entry_name += "-e"
  851. # Append site to make name unique
  852. entry_name += "/%s" % match.group (1)
  853. else:
  854. entry_name += "/%s" % re.sub (r'^(vx_.*|i2e|e2i)[_-](.*)$', '\g<1>/\g<2>', iface)
  855. bat_hosts[hwaddress] = entry_name
  856. if 'fastd' in node_config.get ('roles', []):
  857. device_no = node_config.get ('id')
  858. for site in node_config.get ('sites', []):
  859. site_no = _get_site_no (sites_config, site)
  860. for network in ('intergw', 'nodes4', 'nodes6'):
  861. hwaddress = gen_batman_iface_mac (site_no, device_no, network)
  862. bat_hosts[hwaddress] = "%s/%s/%s" % (node_name, network, site)
  863. return bat_hosts
  864. # Return the appropriate hop penalty to configure for the given interface.
  865. def get_batman_iface_penalty (iface):
  866. if iface.startswith ('vlan'):
  867. vid = int (re.sub ('vlan', '', iface))
  868. if 2000 <= vid < 2100:
  869. return default_batman_iface_penalty_by_role.get ('WBBL')
  870. if 2200 <= vid < 2300:
  871. return default_batman_iface_penalty_by_role.get ('WBBL_backup')
  872. if 'intergw' in iface:
  873. return default_batman_iface_penalty_by_role.get ('VPN_intergw')
  874. if 'nodes' in iface:
  875. return default_batman_iface_penalty_by_role.get ('VPN_node')
  876. return default_batman_iface_penalty_by_role.get ('default', 0)
  877. # Generate eBGP session parameters for FFRL Transit from nodes pillar information.
  878. def get_ffrl_bgp_config (ifaces, proto):
  879. _generate_ffrl_gre_tunnels (ifaces)
  880. sessions = {}
  881. for iface in sorted (ifaces):
  882. # We only care for GRE tunnels to the FFRL Backbone
  883. if not iface.startswith ('gre_ffrl_'):
  884. continue
  885. iface_config = ifaces.get (iface)
  886. # Search for IPv4/IPv6 prefix as defined by proto parameter
  887. local = None
  888. neighbor = None
  889. for prefix in iface_config.get ('prefixes', []):
  890. if (proto == 'v4' and '.' in prefix) or (proto == 'v6' and ':' in prefix):
  891. local = prefix.split ('/')[0]
  892. # Calculate neighbor IP as <local IP> - 1
  893. neighbor = str (ipaddress.ip_address (u'%s' % local) - 1)
  894. break
  895. # Strip gre_ prefix iface name and use it as identifier for the eBGP session.
  896. name = re.sub ('gre_ffrl_', 'ffrl_', iface)
  897. sessions[name] = {
  898. 'local' : local,
  899. 'neighbor' : neighbor,
  900. 'bgp_local_pref' : iface_config.get ('bgp_local_pref', None),
  901. }
  902. return sessions
  903. # Get list of IP address configured on given interface on given node.
  904. #
  905. # @param: node_config Pillar node configuration (as dict)
  906. # @param: iface_name Name of the interface defined in pillar node config
  907. # OR name of VRF ("vrf_<something>") whichs ifaces are
  908. # to be examined.
  909. # @param: with_mask Don't strip the netmask from the prefix. (Default false)
  910. def get_node_iface_ips (node_config, iface_name, with_mask = False):
  911. ips = {
  912. 'v4' : [],
  913. 'v6' : [],
  914. }
  915. ifaces = node_config.get ('ifaces', {})
  916. ifaces_names = [ iface_name ]
  917. if iface_name.startswith ('vrf_'):
  918. # Reset list of ifaces_names to consider
  919. ifaces_names = []
  920. vrf = iface_name
  921. for iface, iface_config in ifaces.items ():
  922. # Ignore any iface NOT in the given VRF
  923. if iface_config.get ('vrf', None) != vrf:
  924. continue
  925. # Ignore any VEth pairs
  926. if iface.startswith ('veth'):
  927. continue
  928. ifaces_names.append (iface)
  929. try:
  930. for iface in ifaces_names:
  931. for prefix in ifaces[iface]['prefixes']:
  932. ip_ver = 'v6' if ':' in prefix else 'v4'
  933. if not with_mask:
  934. prefix = prefix.split ('/')[0]
  935. ips[ip_ver].append (prefix)
  936. except KeyError:
  937. pass
  938. return ips
  939. #
  940. # Get the primary IP(s) of the given node
  941. #
  942. # @param node_config: Pillar node configuration (as dict)
  943. # @param af: Address family
  944. def get_primary_ip (node_config, af):
  945. # Compatility glue
  946. if 'primary_ips' not in node_config:
  947. return Prefix ("%s%s" % (loopback_prefix[af], node_config['id']))
  948. return Prefix (node_config['primary_ips'][af])
  949. #
  950. # Get the router id (read: IPv4 Lo-IP) out of the given node config.
  951. def get_router_id (node_config, node_id):
  952. return get_primary_ip (node_config, 'v4').ip
  953. # Compute minions OSPF interface configuration according to FFHO routing policy
  954. # See https://wiki.ffho.net/infrastruktur:vlans for information about Vlans
  955. #
  956. # Costs are based on the following reference values:
  957. #
  958. # Iface speed | Cost
  959. # ------------+---------
  960. # 100 Gbit/s | 1
  961. # 40 Gbit/s | 2
  962. # 25 Gbit/s | 4
  963. # 20 Gbit/s | 5
  964. # 10 Gbit/s | 10
  965. # 1 Gbit/s | 100
  966. # 100 Mbit/s | 1000
  967. # VPN | 10000
  968. #
  969. def get_ospf_interface_config (node_config, grains_id):
  970. ospf_node_config = node_config.get ('ospf', {})
  971. ospf_interfaces = {}
  972. for iface, iface_config in node_config.get ('ifaces', {}).items ():
  973. # By default we don't speak OSPF on interfaces
  974. ospf_on = False
  975. # Defaults for OSPF interfaces
  976. ospf_config = {
  977. 'stub' : True, # Active/Passive interface
  978. 'cost' : 12345,
  979. # 'type' # Area type
  980. }
  981. # OSPF configuration for interface present?
  982. ospf_config_pillar = iface_config.get ('ospf', {})
  983. # Should be completely ignore this interface?
  984. if ospf_config_pillar.get ('ignore', False):
  985. continue
  986. # Ignore interfaces without any IPs configured
  987. if not iface_config.get ('prefixes'):
  988. continue
  989. # Wireless Local Links (WLL)
  990. if re.search (r'^vlan90\d$', iface):
  991. ospf_on = True
  992. ospf_config['stub'] = True
  993. ospf_config['cost'] = 10
  994. ospf_config['desc'] = "Wireless Local Link (WLL)"
  995. # Local Gigabit Ethernet based connections (PTP or L2 subnets), cost 10
  996. elif re.search (r'^(br-?|br\d+\.|vlan)10\d\d$', iface):
  997. ospf_on = True
  998. ospf_config['stub'] = False
  999. ospf_config['cost'] = 100
  1000. ospf_config['desc'] = "Wired Gigabit connection"
  1001. # 10/20 Gbit/s Dark Fiber connection
  1002. elif re.search (r'^vlan12\d\d$', iface):
  1003. ospf_on = True
  1004. ospf_config['stub'] = False
  1005. ospf_config['cost'] = 10
  1006. ospf_config['desc'] = "Wired 10Gb/s connection"
  1007. # VLL connection
  1008. elif re.search (r'^vlan15\d\d$', iface):
  1009. ospf_on = True
  1010. ospf_config['stub'] = False
  1011. ospf_config['cost'] = 200
  1012. ospf_config['desc'] = "VLL connection"
  1013. # WBBL connection
  1014. elif re.search (r'^vlan20\d\d$', iface):
  1015. ospf_on = True
  1016. ospf_config['stub'] = False
  1017. ospf_config['cost'] = 1000
  1018. ospf_config['desc'] = "WBBL connection"
  1019. # Legacy WBBL connection
  1020. elif re.search (r'^vlan22\d\d$', iface):
  1021. ospf_on = True
  1022. ospf_config['stub'] = False
  1023. ospf_config['cost'] = 1000
  1024. ospf_config['desc'] = "WBBL connection"
  1025. # Management Vlans
  1026. elif re.search (r'^vlan30\d\d$', iface):
  1027. ospf_on = True
  1028. ospf_config['stub'] = True
  1029. ospf_config['cost'] = 10
  1030. # OPS Vlans
  1031. elif re.search (r'^vlan39\d\d$', iface):
  1032. ospf_on = True
  1033. ospf_config['stub'] = True
  1034. ospf_config['cost'] = 10
  1035. # Active OSPF on OpenVPN tunnels, cost 10000
  1036. elif iface.startswith ('ovpn-'):
  1037. ospf_on = True
  1038. ospf_config['stub'] = False
  1039. ospf_config['cost'] = 10000
  1040. # Inter-Core links should have cost 5000
  1041. if iface.startswith ('ovpn-cr') and grains_id.startswith ('cr'):
  1042. ospf_config['cost'] = 5000
  1043. # OpenVPN tunnels to EdgeRouters
  1044. elif iface.startswith ('ovpn-er-'):
  1045. ospf_config['type'] = 'broadcast'
  1046. # Active OSPF on Wireguard tunnels, cost 10000
  1047. elif iface.startswith ('wg-'):
  1048. ospf_on = True
  1049. ospf_config['stub'] = False
  1050. ospf_config['cost'] = 10000
  1051. # Inter-Core links should have cost 5000
  1052. if iface.startswith ('wg-cr') and grains_id.startswith ('cr'):
  1053. ospf_config['cost'] = 5000
  1054. # OSPF explicitly enabled for interface
  1055. elif 'ospf' in iface_config:
  1056. ospf_on = True
  1057. # iface ospf parameters will be applied later
  1058. # Go on if OSPF should not be actived
  1059. if not ospf_on:
  1060. continue
  1061. # Explicit OSPF interface configuration parameters take precendence over generated ones
  1062. for attr, val in ospf_config_pillar.items ():
  1063. ospf_config[attr] = val
  1064. # Store interface configuration
  1065. ospf_interfaces[iface] = ospf_config
  1066. return ospf_interfaces
  1067. # Return (possibly empty) subset of Traffic Engineering entries from 'te' pillar entry
  1068. # relevenant for this minion and protocol (IPv4 / IPv6)
  1069. def get_te_prefixes (te_node_config, grains_id, proto):
  1070. te_config = {}
  1071. for prefix, prefix_config in te_node_config.get ('prefixes', {}).items ():
  1072. prefix_proto = 'v6' if ':' in prefix else 'v4'
  1073. # Should this TE policy be applied on this node and is the prefix
  1074. # of the proto we are looking for?
  1075. if grains_id in prefix_config.get ('nodes', []) and prefix_proto == proto:
  1076. te_config[prefix] = prefix_config
  1077. return te_config
  1078. def generate_DNS_entries (nodes_config, sites_config):
  1079. forward_zone_name = ""
  1080. forward_zone = []
  1081. zones = {
  1082. # <forward_zone_name>: [],
  1083. # <rev_zone1_name>: [],
  1084. # <rev_zone2_name>: [],
  1085. # ...
  1086. }
  1087. # Fill zones dict with zones configured in DNS_zone_names at the top of this file.
  1088. # Make sure the zone base names provided start with a leading . so the string
  1089. # operations later can be done easily and safely. Proceed with fingers crossed.
  1090. for entry, value in DNS_zone_names.items ():
  1091. if entry == "forward":
  1092. zone = value
  1093. if not zone.startswith ('.'):
  1094. zone = ".%s" % zone
  1095. zones[zone] = forward_zone
  1096. forward_zone_name = zone
  1097. if entry in [ 'rev_v4', 'rev_v6' ]:
  1098. for zone in value:
  1099. if not zone.startswith ('.'):
  1100. zone = ".%s" % zone
  1101. zones[zone] = []
  1102. # Process all interfaace of all nodes defined in pillar and generate forward
  1103. # and reverse entries for all zones defined in DNS_zone_names. Automagically
  1104. # put reverse entries into correct zone.
  1105. for node_id in sorted (nodes_config):
  1106. node_config = nodes_config.get (node_id)
  1107. ifaces = get_interface_config (node_config, sites_config, node_id)
  1108. for iface in sorted (ifaces):
  1109. iface_config = ifaces.get (iface)
  1110. # We only care for interfaces with IPs configured
  1111. prefixes = iface_config.get ("prefixes", None)
  1112. if prefixes == None:
  1113. continue
  1114. # Ignore any interface in $VRF
  1115. if iface_config.get ('vrf', "") in [ 'vrf_external' ]:
  1116. continue
  1117. for prefix in sorted (prefixes):
  1118. ip = ipaddress.ip_address (u'%s' % prefix.split ('/')[0])
  1119. proto = 'v%s' % ip.version
  1120. # The entry name is
  1121. # <node_id> when interface 'lo'
  1122. # <node_name>.srv.<residual> when interface 'srv' (or magically detected internal srv record)
  1123. # <interface>.<node_id> else
  1124. entry_name = node_id
  1125. if iface != "lo":
  1126. entry_name = "%s.%s" % (iface, node_id)
  1127. elif iface == 'srv' or re.search (r'^(10.132.251|2a03:2260:2342:f251:)', prefix):
  1128. entry_name = re.sub (r'^([^.]+)\.(.+)$', r'\g<1>.srv.\g<2>', entry_name)
  1129. # Strip forward zone name from entry_name and store forward entry
  1130. # with correct entry type for found IP address.
  1131. forward_entry_name = re.sub (forward_zone_name, "", entry_name)
  1132. forward_entry_name = re.sub (forward_zone_name, "", entry_name)
  1133. forward_entry_typ = "A" if ip.version == 4 else "AAAA"
  1134. forward_zone.append ("%s IN %s %s" % (forward_entry_name, forward_entry_typ, ip))
  1135. # Find correct reverse zone, if configured and strip reverse zone name
  1136. # from calculated reverse pointer name. Store reverse entry if we found
  1137. # a zone for it. If no configured reverse zone did match, this reverse
  1138. # entry will be ignored.
  1139. for zone in zones:
  1140. if ip.reverse_pointer.find (zone) > 0:
  1141. PTR_entry = re.sub (zone, "", ip.reverse_pointer)
  1142. zones[zone].append ("%s IN PTR %s." % (PTR_entry, entry_name))
  1143. break
  1144. return zones
  1145. # Convert the CIDR network from the given prefix into a dotted netmask
  1146. def cidr_to_dotted_mask (prefix):
  1147. from ipcalc import Network
  1148. return str (Network (prefix).netmask ())
  1149. def is_subprefix (prefix, subprefix):
  1150. from ipcalc import Network
  1151. return subprefix in Network(prefix)
  1152. # Return the network address of the given prefix
  1153. def get_network_address (prefix, with_prefixlen = False):
  1154. net_h = ipaddress.ip_network (u'%s' % prefix, strict = False)
  1155. network = str (net_h.network_address)
  1156. if with_prefixlen:
  1157. network += "/%s" % net_h.prefixlen
  1158. return network