generate_config_quagga.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import ipaddr
  4. import yaml
  5. import sys
  6. import os
  7. import glob
  8. from jinja2 import Environment, FileSystemLoader
  9. from termcolor import colored
  10. def parse_peers(peer_file):
  11. """parse_peers: Just a simple function for peers parsing
  12. :peer_file: The YAML peer file to parse
  13. :returns: Just a return code if the file is correctly parsed or not
  14. """
  15. peering_flat = open(peer_file).read()
  16. ixp = os.path.splitext(os.path.basename(peer_file))[0]
  17. try:
  18. peerings = yaml.safe_load(peering_flat)
  19. except:
  20. print colored('ERROR', 'red') + ": the peers.yaml file could not be parsed.. please check \
  21. your syntax"
  22. sys.exit(2)
  23. for asn in peerings:
  24. for keyword in ['export', 'import', 'description']:
  25. if keyword not in peerings[asn]:
  26. print colored('ERROR', 'red') + ": missing %s statement in stanza %s" % (keyword, asn)
  27. sys.exit(2)
  28. acceptable_exports = ['AS-GITOYEN', 'NOT ANY', 'ANY']
  29. if not peerings[asn]['export'] in acceptable_exports:
  30. print colored('ERROR', 'red') + ": export must be one of the following: %s" \
  31. % " ".join(acceptable_exports)
  32. sys.exit(2)
  33. for peer in peerings[asn]['peerings']:
  34. try:
  35. peer_ip = ipaddr.IPAddress(peer)
  36. if type(ipaddr.IPAddress(peer_ip)) is ipaddr.IPv4Address:
  37. neighbor_ipv4 = peer_ip
  38. if ixp == 'sfinx':
  39. ix4_group = 'SFINX'
  40. else:
  41. ix4_group = 'AMS-IX-PEERS'
  42. elif type(ipaddr.IPAddress(peer_ip)) is ipaddr.IPv6Address:
  43. neighbor_ipv6 = peer_ip
  44. if ixp == 'sfinx':
  45. ix6_group = 'SFINXV6'
  46. else:
  47. ix6_group = 'AMS-IX6-PEERS'
  48. except ValueError:
  49. print colored('ERROR', 'red') + ": %s in %s is not a valid IP" % (peer, asn)
  50. sys.exit(2)
  51. try:
  52. limit_ipv4 = peerings[asn]['limit_ipv4']
  53. except:
  54. limit_ipv4 = False
  55. try:
  56. limit_ipv6 = peerings[asn]['limit_ipv6']
  57. except:
  58. limit_ipv6 = False
  59. env = Environment(loader=FileSystemLoader('./'))
  60. tpl = env.get_template('templates/quagga.j2')
  61. print tpl.render(neighbor_as = asn, description =
  62. peerings[asn]['description'], export_as = peerings[asn]['export'],
  63. import_as = peerings[asn]['import'], neighbor_ipv4 =
  64. neighbor_ipv4, neighbor_ipv6 = neighbor_ipv6, ix4_name =
  65. ix4_group, ix6_name = ix6_group, limit_ipv4 = limit_ipv4,
  66. limit_ipv6 = limit_ipv6)
  67. for peer_files in ('peers/sfinx.yml','peers/amsix.yml'):
  68. parse_peers(peer_files)