ffho_net.py 42 KB

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