ffho_net.py 39 KB

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