ffho_net.py 43 KB

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