ffho_net.py 38 KB

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