ffho_net.py 44 KB

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