ffho_net.py 45 KB

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