ffho_net.py 38 KB

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