[8242] | 1 | #!/usr/bin/env python
|
---|
| 2 | #
|
---|
| 3 | # vim:ts=2:et:sw=2:ai
|
---|
| 4 | # Wireless Leiden configuration generator, based on yaml files'
|
---|
[9957] | 5 | #
|
---|
| 6 | # XXX: This should be rewritten to make use of the ipaddr.py library.
|
---|
| 7 | #
|
---|
[10058] | 8 | # Sample apache configuration (mind the AcceptPathInfo!)
|
---|
| 9 | # ScriptAlias /wleiden/config /usr/local/www/genesis/tools/gformat.py
|
---|
| 10 | # <Directory /usr/local/www/genesis>
|
---|
| 11 | # Allow from all
|
---|
| 12 | # AcceptPathInfo On
|
---|
| 13 | # </Directory>
|
---|
| 14 | #
|
---|
[11426] | 15 | # MUCH FASTER WILL IT BE with mod_wsgi, due to caches and avoiding loading all
|
---|
| 16 | # the heavy template lifting all the time.
|
---|
| 17 | #
|
---|
[11503] | 18 | # WSGIDaemonProcess gformat threads=25
|
---|
[11426] | 19 | # WSGISocketPrefix run/wsgi
|
---|
| 20 | #
|
---|
| 21 | # <Directory /var/www/cgi-bin>
|
---|
| 22 | # WSGIProcessGroup gformat
|
---|
| 23 | # </Directory>
|
---|
| 24 | # WSGIScriptAlias /hello /var/www/cgi-bin/genesis/tools/gformat.py
|
---|
| 25 | #
|
---|
| 26 | #
|
---|
[8242] | 27 | # Rick van der Zwet <info@rickvanderzwet.nl>
|
---|
[9957] | 28 | #
|
---|
[8622] | 29 |
|
---|
| 30 | # Hack to make the script directory is also threated as a module search path.
|
---|
| 31 | import sys
|
---|
| 32 | import os
|
---|
[9286] | 33 | import re
|
---|
[8622] | 34 | sys.path.append(os.path.dirname(__file__))
|
---|
[11579] | 35 | sys.path.append('/usr/local/bin')
|
---|
[8622] | 36 |
|
---|
[8242] | 37 | import cgi
|
---|
[8267] | 38 | import cgitb
|
---|
| 39 | import copy
|
---|
[8242] | 40 | import glob
|
---|
[11426] | 41 | import make_network_kml
|
---|
| 42 | import math
|
---|
| 43 | import rdnap
|
---|
[8242] | 44 | import socket
|
---|
| 45 | import string
|
---|
| 46 | import subprocess
|
---|
| 47 | import time
|
---|
[11426] | 48 | import urlparse
|
---|
[8584] | 49 | from pprint import pprint
|
---|
[10281] | 50 | from collections import defaultdict
|
---|
[8575] | 51 | try:
|
---|
| 52 | import yaml
|
---|
| 53 | except ImportError, e:
|
---|
| 54 | print e
|
---|
| 55 | print "[ERROR] Please install the python-yaml or devel/py-yaml package"
|
---|
| 56 | exit(1)
|
---|
[8588] | 57 |
|
---|
| 58 | try:
|
---|
| 59 | from yaml import CLoader as Loader
|
---|
| 60 | from yaml import CDumper as Dumper
|
---|
| 61 | except ImportError:
|
---|
| 62 | from yaml import Loader, Dumper
|
---|
| 63 |
|
---|
[10584] | 64 | from jinja2 import Environment, Template
|
---|
| 65 | def yesorno(value):
|
---|
| 66 | return "YES" if bool(value) else "NO"
|
---|
| 67 | env = Environment()
|
---|
| 68 | env.filters['yesorno'] = yesorno
|
---|
| 69 | def render_template(datadump, template):
|
---|
| 70 | result = env.from_string(template).render(datadump)
|
---|
| 71 | # Make it look pretty to the naked eye, as jinja templates are not so
|
---|
| 72 | # friendly when it comes to whitespace formatting
|
---|
| 73 | ## Remove extra whitespace at end of line lstrip() style.
|
---|
| 74 | result = re.sub(r'\n[\ ]+','\n', result)
|
---|
| 75 | ## Include only a single newline between an definition and a comment
|
---|
| 76 | result = re.sub(r'(["\'])\n+([a-z]|\n#\n)',r'\1\n\2', result)
|
---|
| 77 | ## Remove extra newlines after single comment
|
---|
| 78 | result = re.sub(r'(#\n)\n+([a-z])',r'\1\2', result)
|
---|
| 79 | return result
|
---|
[10110] | 80 |
|
---|
[9697] | 81 | import logging
|
---|
| 82 | logging.basicConfig(format='# %(levelname)s: %(message)s' )
|
---|
| 83 | logger = logging.getLogger()
|
---|
| 84 | logger.setLevel(logging.DEBUG)
|
---|
[8242] | 85 |
|
---|
[9283] | 86 |
|
---|
[8948] | 87 | if os.environ.has_key('CONFIGROOT'):
|
---|
| 88 | NODE_DIR = os.environ['CONFIGROOT']
|
---|
| 89 | else:
|
---|
[9283] | 90 | NODE_DIR = os.path.abspath(os.path.dirname(__file__)) + '/../nodes'
|
---|
[8242] | 91 | __version__ = '$Id: gformat.py 11736 2013-02-14 09:16:54Z rick $'
|
---|
| 92 |
|
---|
[9283] | 93 | files = [
|
---|
[8242] | 94 | 'authorized_keys',
|
---|
| 95 | 'dnsmasq.conf',
|
---|
[10410] | 96 | 'dhcpd.conf',
|
---|
[8242] | 97 | 'rc.conf.local',
|
---|
| 98 | 'resolv.conf',
|
---|
[10069] | 99 | 'motd',
|
---|
[10654] | 100 | 'ntp.conf',
|
---|
[10705] | 101 | 'pf.hybrid.conf.local',
|
---|
[10054] | 102 | 'wleiden.yaml',
|
---|
[8242] | 103 | ]
|
---|
| 104 |
|
---|
[8319] | 105 | # Global variables uses
|
---|
[8323] | 106 | OK = 10
|
---|
| 107 | DOWN = 20
|
---|
| 108 | UNKNOWN = 90
|
---|
[8257] | 109 |
|
---|
[11426] | 110 |
|
---|
[11503] | 111 | ileiden_proxies = []
|
---|
| 112 | normal_proxies = []
|
---|
[10860] | 113 | datadump_cache = {}
|
---|
[11426] | 114 | interface_list_cache = {}
|
---|
| 115 | rc_conf_local_cache = {}
|
---|
[11503] | 116 | nameservers_cache = []
|
---|
[11426] | 117 | def clear_cache():
|
---|
| 118 | ''' Poor mans cache implementation '''
|
---|
[11503] | 119 | global datadump_cache, interface_list_cache, rc_conf_local_cache, ileiden_proxies, normal_proxies, nameservers_cache
|
---|
[11426] | 120 | datadump_cache = {}
|
---|
| 121 | interface_list_cache = {}
|
---|
| 122 | rc_conf_local_cache = {}
|
---|
[11503] | 123 | ileiden_proxies = []
|
---|
| 124 | normal_proxies = []
|
---|
| 125 | nameservers_cache = []
|
---|
[11533] | 126 |
|
---|
[10887] | 127 | NO_DHCP = 0
|
---|
| 128 | DHCP_CLIENT = 10
|
---|
| 129 | DHCP_SERVER = 20
|
---|
| 130 | def dhcp_type(item):
|
---|
| 131 | if not item.has_key('dhcp'):
|
---|
| 132 | return NO_DHCP
|
---|
| 133 | elif not item['dhcp']:
|
---|
| 134 | return NO_DHCP
|
---|
| 135 | elif item['dhcp'].lower() == 'client':
|
---|
| 136 | return DHCP_CLIENT
|
---|
| 137 | else:
|
---|
[10889] | 138 | # Validation Checks
|
---|
| 139 | begin,end = map(int,item['dhcp'].split('-'))
|
---|
| 140 | if begin >= end:
|
---|
| 141 | raise ValueError("DHCP Start >= DHCP End")
|
---|
[10887] | 142 | return DHCP_SERVER
|
---|
| 143 |
|
---|
[10904] | 144 |
|
---|
| 145 |
|
---|
| 146 | def get_yaml(item,add_version_info=True):
|
---|
[10872] | 147 | try:
|
---|
| 148 | """ Get configuration yaml for 'item'"""
|
---|
| 149 | if datadump_cache.has_key(item):
|
---|
| 150 | return datadump_cache[item].copy()
|
---|
[10860] | 151 |
|
---|
[10872] | 152 | gfile = os.path.join(NODE_DIR,item,'wleiden.yaml')
|
---|
[8257] | 153 |
|
---|
[10904] | 154 | # Default values
|
---|
| 155 | datadump = {
|
---|
| 156 | 'autogen_revision' : 'NOTFOUND',
|
---|
| 157 | 'autogen_gfile' : gfile,
|
---|
| 158 | }
|
---|
[10872] | 159 | f = open(gfile, 'r')
|
---|
| 160 | datadump.update(yaml.load(f,Loader=Loader))
|
---|
| 161 | if datadump['nodetype'] == 'Hybrid':
|
---|
| 162 | # Some values are defined implicitly
|
---|
| 163 | if datadump.has_key('rdr_rules') and datadump['rdr_rules'] and not datadump.has_key('service_incoming_rdr'):
|
---|
| 164 | datadump['service_incoming_rdr'] = True
|
---|
| 165 | # Use some boring defaults
|
---|
| 166 | defaults = {
|
---|
| 167 | 'service_proxy_normal' : False,
|
---|
| 168 | 'service_proxy_ileiden' : False,
|
---|
| 169 | 'service_accesspoint' : True,
|
---|
[11326] | 170 | 'service_incoming_rdr' : False,
|
---|
[11538] | 171 | 'service_concentrator' : False,
|
---|
[11326] | 172 | 'monitoring_group' : 'wleiden',
|
---|
[10872] | 173 | }
|
---|
| 174 | for (key,value) in defaults.iteritems():
|
---|
| 175 | if not datadump.has_key(key):
|
---|
| 176 | datadump[key] = value
|
---|
| 177 | f.close()
|
---|
[10391] | 178 |
|
---|
[10904] | 179 | # Sometimes getting version information is useless or harmfull, like in the pre-commit hooks
|
---|
| 180 | if add_version_info:
|
---|
| 181 | p = subprocess.Popen(['svn', 'info', datadump['autogen_gfile']], stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
|
---|
[11624] | 182 | lines = p.communicate()[0].split('\n')
|
---|
| 183 | if p.returncode == 0:
|
---|
| 184 | for line in lines:
|
---|
| 185 | if line:
|
---|
| 186 | (key, value) = line.split(': ')
|
---|
| 187 | datadump["autogen_" + key.lower().replace(' ','_')] = value
|
---|
[10904] | 188 |
|
---|
[10872] | 189 | # Preformat certain needed variables for formatting and push those into special object
|
---|
| 190 | datadump['autogen_iface_keys'] = get_interface_keys(datadump)
|
---|
[10391] | 191 |
|
---|
[10872] | 192 | wlan_count=0
|
---|
| 193 | try:
|
---|
| 194 | for key in datadump['autogen_iface_keys']:
|
---|
[10890] | 195 | datadump[key]['autogen_ifbase'] = key.split('_')[1]
|
---|
[10872] | 196 | if datadump[key]['type'] in ['11a', '11b', '11g', 'wireless']:
|
---|
| 197 | datadump[key]['autogen_ifname'] = 'wlan%i' % wlan_count
|
---|
| 198 | wlan_count += 1
|
---|
| 199 | else:
|
---|
[10890] | 200 | datadump[key]['autogen_ifname'] = datadump[key]['autogen_ifbase']
|
---|
[10872] | 201 | except Exception as e:
|
---|
| 202 | print "# Error while processing interface %s" % key
|
---|
| 203 | raise
|
---|
[10391] | 204 |
|
---|
[10887] | 205 | dhcp_interfaces = [datadump[key]['autogen_ifname'] for key in datadump['autogen_iface_keys'] \
|
---|
| 206 | if dhcp_type(datadump[key]) == DHCP_SERVER]
|
---|
| 207 |
|
---|
[10872] | 208 | datadump['autogen_dhcp_interfaces'] = dhcp_interfaces
|
---|
| 209 | datadump['autogen_item'] = item
|
---|
[10391] | 210 |
|
---|
[10872] | 211 | datadump['autogen_realname'] = get_realname(datadump)
|
---|
| 212 | datadump['autogen_domain'] = datadump['domain'] if datadump.has_key('domain') else 'wleiden.net.'
|
---|
| 213 | datadump['autogen_fqdn'] = datadump['autogen_realname'] + '.' + datadump['autogen_domain']
|
---|
| 214 | datadump_cache[item] = datadump.copy()
|
---|
| 215 | except Exception as e:
|
---|
| 216 | print "# Error while processing %s" % item
|
---|
| 217 | raise
|
---|
[10391] | 218 | return datadump
|
---|
| 219 |
|
---|
| 220 |
|
---|
| 221 | def store_yaml(datadump, header=False):
|
---|
| 222 | """ Store configuration yaml for 'item'"""
|
---|
| 223 | item = datadump['autogen_item']
|
---|
| 224 | gfile = os.path.join(NODE_DIR,item,'wleiden.yaml')
|
---|
| 225 |
|
---|
[10881] | 226 | output = generate_wleiden_yaml(datadump, header)
|
---|
| 227 |
|
---|
[10391] | 228 | f = open(gfile, 'w')
|
---|
[10881] | 229 | f.write(output)
|
---|
[10391] | 230 | f.close()
|
---|
| 231 |
|
---|
| 232 |
|
---|
[10729] | 233 | def network(ip):
|
---|
| 234 | addr, mask = ip.split('/')
|
---|
| 235 | # Not parsing of these folks please
|
---|
| 236 | addr = parseaddr(addr)
|
---|
| 237 | mask = int(mask)
|
---|
| 238 | network = addr & ~((1 << (32 - mask)) - 1)
|
---|
| 239 | return network
|
---|
| 240 |
|
---|
[10391] | 241 |
|
---|
[10729] | 242 |
|
---|
[10932] | 243 | def make_relations(datadumps=dict()):
|
---|
[10270] | 244 | """ Process _ALL_ yaml files to get connection relations """
|
---|
[10729] | 245 | errors = []
|
---|
[10281] | 246 | poel = defaultdict(list)
|
---|
[10729] | 247 |
|
---|
| 248 | if not datadumps:
|
---|
| 249 | for host in get_hostlist():
|
---|
| 250 | datadumps[host] = get_yaml(host)
|
---|
| 251 |
|
---|
| 252 | for host, datadump in datadumps.iteritems():
|
---|
[10270] | 253 | try:
|
---|
| 254 | for iface_key in datadump['autogen_iface_keys']:
|
---|
[10729] | 255 | net_addr = network(datadump[iface_key]['ip'])
|
---|
| 256 | poel[net_addr] += [(host,datadump[iface_key])]
|
---|
[10270] | 257 | except (KeyError, ValueError), e:
|
---|
[10729] | 258 | errors.append("[FOUT] in '%s' interface '%s' (%s)" % (host,iface_key, e))
|
---|
[10270] | 259 | continue
|
---|
| 260 | return (poel, errors)
|
---|
| 261 |
|
---|
| 262 |
|
---|
[8267] | 263 |
|
---|
[8321] | 264 | def valid_addr(addr):
|
---|
| 265 | """ Show which address is valid in which are not """
|
---|
| 266 | return str(addr).startswith('172.')
|
---|
| 267 |
|
---|
[10692] | 268 | def get_system_list(prefix):
|
---|
| 269 | return sorted([os.path.basename(os.path.dirname(x)) for x in glob.glob("%s/%s*/wleiden.yaml" % (NODE_DIR, prefix))])
|
---|
[8321] | 270 |
|
---|
[10692] | 271 | get_hybridlist = lambda: get_system_list("Hybrid")
|
---|
| 272 | get_nodelist = lambda: get_system_list("CNode")
|
---|
| 273 | get_proxylist = lambda: get_system_list("Proxy")
|
---|
[8267] | 274 |
|
---|
[8296] | 275 | def get_hostlist():
|
---|
| 276 | """ Combined hosts and proxy list"""
|
---|
[10192] | 277 | return get_nodelist() + get_proxylist() + get_hybridlist()
|
---|
[8267] | 278 |
|
---|
[8588] | 279 | def angle_between_points(lat1,lat2,long1,long2):
|
---|
[9283] | 280 | """
|
---|
[8588] | 281 | Return Angle in radians between two GPS coordinates
|
---|
| 282 | See: http://stackoverflow.com/questions/3809179/angle-between-2-gps-coordinates
|
---|
| 283 | """
|
---|
| 284 | dy = lat2 - lat1
|
---|
[10729] | 285 | dx = math.cos(lat1)*(long2 - long1)
|
---|
[8588] | 286 | angle = math.atan2(dy,dx)
|
---|
| 287 | return angle
|
---|
[8267] | 288 |
|
---|
[10729] | 289 |
|
---|
| 290 |
|
---|
[8588] | 291 | def angle_to_cd(angle):
|
---|
| 292 | """ Return Dutch Cardinal Direction estimation in 'one digit' of radian angle """
|
---|
| 293 |
|
---|
| 294 | # For easy conversion get positive degree
|
---|
| 295 | degrees = math.degrees(angle)
|
---|
[10729] | 296 | abs_degrees = 360 + degrees if degrees < 0 else degrees
|
---|
[8588] | 297 |
|
---|
| 298 | # Numbers can be confusing calculate from the 4 main directions
|
---|
| 299 | p = 22.5
|
---|
[10729] | 300 | if abs_degrees < p:
|
---|
| 301 | cd = "n"
|
---|
| 302 | elif abs_degrees < (90 - p):
|
---|
| 303 | cd = "no"
|
---|
| 304 | elif abs_degrees < (90 + p):
|
---|
| 305 | cd = "o"
|
---|
| 306 | elif abs_degrees < (180 - p):
|
---|
| 307 | cd = "zo"
|
---|
| 308 | elif abs_degrees < (180 + p):
|
---|
| 309 | cd = "z"
|
---|
| 310 | elif abs_degrees < (270 - p):
|
---|
| 311 | cd = "zw"
|
---|
| 312 | elif abs_degrees < (270 + p):
|
---|
| 313 | cd = "w"
|
---|
| 314 | elif abs_degrees < (360 - p):
|
---|
| 315 | cd = "nw"
|
---|
[8588] | 316 | else:
|
---|
[10729] | 317 | cd = "n"
|
---|
| 318 | return cd
|
---|
[8588] | 319 |
|
---|
| 320 |
|
---|
[10729] | 321 |
|
---|
| 322 | def cd_between_hosts(hostA, hostB, datadumps):
|
---|
| 323 | # Using RDNAP coordinates
|
---|
| 324 | dx = float(int(datadumps[hostA]['rdnap_x']) - int(datadumps[hostB]['rdnap_x'])) * -1
|
---|
| 325 | dy = float(int(datadumps[hostA]['rdnap_y']) - int(datadumps[hostB]['rdnap_y'])) * -1
|
---|
| 326 | return angle_to_cd(math.atan2(dx,dy))
|
---|
| 327 |
|
---|
| 328 | # GPS coordinates seems to fail somehow
|
---|
| 329 | #latA = float(datadumps[hostA]['latitude'])
|
---|
| 330 | #latB = float(datadumps[hostB]['latitude'])
|
---|
| 331 | #lonA = float(datadumps[hostA]['longitude'])
|
---|
| 332 | #lonB = float(datadumps[hostB]['longitude'])
|
---|
| 333 | #return angle_to_cd(angle_between_points(latA, latB, lonA, lonB))
|
---|
| 334 |
|
---|
| 335 |
|
---|
[8267] | 336 | def generate_title(nodelist):
|
---|
[8257] | 337 | """ Main overview page """
|
---|
[9283] | 338 | items = {'root' : "." }
|
---|
[10682] | 339 | def fl(spaces, line):
|
---|
| 340 | return (' ' * spaces) + line + '\n'
|
---|
| 341 |
|
---|
[8267] | 342 | output = """
|
---|
[8257] | 343 | <html>
|
---|
| 344 | <head>
|
---|
| 345 | <title>Wireless leiden Configurator - GFormat</title>
|
---|
| 346 | <style type="text/css">
|
---|
| 347 | th {background-color: #999999}
|
---|
| 348 | tr:nth-child(odd) {background-color: #cccccc}
|
---|
| 349 | tr:nth-child(even) {background-color: #ffffff}
|
---|
| 350 | th, td {padding: 0.1em 1em}
|
---|
| 351 | </style>
|
---|
| 352 | </head>
|
---|
| 353 | <body>
|
---|
| 354 | <center>
|
---|
[8259] | 355 | <form type="GET" action="%(root)s">
|
---|
[8257] | 356 | <input type="hidden" name="action" value="update">
|
---|
| 357 | <input type="submit" value="Update Configuration Database (SVN)">
|
---|
| 358 | </form>
|
---|
| 359 | <table>
|
---|
[10682] | 360 | <caption><h3>Wireless Leiden Configurator</h3></caption>
|
---|
[8257] | 361 | """ % items
|
---|
[8242] | 362 |
|
---|
[8296] | 363 | for node in nodelist:
|
---|
[8257] | 364 | items['node'] = node
|
---|
[10682] | 365 | output += fl(5, '<tr>') + fl(7,'<td><a href="%(root)s/%(node)s">%(node)s</a></td>' % items)
|
---|
[8257] | 366 | for config in files:
|
---|
| 367 | items['config'] = config
|
---|
[10682] | 368 | output += fl(7,'<td><a href="%(root)s/%(node)s/%(config)s">%(config)s</a></td>' % items)
|
---|
| 369 | output += fl(5, "</tr>")
|
---|
[8267] | 370 | output += """
|
---|
[8257] | 371 | </table>
|
---|
| 372 | <hr />
|
---|
| 373 | <em>%s</em>
|
---|
| 374 | </center>
|
---|
| 375 | </body>
|
---|
| 376 | </html>
|
---|
| 377 | """ % __version__
|
---|
[8242] | 378 |
|
---|
[8267] | 379 | return output
|
---|
[8257] | 380 |
|
---|
| 381 |
|
---|
[8267] | 382 |
|
---|
| 383 | def generate_node(node):
|
---|
[8257] | 384 | """ Print overview of all files available for node """
|
---|
[8267] | 385 | return "\n".join(files)
|
---|
[8242] | 386 |
|
---|
[10270] | 387 | def generate_node_overview(host):
|
---|
| 388 | """ Print overview of all files available for node """
|
---|
| 389 | datadump = get_yaml(host)
|
---|
| 390 | params = { 'host' : host }
|
---|
| 391 | output = "<em><a href='..'>Back to overview</a></em><hr />"
|
---|
| 392 | output += "<h2>Available files:</h2><ul>"
|
---|
| 393 | for cf in files:
|
---|
| 394 | params['cf'] = cf
|
---|
| 395 | output += '<li><a href="%(host)s/%(cf)s">%(cf)s</a></li>\n' % params
|
---|
| 396 | output += "</ul>"
|
---|
[8257] | 397 |
|
---|
[10270] | 398 | # Generate and connection listing
|
---|
| 399 | output += "<h2>Connected To:</h2><ul>"
|
---|
[10281] | 400 | (poel, errors) = make_relations()
|
---|
| 401 | for network, hosts in poel.iteritems():
|
---|
| 402 | if host in [x[0] for x in hosts]:
|
---|
| 403 | if len(hosts) == 1:
|
---|
| 404 | # Single not connected interface
|
---|
| 405 | continue
|
---|
| 406 | for remote,ifacedump in hosts:
|
---|
| 407 | if remote == host:
|
---|
| 408 | # This side of the interface
|
---|
| 409 | continue
|
---|
| 410 | params = { 'remote': remote, 'remote_ip' : ifacedump['ip'] }
|
---|
| 411 | output += '<li><a href="%(remote)s">%(remote)s</a> -- %(remote_ip)s</li>\n' % params
|
---|
[10270] | 412 | output += "</ul>"
|
---|
[10281] | 413 | output += "<h2>MOTD details:</h2><pre>" + generate_motd(datadump) + "</pre>"
|
---|
[8257] | 414 |
|
---|
[10270] | 415 | output += "<hr /><em><a href='..'>Back to overview</a></em>"
|
---|
| 416 | return output
|
---|
| 417 |
|
---|
| 418 |
|
---|
[10904] | 419 | def generate_header(datadump, ctag="#"):
|
---|
[8242] | 420 | return """\
|
---|
[9283] | 421 | %(ctag)s
|
---|
[8242] | 422 | %(ctag)s DO NOT EDIT - Automatically generated by 'gformat'
|
---|
[10904] | 423 | %(ctag)s Generated at %(date)s by %(host)s from r%(revision)s
|
---|
[9283] | 424 | %(ctag)s
|
---|
[10904] | 425 | """ % { 'ctag' : ctag, 'date' : time.ctime(), 'host' : socket.gethostname(), 'revision' : datadump['autogen_revision'] }
|
---|
[8242] | 426 |
|
---|
[8257] | 427 |
|
---|
| 428 |
|
---|
[8242] | 429 | def parseaddr(s):
|
---|
[8257] | 430 | """ Process IPv4 CIDR notation addr to a (binary) number """
|
---|
[8242] | 431 | f = s.split('.')
|
---|
| 432 | return (long(f[0]) << 24L) + \
|
---|
| 433 | (long(f[1]) << 16L) + \
|
---|
| 434 | (long(f[2]) << 8L) + \
|
---|
| 435 | long(f[3])
|
---|
| 436 |
|
---|
[8257] | 437 |
|
---|
| 438 |
|
---|
[8242] | 439 | def showaddr(a):
|
---|
[8257] | 440 | """ Display IPv4 addr in (dotted) CIDR notation """
|
---|
[8242] | 441 | return "%d.%d.%d.%d" % ((a >> 24) & 0xff, (a >> 16) & 0xff, (a >> 8) & 0xff, a & 0xff)
|
---|
| 442 |
|
---|
[8257] | 443 |
|
---|
[8584] | 444 | def is_member(ip, mask, canidate):
|
---|
| 445 | """ Return True if canidate is part of ip/mask block"""
|
---|
[10729] | 446 | ip_addr = parseaddr(ip)
|
---|
| 447 | ip_canidate = parseaddr(canidate)
|
---|
[8584] | 448 | mask = int(mask)
|
---|
| 449 | ip_addr = ip_addr & ~((1 << (32 - mask)) - 1)
|
---|
| 450 | ip_canidate = ip_canidate & ~((1 << (32 - mask)) - 1)
|
---|
| 451 | return ip_addr == ip_canidate
|
---|
[8257] | 452 |
|
---|
[8584] | 453 |
|
---|
| 454 |
|
---|
[10410] | 455 | def cidr2netmask(netmask):
|
---|
[8257] | 456 | """ Given a 'netmask' return corresponding CIDR """
|
---|
[8242] | 457 | return showaddr(0xffffffff & (0xffffffff << (32 - int(netmask))))
|
---|
| 458 |
|
---|
[10410] | 459 | def get_network(addr, mask):
|
---|
| 460 | return showaddr(parseaddr(addr) & ~((1 << (32 - int(mask))) - 1))
|
---|
[8257] | 461 |
|
---|
| 462 |
|
---|
[10410] | 463 | def generate_dhcpd_conf(datadump):
|
---|
| 464 | """ Generate config file '/usr/local/etc/dhcpd.conf """
|
---|
[10904] | 465 | output = generate_header(datadump)
|
---|
[10410] | 466 | output += Template("""\
|
---|
| 467 | # option definitions common to all supported networks...
|
---|
| 468 | option domain-name "dhcp.{{ autogen_fqdn }}";
|
---|
| 469 |
|
---|
| 470 | default-lease-time 600;
|
---|
| 471 | max-lease-time 7200;
|
---|
| 472 |
|
---|
| 473 | # Use this to enble / disable dynamic dns updates globally.
|
---|
| 474 | #ddns-update-style none;
|
---|
| 475 |
|
---|
| 476 | # If this DHCP server is the official DHCP server for the local
|
---|
| 477 | # network, the authoritative directive should be uncommented.
|
---|
| 478 | authoritative;
|
---|
| 479 |
|
---|
| 480 | # Use this to send dhcp log messages to a different log file (you also
|
---|
| 481 | # have to hack syslog.conf to complete the redirection).
|
---|
| 482 | log-facility local7;
|
---|
| 483 |
|
---|
| 484 | #
|
---|
| 485 | # Interface definitions
|
---|
| 486 | #
|
---|
| 487 | \n""").render(datadump)
|
---|
| 488 |
|
---|
[10734] | 489 | dhcp_out = defaultdict(list)
|
---|
[10410] | 490 | for iface_key in datadump['autogen_iface_keys']:
|
---|
[10734] | 491 | ifname = datadump[iface_key]['autogen_ifname']
|
---|
[10410] | 492 | if not datadump[iface_key].has_key('comment'):
|
---|
[10455] | 493 | datadump[iface_key]['comment'] = None
|
---|
[10890] | 494 | dhcp_out[ifname].append(" ## %(autogen_ifname)s - %(comment)s\n" % datadump[iface_key])
|
---|
[10410] | 495 |
|
---|
| 496 | (addr, mask) = datadump[iface_key]['ip'].split('/')
|
---|
[10882] | 497 | datadump[iface_key]['autogen_addr'] = addr
|
---|
| 498 | datadump[iface_key]['autogen_netmask'] = cidr2netmask(mask)
|
---|
| 499 | datadump[iface_key]['autogen_subnet'] = get_network(addr, mask)
|
---|
[10889] | 500 | if dhcp_type(datadump[iface_key]) != DHCP_SERVER:
|
---|
| 501 | dhcp_out[ifname].append(" subnet %(autogen_subnet)s netmask %(autogen_netmask)s {\n ### not autoritive\n }\n" % \
|
---|
| 502 | datadump[iface_key])
|
---|
[10410] | 503 | continue
|
---|
| 504 |
|
---|
[10889] | 505 | (dhcp_start, dhcp_stop) = datadump[iface_key]['dhcp'].split('-')
|
---|
[10410] | 506 | dhcp_part = ".".join(addr.split('.')[0:3])
|
---|
[10882] | 507 | datadump[iface_key]['autogen_dhcp_start'] = dhcp_part + "." + dhcp_start
|
---|
| 508 | datadump[iface_key]['autogen_dhcp_stop'] = dhcp_part + "." + dhcp_stop
|
---|
[10734] | 509 | dhcp_out[ifname].append("""\
|
---|
[10882] | 510 | subnet %(autogen_subnet)s netmask %(autogen_netmask)s {
|
---|
| 511 | range %(autogen_dhcp_start)s %(autogen_dhcp_stop)s;
|
---|
| 512 | option routers %(autogen_addr)s;
|
---|
| 513 | option domain-name-servers %(autogen_addr)s;
|
---|
[10734] | 514 | }
|
---|
| 515 | """ % datadump[iface_key])
|
---|
[10410] | 516 |
|
---|
[10734] | 517 | for ifname,value in dhcp_out.iteritems():
|
---|
| 518 | output += ("shared-network %s {\n" % ifname) + ''.join(value) + '}\n\n'
|
---|
[10410] | 519 | return output
|
---|
| 520 |
|
---|
| 521 |
|
---|
| 522 |
|
---|
[8242] | 523 | def generate_dnsmasq_conf(datadump):
|
---|
[8257] | 524 | """ Generate configuration file '/usr/local/etc/dnsmasq.conf' """
|
---|
[10904] | 525 | output = generate_header(datadump)
|
---|
[10368] | 526 | output += Template("""\
|
---|
[9283] | 527 | # DHCP server options
|
---|
[8242] | 528 | dhcp-authoritative
|
---|
| 529 | dhcp-fqdn
|
---|
[10391] | 530 | domain=dhcp.{{ autogen_fqdn }}
|
---|
[8242] | 531 | domain-needed
|
---|
| 532 | expand-hosts
|
---|
[10120] | 533 | log-async=100
|
---|
[8242] | 534 |
|
---|
| 535 | # Low memory footprint
|
---|
| 536 | cache-size=10000
|
---|
| 537 |
|
---|
[10368] | 538 | \n""").render(datadump)
|
---|
| 539 |
|
---|
[10281] | 540 | for iface_key in datadump['autogen_iface_keys']:
|
---|
[8262] | 541 | if not datadump[iface_key].has_key('comment'):
|
---|
[10455] | 542 | datadump[iface_key]['comment'] = None
|
---|
[10890] | 543 | output += "## %(autogen_ifname)s - %(comment)s\n" % datadump[iface_key]
|
---|
[8242] | 544 |
|
---|
[10889] | 545 | if dhcp_type(datadump[iface_key]) != DHCP_SERVER:
|
---|
[8242] | 546 | output += "# not autoritive\n\n"
|
---|
| 547 | continue
|
---|
| 548 |
|
---|
[10889] | 549 | (dhcp_start, dhcp_stop) = datadump[iface_key]['dhcp'].split('-')
|
---|
| 550 | (ip, cidr) = datadump[iface_key]['ip'].split('/')
|
---|
| 551 | datadump[iface_key]['autogen_netmask'] = cidr2netmask(cidr)
|
---|
| 552 |
|
---|
[8242] | 553 | dhcp_part = ".".join(ip.split('.')[0:3])
|
---|
[10882] | 554 | datadump[iface_key]['autogen_dhcp_start'] = dhcp_part + "." + dhcp_start
|
---|
| 555 | datadump[iface_key]['autogen_dhcp_stop'] = dhcp_part + "." + dhcp_stop
|
---|
[10890] | 556 | output += "dhcp-range=%(autogen_ifname)s,%(autogen_dhcp_start)s,%(autogen_dhcp_stop)s,%(autogen_netmask)s,24h\n\n" % datadump[iface_key]
|
---|
[9283] | 557 |
|
---|
[8242] | 558 | return output
|
---|
| 559 |
|
---|
[8257] | 560 |
|
---|
[10907] | 561 | def make_interface_list(datadump):
|
---|
| 562 | if interface_list_cache.has_key(datadump['autogen_item']):
|
---|
| 563 | return (interface_list_cache[datadump['autogen_item']])
|
---|
| 564 | # lo0 configuration:
|
---|
| 565 | # - 172.32.255.1/32 is the proxy.wleiden.net deflector
|
---|
| 566 | # - masterip is special as it needs to be assigned to at
|
---|
| 567 | # least one interface, so if not used assign to lo0
|
---|
| 568 | addrs_list = { 'lo0' : [("127.0.0.1/8", "LocalHost"), ("172.31.255.1/32","Proxy IP")] }
|
---|
| 569 | dhclient_if = {'lo0' : False}
|
---|
| 570 |
|
---|
| 571 | # XXX: Find some way of send this output nicely
|
---|
| 572 | output = ''
|
---|
| 573 |
|
---|
| 574 | masterip_used = False
|
---|
| 575 | for iface_key in datadump['autogen_iface_keys']:
|
---|
| 576 | if datadump[iface_key]['ip'].startswith(datadump['masterip']):
|
---|
| 577 | masterip_used = True
|
---|
| 578 | break
|
---|
| 579 | if not masterip_used:
|
---|
| 580 | addrs_list['lo0'].append((datadump['masterip'] + "/32", 'Master IP Not used in interface'))
|
---|
| 581 |
|
---|
| 582 | for iface_key in datadump['autogen_iface_keys']:
|
---|
| 583 | ifacedump = datadump[iface_key]
|
---|
| 584 | ifname = ifacedump['autogen_ifname']
|
---|
| 585 |
|
---|
| 586 | # Flag dhclient is possible
|
---|
[11736] | 587 | if not dhclient_if[ifname]:
|
---|
| 588 | dhclient_if[ifname] = dhcp_type(ifacedump) == DHCP_CLIENT
|
---|
[10907] | 589 |
|
---|
| 590 | # Add interface IP to list
|
---|
| 591 | item = (ifacedump['ip'], ifacedump['comment'])
|
---|
| 592 | if addrs_list.has_key(ifname):
|
---|
| 593 | addrs_list[ifname].append(item)
|
---|
| 594 | else:
|
---|
| 595 | addrs_list[ifname] = [item]
|
---|
| 596 |
|
---|
| 597 | # Alias only needs IP assignment for now, this might change if we
|
---|
| 598 | # are going to use virtual accesspoints
|
---|
| 599 | if "alias" in iface_key:
|
---|
| 600 | continue
|
---|
| 601 |
|
---|
| 602 | # XXX: Might want to deduct type directly from interface name
|
---|
| 603 | if ifacedump['type'] in ['11a', '11b', '11g', 'wireless']:
|
---|
| 604 | # Default to station (client) mode
|
---|
| 605 | ifacedump['autogen_wlanmode'] = "sta"
|
---|
| 606 | if ifacedump['mode'] in ['master', 'master-wds', 'ap', 'ap-wds']:
|
---|
| 607 | ifacedump['autogen_wlanmode'] = "ap"
|
---|
| 608 | # Default to 802.11b mode
|
---|
| 609 | ifacedump['mode'] = '11b'
|
---|
| 610 | if ifacedump['type'] in ['11a', '11b' '11g']:
|
---|
| 611 | ifacedump['mode'] = ifacedump['type']
|
---|
| 612 |
|
---|
| 613 | if not ifacedump.has_key('channel'):
|
---|
| 614 | if ifacedump['type'] == '11a':
|
---|
| 615 | ifacedump['channel'] = 36
|
---|
| 616 | else:
|
---|
| 617 | ifacedump['channel'] = 1
|
---|
| 618 |
|
---|
| 619 | # Allow special hacks at the back like wds and stuff
|
---|
| 620 | if not ifacedump.has_key('extra'):
|
---|
| 621 | ifacedump['autogen_extra'] = 'regdomain ETSI country NL'
|
---|
| 622 | else:
|
---|
| 623 | ifacedump['autogen_extra'] = ifacedump['extra']
|
---|
| 624 |
|
---|
| 625 | output += "wlans_%(autogen_ifbase)s='%(autogen_ifname)s'\n" % ifacedump
|
---|
| 626 | output += ("create_args_%(autogen_ifname)s='wlanmode %(autogen_wlanmode)s mode " +\
|
---|
| 627 | "%(mode)s ssid %(ssid)s %(autogen_extra)s channel %(channel)s'\n") % ifacedump
|
---|
| 628 |
|
---|
| 629 | elif ifacedump['type'] in ['ethernet', 'eth']:
|
---|
| 630 | # No special config needed besides IP
|
---|
| 631 | pass
|
---|
| 632 | else:
|
---|
| 633 | assert False, "Unknown type " + ifacedump['type']
|
---|
| 634 |
|
---|
| 635 | store = (addrs_list, dhclient_if, output)
|
---|
| 636 | interface_list_cache[datadump['autogen_item']] = store
|
---|
| 637 | return(store)
|
---|
| 638 |
|
---|
| 639 |
|
---|
| 640 |
|
---|
[8242] | 641 | def generate_rc_conf_local(datadump):
|
---|
[8257] | 642 | """ Generate configuration file '/etc/rc.conf.local' """
|
---|
[10860] | 643 | item = datadump['autogen_item']
|
---|
| 644 | if rc_conf_local_cache.has_key(item):
|
---|
| 645 | return rc_conf_local_cache[item]
|
---|
| 646 |
|
---|
[10455] | 647 | if not datadump.has_key('ileiden'):
|
---|
| 648 | datadump['autogen_ileiden_enable'] = False
|
---|
| 649 | else:
|
---|
| 650 | datadump['autogen_ileiden_enable'] = datadump['ileiden']
|
---|
[10110] | 651 |
|
---|
[10547] | 652 | datadump['autogen_ileiden_enable'] = switchFormat(datadump['autogen_ileiden_enable'])
|
---|
| 653 |
|
---|
[10860] | 654 | if not ileiden_proxies or not normal_proxies:
|
---|
| 655 | for proxy in get_proxylist():
|
---|
| 656 | proxydump = get_yaml(proxy)
|
---|
| 657 | if proxydump['ileiden']:
|
---|
| 658 | ileiden_proxies.append(proxydump)
|
---|
| 659 | else:
|
---|
| 660 | normal_proxies.append(proxydump)
|
---|
| 661 | for host in get_hybridlist():
|
---|
| 662 | hostdump = get_yaml(host)
|
---|
| 663 | if hostdump['service_proxy_ileiden']:
|
---|
| 664 | ileiden_proxies.append(hostdump)
|
---|
| 665 | if hostdump['service_proxy_normal']:
|
---|
| 666 | normal_proxies.append(hostdump)
|
---|
[10461] | 667 |
|
---|
[10585] | 668 | datadump['autogen_ileiden_proxies'] = ileiden_proxies
|
---|
| 669 | datadump['autogen_normal_proxies'] = normal_proxies
|
---|
| 670 | datadump['autogen_ileiden_proxies_ips'] = ','.join([x['masterip'] for x in ileiden_proxies])
|
---|
[10112] | 671 | datadump['autogen_ileiden_proxies_names'] = ','.join([x['autogen_item'] for x in ileiden_proxies])
|
---|
[10585] | 672 | datadump['autogen_normal_proxies_ips'] = ','.join([x['masterip'] for x in normal_proxies])
|
---|
[10367] | 673 | datadump['autogen_normal_proxies_names'] = ','.join([x['autogen_item'] for x in normal_proxies])
|
---|
[10112] | 674 |
|
---|
[10904] | 675 | output = generate_header(datadump, "#");
|
---|
[10584] | 676 | output += render_template(datadump, """\
|
---|
[10391] | 677 | hostname='{{ autogen_fqdn }}'
|
---|
[10110] | 678 | location='{{ location }}'
|
---|
| 679 | nodetype="{{ nodetype }}"
|
---|
[9283] | 680 |
|
---|
[10459] | 681 | #
|
---|
| 682 | # Configured listings
|
---|
| 683 | #
|
---|
| 684 | captive_portal_whitelist=""
|
---|
| 685 | {% if nodetype == "Proxy" %}
|
---|
[10054] | 686 | #
|
---|
[10459] | 687 | # Proxy Configuration
|
---|
[10054] | 688 | #
|
---|
[10110] | 689 | {% if gateway -%}
|
---|
| 690 | defaultrouter="{{ gateway }}"
|
---|
| 691 | {% else -%}
|
---|
| 692 | #defaultrouter="NOTSET"
|
---|
| 693 | {% endif -%}
|
---|
| 694 | internalif="{{ internalif }}"
|
---|
[10112] | 695 | ileiden_enable="{{ autogen_ileiden_enable }}"
|
---|
| 696 | gateway_enable="{{ autogen_ileiden_enable }}"
|
---|
[10238] | 697 | pf_enable="yes"
|
---|
[10302] | 698 | pf_rules="/etc/pf.conf"
|
---|
[10455] | 699 | {% if autogen_ileiden_enable -%}
|
---|
[10234] | 700 | pf_flags="-D ext_if={{ externalif }} -D int_if={{ internalif }} -D publicnat={80,443}"
|
---|
[10238] | 701 | lvrouted_enable="{{ autogen_ileiden_enable }}"
|
---|
| 702 | lvrouted_flags="-u -s s00p3rs3kr3t -m 28"
|
---|
| 703 | {% else -%}
|
---|
| 704 | pf_flags="-D ext_if={{ externalif }} -D int_if={{ internalif }} -D publicnat={0}"
|
---|
[10310] | 705 | {% endif -%}
|
---|
[10238] | 706 | {% if internalroute -%}
|
---|
| 707 | static_routes="wleiden"
|
---|
| 708 | route_wleiden="-net 172.16.0.0/12 {{ internalroute }}"
|
---|
[10110] | 709 | {% endif -%}
|
---|
[10054] | 710 |
|
---|
[10584] | 711 | {% elif nodetype == "Hybrid" %}
|
---|
| 712 | #
|
---|
| 713 | # Hybrid Configuration
|
---|
| 714 | #
|
---|
[10599] | 715 | list_ileiden_proxies="
|
---|
[10585] | 716 | {% for item in autogen_ileiden_proxies -%}
|
---|
| 717 | {{ "%-16s"|format(item.masterip) }} # {{ item.autogen_realname }}
|
---|
| 718 | {% endfor -%}
|
---|
[10599] | 719 | "
|
---|
| 720 | list_normal_proxies="
|
---|
[10585] | 721 | {% for item in autogen_normal_proxies -%}
|
---|
| 722 | {{ "%-16s"|format(item.masterip) }} # {{ item.autogen_realname }}
|
---|
| 723 | {% endfor -%}
|
---|
[10599] | 724 | "
|
---|
[10585] | 725 |
|
---|
[10733] | 726 | captive_portal_interfaces="{{ autogen_dhcp_interfaces|join(',')|default('none', true) }}"
|
---|
[10584] | 727 | externalif="{{ externalif|default('vr0', true) }}"
|
---|
| 728 | masterip="{{ masterip }}"
|
---|
| 729 |
|
---|
| 730 | # Defined services
|
---|
| 731 | service_proxy_ileiden="{{ service_proxy_ileiden|yesorno }}"
|
---|
| 732 | service_proxy_normal="{{ service_proxy_normal|yesorno }}"
|
---|
| 733 | service_accesspoint="{{ service_accesspoint|yesorno }}"
|
---|
[10748] | 734 | service_incoming_rdr="{{ service_incoming_rdr|yesorno }}"
|
---|
[11538] | 735 | service_concentrator="{{ service_concentrator|yesorno }}"
|
---|
[10584] | 736 | #
|
---|
[10459] | 737 |
|
---|
[11540] | 738 | {% if service_proxy_ileiden %}
|
---|
[10584] | 739 | pf_rules="/etc/pf.hybrid.conf"
|
---|
[11540] | 740 | {% if service_concentrator %}
|
---|
[11541] | 741 | pf_flags="-D ext_if=$externalif -D ext_if_net=$externalif:network -D inet_if=tun0 -D inet_ip='(tun0)' -D masterip=$masterip"
|
---|
[11540] | 742 | {% else %}
|
---|
| 743 | pf_flags="-D ext_if=$externalif -D ext_if_net=$externalif:network -D inet_if=$externalif -D inet_ip='($externalif:0)' -D masterip=$masterip"
|
---|
| 744 | {% endif %}
|
---|
[10587] | 745 | pf_flags="$pf_flags -D publicnat=80,443"
|
---|
[10748] | 746 | {% elif service_proxy_normal or service_incoming_rdr %}
|
---|
[10649] | 747 | pf_rules="/etc/pf.hybrid.conf"
|
---|
[10587] | 748 | pf_flags="-D ext_if=$externalif -D ext_if_net=$externalif:network -D masterip=$masterip"
|
---|
[10649] | 749 | pf_flags="$pf_flags -D publicnat=0"
|
---|
[10599] | 750 | lvrouted_flags="$lvrouted_flags -z `make_list "$list_ileiden_proxies" ","`"
|
---|
[10649] | 751 | named_setfib="1"
|
---|
| 752 | tinyproxy_setfib="1"
|
---|
| 753 | dnsmasq_setfib="1"
|
---|
[10698] | 754 | sshd_setfib="1"
|
---|
[10584] | 755 | {% else %}
|
---|
[10983] | 756 | named_auto_forward_only="YES"
|
---|
[10584] | 757 | pf_rules="/etc/pf.node.conf"
|
---|
[10587] | 758 | pf_flags=""
|
---|
[10731] | 759 | lvrouted_flags="$lvrouted_flags -z `make_list "$list_ileiden_proxies" ","`"
|
---|
[10584] | 760 | {% endif %}
|
---|
[11539] | 761 | {% if service_concentrator %}
|
---|
| 762 | # Do mind installing certificates is NOT done automatically for security reasons
|
---|
| 763 | openvpn_enable="YES"
|
---|
| 764 | openvpn_configfile="/usr/local/etc/openvpn/client.conf"
|
---|
| 765 | {% endif %}
|
---|
[10459] | 766 |
|
---|
[10584] | 767 | {% if service_proxy_normal %}
|
---|
| 768 | tinyproxy_enable="yes"
|
---|
| 769 | {% else %}
|
---|
| 770 | pen_wrapper_enable="yes"
|
---|
| 771 | {% endif %}
|
---|
[10460] | 772 |
|
---|
[10584] | 773 | {% if service_accesspoint %}
|
---|
| 774 | pf_flags="$pf_flags -D captive_portal_interfaces=$captive_portal_interfaces"
|
---|
| 775 | {% endif %}
|
---|
[10459] | 776 |
|
---|
[10584] | 777 | {% if board == "ALIX2" %}
|
---|
| 778 | #
|
---|
| 779 | # ''Fat'' configuration, board has 256MB RAM
|
---|
| 780 | #
|
---|
| 781 | dnsmasq_enable="NO"
|
---|
| 782 | named_enable="YES"
|
---|
[10732] | 783 | {% if autogen_dhcp_interfaces -%}
|
---|
[10584] | 784 | dhcpd_enable="YES"
|
---|
[10732] | 785 | dhcpd_flags="$dhcpd_flags {{ autogen_dhcp_interfaces|join(' ') }}"
|
---|
| 786 | {% endif -%}
|
---|
[10584] | 787 | {% endif -%}
|
---|
[10459] | 788 |
|
---|
[10823] | 789 | {% if gateway %}
|
---|
[10584] | 790 | defaultrouter="{{ gateway }}"
|
---|
| 791 | {% endif %}
|
---|
| 792 | {% elif nodetype == "CNode" %}
|
---|
[10459] | 793 | #
|
---|
[10054] | 794 | # NODE iLeiden Configuration
|
---|
[10112] | 795 | #
|
---|
[10585] | 796 |
|
---|
| 797 | # iLeiden Proxies {{ autogen_ileiden_proxies_names }}
|
---|
| 798 | list_ileiden_proxies="{{ autogen_ileiden_proxies_ips }}"
|
---|
| 799 | # normal Proxies {{ autogen_normal_proxies_names }}
|
---|
| 800 | list_normal_proxies="{{ autogen_normal_proxies_ips }}"
|
---|
| 801 |
|
---|
[10732] | 802 | captive_portal_interfaces="{{ autogen_dhcp_interfaces|join(',') }}"
|
---|
[10367] | 803 |
|
---|
| 804 | lvrouted_flags="-u -s s00p3rs3kr3t -m 28 -z $list_ileiden_proxies"
|
---|
[10110] | 805 | {% endif %}
|
---|
| 806 |
|
---|
[10584] | 807 | #
|
---|
| 808 | # Interface definitions
|
---|
| 809 | #\n
|
---|
| 810 | """)
|
---|
| 811 |
|
---|
[10907] | 812 | (addrs_list, dhclient_if, extra_ouput) = make_interface_list(datadump)
|
---|
| 813 | output += extra_ouput
|
---|
[8242] | 814 |
|
---|
[9283] | 815 | # Print IP address which needs to be assigned over here
|
---|
[8242] | 816 | output += "\n"
|
---|
| 817 | for iface,addrs in sorted(addrs_list.iteritems()):
|
---|
[10079] | 818 | for addr, comment in sorted(addrs,key=lambda x: parseaddr(x[0].split('/')[0])):
|
---|
[9808] | 819 | output += "# %s || %s || %s\n" % (iface, addr, comment)
|
---|
[8242] | 820 |
|
---|
[10366] | 821 | # Write DHCLIENT entry
|
---|
| 822 | if dhclient_if[iface]:
|
---|
| 823 | output += "ifconfig_%s='SYNCDHCP'\n\n" % (iface)
|
---|
| 824 | else:
|
---|
[10863] | 825 | # Make sure the external address is always first as this is needed in the
|
---|
| 826 | # firewall setup
|
---|
| 827 | addrs = sorted(addrs,key=lambda x: x[0].split('.')[0], cmp=lambda x,y: cmp(1 if x == '172' else 0, 1 if y == '172' else 0))
|
---|
[10366] | 828 | output += "ipv4_addrs_%s='%s'\n\n" % (iface, " ".join([x[0] for x in addrs]))
|
---|
| 829 |
|
---|
[10860] | 830 | rc_conf_local_cache[datadump['autogen_item']] = output
|
---|
[8242] | 831 | return output
|
---|
| 832 |
|
---|
[8257] | 833 |
|
---|
| 834 |
|
---|
[8242] | 835 |
|
---|
[8317] | 836 | def get_all_configs():
|
---|
| 837 | """ Get dict with key 'host' with all configs present """
|
---|
| 838 | configs = dict()
|
---|
| 839 | for host in get_hostlist():
|
---|
| 840 | datadump = get_yaml(host)
|
---|
| 841 | configs[host] = datadump
|
---|
| 842 | return configs
|
---|
| 843 |
|
---|
| 844 |
|
---|
[8319] | 845 | def get_interface_keys(config):
|
---|
| 846 | """ Quick hack to get all interface keys, later stage convert this to a iterator """
|
---|
[10054] | 847 | return sorted([elem for elem in config.keys() if (elem.startswith('iface_') and not "lo0" in elem)])
|
---|
[8317] | 848 |
|
---|
[8319] | 849 |
|
---|
[8317] | 850 | def get_used_ips(configs):
|
---|
| 851 | """ Return array of all IPs used in config files"""
|
---|
| 852 | ip_list = []
|
---|
[8319] | 853 | for config in configs:
|
---|
[8317] | 854 | ip_list.append(config['masterip'])
|
---|
[8319] | 855 | for iface_key in get_interface_keys(config):
|
---|
[8317] | 856 | l = config[iface_key]['ip']
|
---|
| 857 | addr, mask = l.split('/')
|
---|
| 858 | # Special case do not process
|
---|
[8332] | 859 | if valid_addr(addr):
|
---|
| 860 | ip_list.append(addr)
|
---|
| 861 | else:
|
---|
[9728] | 862 | logger.error("## IP '%s' in '%s' not valid" % (addr, config['nodename']))
|
---|
[8317] | 863 | return sorted(ip_list)
|
---|
| 864 |
|
---|
| 865 |
|
---|
| 866 |
|
---|
[10980] | 867 | def get_nameservers(max_servers=None):
|
---|
[10934] | 868 | if nameservers_cache:
|
---|
[10980] | 869 | return nameservers_cache[0:max_servers]
|
---|
[10934] | 870 |
|
---|
[10935] | 871 | for host in get_hybridlist():
|
---|
| 872 | hostdump = get_yaml(host)
|
---|
[10937] | 873 | if hostdump['status'] == 'up' and (hostdump['service_proxy_ileiden'] or hostdump['service_proxy_normal']):
|
---|
[10936] | 874 | nameservers_cache.append((hostdump['masterip'], hostdump['autogen_realname']))
|
---|
| 875 | for host in get_proxylist():
|
---|
| 876 | hostdump = get_yaml(host)
|
---|
[10937] | 877 | if hostdump['status'] == 'up':
|
---|
| 878 | nameservers_cache.append((hostdump['masterip'], hostdump['autogen_realname']))
|
---|
[10934] | 879 |
|
---|
[10980] | 880 | return nameservers_cache[0:max_servers]
|
---|
[10934] | 881 |
|
---|
| 882 |
|
---|
[8242] | 883 | def generate_resolv_conf(datadump):
|
---|
[8257] | 884 | """ Generate configuration file '/etc/resolv.conf' """
|
---|
[10468] | 885 | # XXX: This should properly going to be an datastructure soon
|
---|
[10904] | 886 | datadump['autogen_header'] = generate_header(datadump, "#")
|
---|
[10468] | 887 | datadump['autogen_edge_nameservers'] = ''
|
---|
| 888 |
|
---|
[10934] | 889 |
|
---|
[10936] | 890 | for masterip,realname in get_nameservers():
|
---|
[10934] | 891 | datadump['autogen_edge_nameservers'] += "nameserver %-15s # %s\n" % (masterip, realname)
|
---|
| 892 |
|
---|
[10468] | 893 | return Template("""\
|
---|
| 894 | {{ autogen_header }}
|
---|
[8242] | 895 | search wleiden.net
|
---|
[10468] | 896 |
|
---|
| 897 | # Try local (cache) first
|
---|
[10209] | 898 | nameserver 127.0.0.1
|
---|
[10468] | 899 |
|
---|
[10584] | 900 | {% if service_proxy_normal or service_proxy_ileiden or nodetype == 'Proxy' -%}
|
---|
[10053] | 901 | nameserver 8.8.8.8 # Google Public NameServer
|
---|
| 902 | nameserver 8.8.4.4 # Google Public NameServer
|
---|
[10468] | 903 | {% else -%}
|
---|
[10646] | 904 | # START DYNAMIC LIST - updated by /tools/nameserver-shuffle
|
---|
[10468] | 905 | {{ autogen_edge_nameservers }}
|
---|
| 906 | {% endif -%}
|
---|
| 907 | """).render(datadump)
|
---|
[10209] | 908 |
|
---|
[9283] | 909 |
|
---|
[8242] | 910 |
|
---|
[10654] | 911 | def generate_ntp_conf(datadump):
|
---|
| 912 | """ Generate configuration file '/etc/ntp.conf' """
|
---|
| 913 | # XXX: This should properly going to be an datastructure soon
|
---|
| 914 |
|
---|
[10904] | 915 | datadump['autogen_header'] = generate_header(datadump, "#")
|
---|
[10654] | 916 | datadump['autogen_ntp_servers'] = ''
|
---|
| 917 | for host in get_proxylist():
|
---|
| 918 | hostdump = get_yaml(host)
|
---|
| 919 | datadump['autogen_ntp_servers'] += "server %(masterip)-15s iburst maxpoll 9 # %(autogen_realname)s\n" % hostdump
|
---|
| 920 | for host in get_hybridlist():
|
---|
| 921 | hostdump = get_yaml(host)
|
---|
| 922 | if hostdump['service_proxy_ileiden'] or hostdump['service_proxy_normal']:
|
---|
| 923 | datadump['autogen_ntp_servers'] += "server %(masterip)-15s iburst maxpoll 9 # %(autogen_realname)s\n" % hostdump
|
---|
| 924 |
|
---|
| 925 | return Template("""\
|
---|
| 926 | {{ autogen_header }}
|
---|
| 927 |
|
---|
| 928 | {% if service_proxy_normal or service_proxy_ileiden or nodetype == 'Proxy' -%}
|
---|
| 929 | # Machine hooked to internet.
|
---|
| 930 | server 0.nl.pool.ntp.org iburst maxpoll 9
|
---|
| 931 | server 1.nl.pool.ntp.org iburst maxpoll 9
|
---|
| 932 | server 2.nl.pool.ntp.org iburst maxpoll 9
|
---|
| 933 | server 3.nl.pool.ntp.org iburst maxpoll 9
|
---|
| 934 | {% else -%}
|
---|
| 935 | # Local Wireless Leiden NTP Servers.
|
---|
| 936 | server 0.pool.ntp.wleiden.net iburst maxpoll 9
|
---|
| 937 | server 1.pool.ntp.wleiden.net iburst maxpoll 9
|
---|
| 938 | server 2.pool.ntp.wleiden.net iburst maxpoll 9
|
---|
| 939 | server 3.pool.ntp.wleiden.net iburst maxpoll 9
|
---|
| 940 |
|
---|
| 941 | # All the configured NTP servers
|
---|
| 942 | {{ autogen_ntp_servers }}
|
---|
| 943 | {% endif %}
|
---|
| 944 |
|
---|
| 945 | # If a server loses sync with all upstream servers, NTP clients
|
---|
| 946 | # no longer follow that server. The local clock can be configured
|
---|
| 947 | # to provide a time source when this happens, but it should usually
|
---|
| 948 | # be configured on just one server on a network. For more details see
|
---|
| 949 | # http://support.ntp.org/bin/view/Support/UndisciplinedLocalClock
|
---|
| 950 | # The use of Orphan Mode may be preferable.
|
---|
| 951 | #
|
---|
| 952 | server 127.127.1.0
|
---|
| 953 | fudge 127.127.1.0 stratum 10
|
---|
| 954 | """).render(datadump)
|
---|
| 955 |
|
---|
| 956 |
|
---|
[10705] | 957 | def generate_pf_hybrid_conf_local(datadump):
|
---|
| 958 | """ Generate configuration file '/etc/pf.hybrid.conf.local' """
|
---|
[10904] | 959 | datadump['autogen_header'] = generate_header(datadump, "#")
|
---|
[10705] | 960 | return Template("""\
|
---|
| 961 | {{ autogen_header }}
|
---|
[10654] | 962 |
|
---|
[10705] | 963 | # Redirect some internal facing services outside (7)
|
---|
[10714] | 964 | # INFO: {{ rdr_rules|count }} rdr_rules (outside to internal redirect rules) defined.
|
---|
[10715] | 965 | {% for protocol, src_port,dest_ip,dest_port in rdr_rules -%}
|
---|
| 966 | rdr on $ext_if inet proto {{ protocol }} from any to $ext_if port {{ src_port }} tag SRV -> {{ dest_ip }} port {{ dest_port }}
|
---|
[10714] | 967 | {% endfor -%}
|
---|
[10705] | 968 | """).render(datadump)
|
---|
| 969 |
|
---|
[10069] | 970 | def generate_motd(datadump):
|
---|
| 971 | """ Generate configuration file '/etc/motd' """
|
---|
[10568] | 972 | output = Template("""\
|
---|
[10627] | 973 | FreeBSD run ``service motd onestart'' to make me look normal
|
---|
[8242] | 974 |
|
---|
[10568] | 975 | WWW: {{ autogen_fqdn }} - http://www.wirelessleiden.nl
|
---|
| 976 | Loc: {{ location }}
|
---|
[8257] | 977 |
|
---|
[10568] | 978 | Services:
|
---|
| 979 | {% if board == "ALIX2" -%}
|
---|
[10906] | 980 | {{" -"}} Core Node ({{ board }})
|
---|
[10568] | 981 | {% else -%}
|
---|
[10906] | 982 | {{" -"}} Hulp Node ({{ board }})
|
---|
[10568] | 983 | {% endif -%}
|
---|
[10584] | 984 | {% if service_proxy_normal -%}
|
---|
[10906] | 985 | {{" -"}} Normal Proxy
|
---|
[10568] | 986 | {% endif -%}
|
---|
[10584] | 987 | {% if service_proxy_ileiden -%}
|
---|
[10906] | 988 | {{" -"}} iLeiden Proxy
|
---|
[10748] | 989 | {% endif -%}
|
---|
| 990 | {% if service_incoming_rdr -%}
|
---|
[10906] | 991 | {{" -"}} Incoming port redirects
|
---|
[10568] | 992 | {% endif %}
|
---|
[10626] | 993 | Interlinks:\n
|
---|
[10568] | 994 | """).render(datadump)
|
---|
[10069] | 995 |
|
---|
[10907] | 996 | (addrs_list, dhclient_if, extra_ouput) = make_interface_list(datadump)
|
---|
| 997 | # Just nasty hack to make the formatting looks nice
|
---|
| 998 | iface_len = max(map(len,addrs_list.keys()))
|
---|
| 999 | addr_len = max(map(len,[x[0] for x in [x[0] for x in addrs_list.values()]]))
|
---|
| 1000 | for iface,addrs in sorted(addrs_list.iteritems()):
|
---|
| 1001 | if iface in ['lo0']:
|
---|
| 1002 | continue
|
---|
| 1003 | for addr, comment in sorted(addrs,key=lambda x: parseaddr(x[0].split('/')[0])):
|
---|
| 1004 | output += " - %s || %s || %s\n" % (iface.ljust(iface_len), addr.ljust(addr_len), comment)
|
---|
| 1005 |
|
---|
| 1006 | output += '\n'
|
---|
[10069] | 1007 | output += """\
|
---|
| 1008 | Attached bridges:
|
---|
| 1009 | """
|
---|
[10907] | 1010 | has_item = False
|
---|
[10069] | 1011 | for iface_key in datadump['autogen_iface_keys']:
|
---|
| 1012 | ifacedump = datadump[iface_key]
|
---|
| 1013 | if ifacedump.has_key('ns_ip'):
|
---|
[10907] | 1014 | has_item = True
|
---|
[10890] | 1015 | output += " - %(autogen_ifname)s || %(mode)s || %(ns_ip)s\n" % ifacedump
|
---|
[10907] | 1016 | if not has_item:
|
---|
| 1017 | output += " - none\n"
|
---|
[10069] | 1018 |
|
---|
| 1019 | return output
|
---|
| 1020 |
|
---|
| 1021 |
|
---|
[8267] | 1022 | def format_yaml_value(value):
|
---|
| 1023 | """ Get yaml value in right syntax for outputting """
|
---|
| 1024 | if isinstance(value,str):
|
---|
[10049] | 1025 | output = '"%s"' % value
|
---|
[8267] | 1026 | else:
|
---|
| 1027 | output = value
|
---|
[9283] | 1028 | return output
|
---|
[8267] | 1029 |
|
---|
| 1030 |
|
---|
| 1031 |
|
---|
| 1032 | def format_wleiden_yaml(datadump):
|
---|
[8242] | 1033 | """ Special formatting to ensure it is editable"""
|
---|
[9283] | 1034 | output = "# Genesis config yaml style\n"
|
---|
[8262] | 1035 | output += "# vim:ts=2:et:sw=2:ai\n"
|
---|
[8242] | 1036 | output += "#\n"
|
---|
| 1037 | iface_keys = [elem for elem in datadump.keys() if elem.startswith('iface_')]
|
---|
| 1038 | for key in sorted(set(datadump.keys()) - set(iface_keys)):
|
---|
[10714] | 1039 | if key == 'rdr_rules':
|
---|
| 1040 | output += '%-10s:\n' % 'rdr_rules'
|
---|
| 1041 | for rdr_rule in datadump[key]:
|
---|
| 1042 | output += '- %s\n' % rdr_rule
|
---|
| 1043 | else:
|
---|
| 1044 | output += "%-10s: %s\n" % (key, format_yaml_value(datadump[key]))
|
---|
[9283] | 1045 |
|
---|
[8242] | 1046 | output += "\n\n"
|
---|
[9283] | 1047 |
|
---|
[10881] | 1048 | # Format (key, required)
|
---|
| 1049 | key_order = (
|
---|
| 1050 | ('comment', True),
|
---|
| 1051 | ('ip', True),
|
---|
| 1052 | ('desc', True),
|
---|
| 1053 | ('sdesc', True),
|
---|
| 1054 | ('mode', True),
|
---|
| 1055 | ('type', True),
|
---|
| 1056 | ('extra_type', False),
|
---|
| 1057 | ('channel', False),
|
---|
| 1058 | ('ssid', False),
|
---|
| 1059 | ('dhcp', True),
|
---|
| 1060 | ('compass', False),
|
---|
| 1061 | ('distance', False),
|
---|
| 1062 | ('ns_ip', False),
|
---|
| 1063 | ('bullet2_ip', False),
|
---|
| 1064 | ('ns_mac', False),
|
---|
| 1065 | ('bullet2_mac', False),
|
---|
| 1066 | ('ns_type', False),
|
---|
[10892] | 1067 | ('bridge_type', False),
|
---|
[10881] | 1068 | ('status', True),
|
---|
| 1069 | )
|
---|
[8272] | 1070 |
|
---|
[8242] | 1071 | for iface_key in sorted(iface_keys):
|
---|
[10881] | 1072 | try:
|
---|
| 1073 | remainder = set(datadump[iface_key].keys()) - set([x[0] for x in key_order])
|
---|
| 1074 | if remainder:
|
---|
| 1075 | raise KeyError("invalid keys: %s" % remainder)
|
---|
[8242] | 1076 |
|
---|
[10881] | 1077 | output += "%s:\n" % iface_key
|
---|
| 1078 | for key,required in key_order:
|
---|
| 1079 | if datadump[iface_key].has_key(key):
|
---|
| 1080 | output += " %-11s: %s\n" % (key, format_yaml_value(datadump[iface_key][key]))
|
---|
| 1081 | output += "\n\n"
|
---|
| 1082 | except Exception as e:
|
---|
| 1083 | print "# Error while processing interface %s" % iface_key
|
---|
| 1084 | raise
|
---|
| 1085 |
|
---|
[8242] | 1086 | return output
|
---|
| 1087 |
|
---|
| 1088 |
|
---|
[8257] | 1089 |
|
---|
[10067] | 1090 | def generate_wleiden_yaml(datadump, header=True):
|
---|
[8267] | 1091 | """ Generate (petty) version of wleiden.yaml"""
|
---|
[10904] | 1092 | output = generate_header(datadump, "#") if header else ''
|
---|
| 1093 |
|
---|
[10053] | 1094 | for key in datadump.keys():
|
---|
| 1095 | if key.startswith('autogen_'):
|
---|
| 1096 | del datadump[key]
|
---|
[10054] | 1097 | # Interface autogen cleanups
|
---|
| 1098 | elif type(datadump[key]) == dict:
|
---|
| 1099 | for key2 in datadump[key].keys():
|
---|
| 1100 | if key2.startswith('autogen_'):
|
---|
| 1101 | del datadump[key][key2]
|
---|
| 1102 |
|
---|
[8267] | 1103 | output += format_wleiden_yaml(datadump)
|
---|
| 1104 | return output
|
---|
| 1105 |
|
---|
| 1106 |
|
---|
[8588] | 1107 | def generate_yaml(datadump):
|
---|
| 1108 | return generate_config(datadump['nodename'], "wleiden.yaml", datadump)
|
---|
[8267] | 1109 |
|
---|
[8588] | 1110 |
|
---|
[9283] | 1111 |
|
---|
[8298] | 1112 | def generate_config(node, config, datadump=None):
|
---|
[8257] | 1113 | """ Print configuration file 'config' of 'node' """
|
---|
[8267] | 1114 | output = ""
|
---|
[8242] | 1115 | try:
|
---|
| 1116 | # Load config file
|
---|
[8298] | 1117 | if datadump == None:
|
---|
| 1118 | datadump = get_yaml(node)
|
---|
[9283] | 1119 |
|
---|
[8242] | 1120 | if config == 'wleiden.yaml':
|
---|
[8267] | 1121 | output += generate_wleiden_yaml(datadump)
|
---|
| 1122 | elif config == 'authorized_keys':
|
---|
[10051] | 1123 | f = open(os.path.join(NODE_DIR,"global_keys"), 'r')
|
---|
[8267] | 1124 | output += f.read()
|
---|
[8242] | 1125 | f.close()
|
---|
| 1126 | elif config == 'dnsmasq.conf':
|
---|
[10281] | 1127 | output += generate_dnsmasq_conf(datadump)
|
---|
[10410] | 1128 | elif config == 'dhcpd.conf':
|
---|
| 1129 | output += generate_dhcpd_conf(datadump)
|
---|
[8242] | 1130 | elif config == 'rc.conf.local':
|
---|
[10281] | 1131 | output += generate_rc_conf_local(datadump)
|
---|
[8242] | 1132 | elif config == 'resolv.conf':
|
---|
[10281] | 1133 | output += generate_resolv_conf(datadump)
|
---|
[10654] | 1134 | elif config == 'ntp.conf':
|
---|
| 1135 | output += generate_ntp_conf(datadump)
|
---|
[10069] | 1136 | elif config == 'motd':
|
---|
[10281] | 1137 | output += generate_motd(datadump)
|
---|
[10705] | 1138 | elif config == 'pf.hybrid.conf.local':
|
---|
| 1139 | output += generate_pf_hybrid_conf_local(datadump)
|
---|
[8242] | 1140 | else:
|
---|
[9283] | 1141 | assert False, "Config not found!"
|
---|
[8242] | 1142 | except IOError, e:
|
---|
[8267] | 1143 | output += "[ERROR] Config file not found"
|
---|
| 1144 | return output
|
---|
[8242] | 1145 |
|
---|
| 1146 |
|
---|
[8257] | 1147 |
|
---|
[11426] | 1148 | def process_cgi_request(environ=os.environ):
|
---|
[8258] | 1149 | """ When calling from CGI """
|
---|
[11426] | 1150 | response_headers = []
|
---|
| 1151 | content_type = 'text/plain'
|
---|
| 1152 |
|
---|
[8258] | 1153 | # Update repository if requested
|
---|
[11427] | 1154 | form = urlparse.parse_qs(environ['QUERY_STRING']) if environ.has_key('QUERY_STRING') else None
|
---|
| 1155 | if form and form.has_key("action") and "update" in form["action"]:
|
---|
[11426] | 1156 | output = "[INFO] Updating subverion, please wait...\n"
|
---|
| 1157 | output += subprocess.Popen(['svn', 'cleanup', "%s/.." % NODE_DIR], stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0]
|
---|
| 1158 | output += subprocess.Popen(['svn', 'up', "%s/.." % NODE_DIR], stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0]
|
---|
| 1159 | output += "[INFO] All done, redirecting in 5 seconds"
|
---|
| 1160 | response_headers += [
|
---|
| 1161 | ('Refresh', '5; url=.'),
|
---|
| 1162 | ]
|
---|
[11533] | 1163 | reload_cache()
|
---|
[11426] | 1164 | else:
|
---|
| 1165 | base_uri = environ['PATH_INFO']
|
---|
| 1166 | uri = base_uri.strip('/').split('/')
|
---|
[9283] | 1167 |
|
---|
[11426] | 1168 | output = "Template Holder"
|
---|
| 1169 | if base_uri.endswith('/create/network.kml'):
|
---|
| 1170 | content_type='application/vnd.google-earth.kml+xml'
|
---|
| 1171 | output = make_network_kml.make_graph()
|
---|
[11444] | 1172 | elif base_uri.endswith('/api/get/nodeplanner.json'):
|
---|
| 1173 | content_type='application/json'
|
---|
| 1174 | output = make_network_kml.make_nodeplanner_json()
|
---|
[11426] | 1175 | elif not uri[0]:
|
---|
| 1176 | if is_text_request(environ):
|
---|
| 1177 | output = '\n'.join(get_hostlist())
|
---|
| 1178 | else:
|
---|
| 1179 | content_type = 'text/html'
|
---|
| 1180 | output = generate_title(get_hostlist())
|
---|
| 1181 | elif len(uri) == 1:
|
---|
| 1182 | if is_text_request(environ):
|
---|
| 1183 | output = generate_node(uri[0])
|
---|
| 1184 | else:
|
---|
| 1185 | content_type = 'text/html'
|
---|
| 1186 | output = generate_node_overview(uri[0])
|
---|
| 1187 | elif len(uri) == 2:
|
---|
| 1188 | output = generate_config(uri[0], uri[1])
|
---|
| 1189 | else:
|
---|
| 1190 | assert False, "Invalid option"
|
---|
[9283] | 1191 |
|
---|
[11426] | 1192 | # Return response
|
---|
| 1193 | response_headers += [
|
---|
| 1194 | ('Content-type', content_type),
|
---|
| 1195 | ('Content-Length', str(len(output))),
|
---|
| 1196 | ]
|
---|
| 1197 | return(response_headers, str(output))
|
---|
[10270] | 1198 |
|
---|
[10681] | 1199 |
|
---|
[10391] | 1200 | def get_realname(datadump):
|
---|
[10365] | 1201 | # Proxy naming convention is special, as the proxy name is also included in
|
---|
| 1202 | # the nodename, when it comes to the numbered proxies.
|
---|
[8588] | 1203 | if datadump['nodetype'] == 'Proxy':
|
---|
[10391] | 1204 | realname = datadump['nodetype'] + datadump['nodename'].replace('proxy','')
|
---|
[8588] | 1205 | else:
|
---|
| 1206 | # By default the full name is listed and also a shortname CNAME for easy use.
|
---|
[10391] | 1207 | realname = datadump['nodetype'] + datadump['nodename']
|
---|
| 1208 | return(realname)
|
---|
[8259] | 1209 |
|
---|
[9283] | 1210 |
|
---|
| 1211 |
|
---|
[10264] | 1212 | def make_dns(output_dir = 'dns', external = False):
|
---|
[8588] | 1213 | items = dict()
|
---|
[8598] | 1214 |
|
---|
[8588] | 1215 | # hostname is key, IP is value
|
---|
[10642] | 1216 | wleiden_zone = defaultdict(list)
|
---|
[8588] | 1217 | wleiden_cname = dict()
|
---|
[8598] | 1218 |
|
---|
[8588] | 1219 | pool = dict()
|
---|
| 1220 | for node in get_hostlist():
|
---|
| 1221 | datadump = get_yaml(node)
|
---|
[9283] | 1222 |
|
---|
[8588] | 1223 | # Proxy naming convention is special
|
---|
[10391] | 1224 | fqdn = datadump['autogen_realname']
|
---|
[10461] | 1225 | if datadump['nodetype'] in ['CNode', 'Hybrid']:
|
---|
[8588] | 1226 | wleiden_cname[datadump['nodename']] = fqdn
|
---|
[10730] | 1227 |
|
---|
| 1228 | if datadump.has_key('rdr_host'):
|
---|
| 1229 | remote_target = datadump['rdr_host']
|
---|
| 1230 | elif datadump.has_key('remote_access') and datadump['remote_access']:
|
---|
| 1231 | remote_target = datadump['remote_access'].split(':')[0]
|
---|
| 1232 | else:
|
---|
| 1233 | remote_target = None
|
---|
[8588] | 1234 |
|
---|
[10730] | 1235 | if remote_target:
|
---|
| 1236 | try:
|
---|
| 1237 | parseaddr(remote_target)
|
---|
| 1238 | wleiden_zone[datadump['nodename'] + '.gw'].append((remote_target, False))
|
---|
| 1239 | except (IndexError, ValueError):
|
---|
| 1240 | wleiden_cname[datadump['nodename'] + '.gw'] = remote_target + '.'
|
---|
| 1241 |
|
---|
| 1242 |
|
---|
[10655] | 1243 | wleiden_zone[fqdn].append((datadump['masterip'], True))
|
---|
[8588] | 1244 |
|
---|
[8598] | 1245 | # Hacking to get proper DHCP IPs and hostnames
|
---|
[8588] | 1246 | for iface_key in get_interface_keys(datadump):
|
---|
[10890] | 1247 | iface_name = iface_key.replace('_','-')
|
---|
[10410] | 1248 | (ip, cidr) = datadump[iface_key]['ip'].split('/')
|
---|
[8588] | 1249 | try:
|
---|
| 1250 | (dhcp_start, dhcp_stop) = datadump[iface_key]['dhcp'].split('-')
|
---|
[10882] | 1251 | datadump[iface_key]['autogen_netmask'] = cidr2netmask(cidr)
|
---|
[8588] | 1252 | dhcp_part = ".".join(ip.split('.')[0:3])
|
---|
| 1253 | if ip != datadump['masterip']:
|
---|
[10655] | 1254 | wleiden_zone["dhcp-gateway-%s.%s" % (iface_name, fqdn)].append((ip, False))
|
---|
[8588] | 1255 | for i in range(int(dhcp_start), int(dhcp_stop) + 1):
|
---|
[10655] | 1256 | wleiden_zone["dhcp-%s-%s.%s" % (i, iface_name, fqdn)].append(("%s.%s" % (dhcp_part, i), True))
|
---|
[10825] | 1257 | except (AttributeError, ValueError, KeyError):
|
---|
[8588] | 1258 | # First push it into a pool, to indentify the counter-part later on
|
---|
| 1259 | addr = parseaddr(ip)
|
---|
[10461] | 1260 | cidr = int(cidr)
|
---|
| 1261 | addr = addr & ~((1 << (32 - cidr)) - 1)
|
---|
[9283] | 1262 | if pool.has_key(addr):
|
---|
[8588] | 1263 | pool[addr] += [(iface_name, fqdn, ip)]
|
---|
[9283] | 1264 | else:
|
---|
[8588] | 1265 | pool[addr] = [(iface_name, fqdn, ip)]
|
---|
| 1266 | continue
|
---|
| 1267 |
|
---|
[9286] | 1268 |
|
---|
| 1269 |
|
---|
[9957] | 1270 | # WL uses an /29 to configure an interface. IP's are ordered like this:
|
---|
[9958] | 1271 | # MasterA (.1) -- DeviceA (.2) <<>> DeviceB (.3) --- SlaveB (.4)
|
---|
[9957] | 1272 |
|
---|
| 1273 | sn = lambda x: re.sub(r'(?i)^cnode','',x)
|
---|
| 1274 |
|
---|
[8598] | 1275 | # Automatic naming convention of interlinks namely 2 + remote.lower()
|
---|
[8588] | 1276 | for (key,value) in pool.iteritems():
|
---|
[9958] | 1277 | # Make sure they are sorted from low-ip to high-ip
|
---|
| 1278 | value = sorted(value, key=lambda x: parseaddr(x[2]))
|
---|
| 1279 |
|
---|
[8588] | 1280 | if len(value) == 1:
|
---|
| 1281 | (iface_name, fqdn, ip) = value[0]
|
---|
[10655] | 1282 | wleiden_zone["2unused-%s.%s" % (iface_name, fqdn)].append((ip, True))
|
---|
[9957] | 1283 |
|
---|
| 1284 | # Device DNS names
|
---|
| 1285 | if 'cnode' in fqdn.lower():
|
---|
[10655] | 1286 | wleiden_zone["d-at-%s.%s" % (iface_name, fqdn)].append((showaddr(parseaddr(ip) + 1), False))
|
---|
| 1287 | wleiden_cname["d-at-%s.%s" % (iface_name,sn(fqdn))] = "d-at-%s.%s" % ((iface_name, fqdn))
|
---|
[9957] | 1288 |
|
---|
[8588] | 1289 | elif len(value) == 2:
|
---|
| 1290 | (a_iface_name, a_fqdn, a_ip) = value[0]
|
---|
| 1291 | (b_iface_name, b_fqdn, b_ip) = value[1]
|
---|
[10655] | 1292 | wleiden_zone["2%s.%s" % (b_fqdn,a_fqdn)].append((a_ip, True))
|
---|
| 1293 | wleiden_zone["2%s.%s" % (a_fqdn,b_fqdn)].append((b_ip, True))
|
---|
[9957] | 1294 |
|
---|
| 1295 | # Device DNS names
|
---|
| 1296 | if 'cnode' in a_fqdn.lower() and 'cnode' in b_fqdn.lower():
|
---|
[10655] | 1297 | wleiden_zone["d-at-%s.%s" % (a_iface_name, a_fqdn)].append((showaddr(parseaddr(a_ip) + 1), False))
|
---|
| 1298 | wleiden_zone["d-at-%s.%s" % (b_iface_name, b_fqdn)].append((showaddr(parseaddr(b_ip) - 1), False))
|
---|
[9957] | 1299 | wleiden_cname["d-at-%s.%s" % (a_iface_name,sn(a_fqdn))] = "d-at-%s.%s" % (a_iface_name, a_fqdn)
|
---|
| 1300 | wleiden_cname["d-at-%s.%s" % (b_iface_name,sn(b_fqdn))] = "d-at-%s.%s" % (b_iface_name, b_fqdn)
|
---|
| 1301 | wleiden_cname["d2%s.%s" % (sn(b_fqdn),sn(a_fqdn))] = "d-at-%s.%s" % (a_iface_name, a_fqdn)
|
---|
| 1302 | wleiden_cname["d2%s.%s" % (sn(a_fqdn),sn(b_fqdn))] = "d-at-%s.%s" % (b_iface_name, b_fqdn)
|
---|
| 1303 |
|
---|
[8588] | 1304 | else:
|
---|
| 1305 | pool_members = [k[1] for k in value]
|
---|
| 1306 | for item in value:
|
---|
[9283] | 1307 | (iface_name, fqdn, ip) = item
|
---|
[10919] | 1308 | wleiden_zone["2ring.%s" % (fqdn)].append((ip, True))
|
---|
[8598] | 1309 |
|
---|
| 1310 | # Include static DNS entries
|
---|
| 1311 | # XXX: Should they override the autogenerated results?
|
---|
| 1312 | # XXX: Convert input to yaml more useable.
|
---|
| 1313 | # Format:
|
---|
| 1314 | ##; this is a comment
|
---|
| 1315 | ## roomburgh=CNodeRoomburgh1
|
---|
| 1316 | ## apkerk1.CNodeVosko=172.17.176.8 ;this as well
|
---|
[10642] | 1317 | dns_list = yaml.load(open(os.path.join(NODE_DIR,'../dns/staticDNS.yaml'),'r'))
|
---|
[9938] | 1318 |
|
---|
| 1319 | # Hack to allow special entries, for development
|
---|
[10642] | 1320 | wleiden_raw = {}
|
---|
[9938] | 1321 |
|
---|
[10642] | 1322 | for line in dns_list:
|
---|
[10660] | 1323 | reverse = False
|
---|
[10642] | 1324 | k, items = line.items()[0]
|
---|
[10660] | 1325 | if type(items) == dict:
|
---|
| 1326 | if items.has_key('reverse'):
|
---|
| 1327 | reverse = items['reverse']
|
---|
| 1328 | items = items['a']
|
---|
| 1329 | else:
|
---|
| 1330 | items = items['cname']
|
---|
| 1331 | items = [items] if type(items) != list else items
|
---|
[10642] | 1332 | for item in items:
|
---|
| 1333 | if item.startswith('IN '):
|
---|
| 1334 | wleiden_raw[k] = item
|
---|
| 1335 | elif valid_addr(item):
|
---|
[10660] | 1336 | wleiden_zone[k].append((item, reverse))
|
---|
[8598] | 1337 | else:
|
---|
[10642] | 1338 | wleiden_cname[k] = item
|
---|
[9283] | 1339 |
|
---|
[10986] | 1340 | # Hack to get dynamic pool listing
|
---|
| 1341 | def chunks(l, n):
|
---|
| 1342 | return [l[i:i+n] for i in range(0, len(l), n)]
|
---|
| 1343 |
|
---|
| 1344 | ntp_servers = [x[0] for x in get_nameservers()]
|
---|
| 1345 | for id, chunk in enumerate(chunks(ntp_servers,(len(ntp_servers)/4))):
|
---|
| 1346 | for ntp_server in chunk:
|
---|
| 1347 | wleiden_zone['%i.pool.ntp' % id].append((ntp_server, False))
|
---|
| 1348 |
|
---|
[8598] | 1349 | details = dict()
|
---|
| 1350 | # 24 updates a day allowed
|
---|
| 1351 | details['serial'] = time.strftime('%Y%m%d%H')
|
---|
| 1352 |
|
---|
[10264] | 1353 | if external:
|
---|
| 1354 | dns_masters = ['siteview.wirelessleiden.nl', 'ns1.vanderzwet.net']
|
---|
| 1355 | else:
|
---|
[10980] | 1356 | dns_masters = ['sunny.wleiden.net'] + ["%s.wleiden.net" % x[1] for x in get_nameservers(max_servers=3)]
|
---|
[10264] | 1357 |
|
---|
| 1358 | details['master'] = dns_masters[0]
|
---|
| 1359 | details['ns_servers'] = '\n'.join(['\tNS\t%s.' % x for x in dns_masters])
|
---|
| 1360 |
|
---|
[8598] | 1361 | dns_header = '''
|
---|
| 1362 | $TTL 3h
|
---|
[11725] | 1363 | %(zone)s. SOA %(master)s. beheer.lijst.wirelessleiden.nl. ( %(serial)s 15m 15m 1w 60s )
|
---|
[8598] | 1364 | ; Serial, Refresh, Retry, Expire, Neg. cache TTL
|
---|
| 1365 |
|
---|
[10264] | 1366 | %(ns_servers)s
|
---|
[8598] | 1367 | \n'''
|
---|
| 1368 |
|
---|
[9283] | 1369 |
|
---|
[10264] | 1370 | if not os.path.isdir(output_dir):
|
---|
| 1371 | os.makedirs(output_dir)
|
---|
[8598] | 1372 | details['zone'] = 'wleiden.net'
|
---|
[9284] | 1373 | f = open(os.path.join(output_dir,"db." + details['zone']), "w")
|
---|
[8598] | 1374 | f.write(dns_header % details)
|
---|
| 1375 |
|
---|
[10655] | 1376 | for host,items in wleiden_zone.iteritems():
|
---|
| 1377 | for ip,reverse in items:
|
---|
[10730] | 1378 | if ip not in ['0.0.0.0']:
|
---|
[10642] | 1379 | f.write("%s.wleiden.net. IN A %s \n" % (host.lower(), ip))
|
---|
[8588] | 1380 | for source,dest in wleiden_cname.iteritems():
|
---|
[10730] | 1381 | dest = dest if dest.endswith('.') else dest + ".wleiden.net."
|
---|
| 1382 | f.write("%s.wleiden.net. IN CNAME %s\n" % (source.lower(), dest.lower()))
|
---|
[9938] | 1383 | for source, dest in wleiden_raw.iteritems():
|
---|
| 1384 | f.write("%s.wleiden.net. %s\n" % (source, dest))
|
---|
[8588] | 1385 | f.close()
|
---|
[9283] | 1386 |
|
---|
[8598] | 1387 | # Create whole bunch of specific sub arpa zones. To keep it compliant
|
---|
| 1388 | for s in range(16,32):
|
---|
| 1389 | details['zone'] = '%i.172.in-addr.arpa' % s
|
---|
[9284] | 1390 | f = open(os.path.join(output_dir,"db." + details['zone']), "w")
|
---|
[8598] | 1391 | f.write(dns_header % details)
|
---|
[8588] | 1392 |
|
---|
[8598] | 1393 | #XXX: Not effient, fix to proper data structure and do checks at other
|
---|
| 1394 | # stages
|
---|
[10655] | 1395 | for host,items in wleiden_zone.iteritems():
|
---|
| 1396 | for ip,reverse in items:
|
---|
| 1397 | if not reverse:
|
---|
| 1398 | continue
|
---|
[10642] | 1399 | if valid_addr(ip):
|
---|
[10655] | 1400 | if valid_addr(ip):
|
---|
| 1401 | if int(ip.split('.')[1]) == s:
|
---|
| 1402 | rev_ip = '.'.join(reversed(ip.split('.')))
|
---|
| 1403 | f.write("%s.in-addr.arpa. IN PTR %s.wleiden.net.\n" % (rev_ip.lower(), host.lower()))
|
---|
[8598] | 1404 | f.close()
|
---|
[8588] | 1405 |
|
---|
[8598] | 1406 |
|
---|
[8259] | 1407 | def usage():
|
---|
[10567] | 1408 | print """Usage: %(prog)s <argument>
|
---|
| 1409 | Argument:
|
---|
| 1410 | \tstandalone [port] = Run configurator webserver [8000]
|
---|
| 1411 | \tdns [outputdir] = Generate BIND compliant zone files in dns [./dns]
|
---|
[11326] | 1412 | \tnagios-export [--heavy-load] = Generate basic nagios configuration file.
|
---|
[9589] | 1413 | \tfull-export = Generate yaml export script for heatmap.
|
---|
[10567] | 1414 | \tstatic [outputdir] = Generate all config files and store on disk
|
---|
| 1415 | \t with format ./<outputdir>/%%NODE%%/%%FILE%% [./static]
|
---|
[10872] | 1416 | \ttest <node> [<file>] = Receive output for certain node [all files].
|
---|
| 1417 | \ttest-cgi <node> <file> = Receive output of CGI script [all files].
|
---|
[10567] | 1418 | \tlist <status> <items> = List systems which have certain status
|
---|
[10563] | 1419 |
|
---|
[10567] | 1420 | Arguments:
|
---|
| 1421 | \t<node> = NodeName (example: HybridRick)
|
---|
| 1422 | \t<file> = %(files)s
|
---|
| 1423 | \t<status> = all|up|down|planned
|
---|
| 1424 | \t<items> = systems|nodes|proxies
|
---|
| 1425 |
|
---|
[10563] | 1426 | NOTE FOR DEVELOPERS; you can test your changes like this:
|
---|
| 1427 | BEFORE any changes in this code:
|
---|
| 1428 | $ ./gformat.py static /tmp/pre
|
---|
| 1429 | AFTER the changes:
|
---|
| 1430 | $ ./gformat.py static /tmp/post
|
---|
| 1431 | VIEW differences and VERIFY all are OK:
|
---|
[10564] | 1432 | $ diff -urI 'Generated' -r /tmp/pre /tmp/post
|
---|
[10567] | 1433 | """ % { 'prog' : sys.argv[0], 'files' : '|'.join(files) }
|
---|
[8259] | 1434 | exit(0)
|
---|
| 1435 |
|
---|
| 1436 |
|
---|
[11426] | 1437 | def is_text_request(environ=os.environ):
|
---|
[10107] | 1438 | """ Find out whether we are calling from the CLI or any text based CLI utility """
|
---|
| 1439 | try:
|
---|
[11426] | 1440 | return environ['HTTP_USER_AGENT'].split()[0] in ['curl', 'fetch', 'wget']
|
---|
[10107] | 1441 | except KeyError:
|
---|
| 1442 | return True
|
---|
[8259] | 1443 |
|
---|
[10547] | 1444 | def switchFormat(setting):
|
---|
| 1445 | if setting:
|
---|
| 1446 | return "YES"
|
---|
| 1447 | else:
|
---|
| 1448 | return "NO"
|
---|
| 1449 |
|
---|
[10885] | 1450 | def rlinput(prompt, prefill=''):
|
---|
| 1451 | import readline
|
---|
| 1452 | readline.set_startup_hook(lambda: readline.insert_text(prefill))
|
---|
| 1453 | try:
|
---|
| 1454 | return raw_input(prompt)
|
---|
| 1455 | finally:
|
---|
| 1456 | readline.set_startup_hook()
|
---|
| 1457 |
|
---|
| 1458 | def fix_conflict(left, right, default='i'):
|
---|
| 1459 | while True:
|
---|
| 1460 | print "## %-30s | %-30s" % (left, right)
|
---|
| 1461 | c = raw_input("## Solve Conflict (h for help) <l|r|e|i|> [%s]: " % default)
|
---|
| 1462 | if not c:
|
---|
| 1463 | c = default
|
---|
| 1464 |
|
---|
| 1465 | if c in ['l','1']:
|
---|
| 1466 | return left
|
---|
| 1467 | elif c in ['r','2']:
|
---|
| 1468 | return right
|
---|
| 1469 | elif c in ['e', '3']:
|
---|
| 1470 | return rlinput("Edit: ", "%30s | %30s" % (left, right))
|
---|
| 1471 | elif c in ['i', '4']:
|
---|
| 1472 | return None
|
---|
| 1473 | else:
|
---|
| 1474 | print "#ERROR: '%s' is invalid input (left, right, edit or ignore)!" % c
|
---|
| 1475 |
|
---|
[11427] | 1476 |
|
---|
| 1477 |
|
---|
| 1478 | def print_cgi_response(response_headers, output):
|
---|
| 1479 | """Could we not use some kind of wsgi wrapper to make this output?"""
|
---|
| 1480 | for header in response_headers:
|
---|
| 1481 | print "%s: %s" % header
|
---|
[11444] | 1482 | print
|
---|
[11427] | 1483 | print output
|
---|
| 1484 |
|
---|
| 1485 |
|
---|
[11534] | 1486 | def fill_cache():
|
---|
| 1487 | ''' Poor man re-loading of few cache items (the slow ones) '''
|
---|
| 1488 | for host in get_hostlist():
|
---|
[11535] | 1489 | get_yaml(host)
|
---|
[11427] | 1490 |
|
---|
[11534] | 1491 |
|
---|
| 1492 | def reload_cache():
|
---|
| 1493 | clear_cache()
|
---|
| 1494 | fill_cache()
|
---|
| 1495 |
|
---|
| 1496 |
|
---|
[8267] | 1497 | def main():
|
---|
| 1498 | """Hard working sub"""
|
---|
| 1499 | # Allow easy hacking using the CLI
|
---|
| 1500 | if not os.environ.has_key('PATH_INFO'):
|
---|
| 1501 | if len(sys.argv) < 2:
|
---|
| 1502 | usage()
|
---|
[9283] | 1503 |
|
---|
[8267] | 1504 | if sys.argv[1] == "standalone":
|
---|
| 1505 | import SocketServer
|
---|
| 1506 | import CGIHTTPServer
|
---|
[10105] | 1507 | # Hop to the right working directory.
|
---|
| 1508 | os.chdir(os.path.dirname(__file__))
|
---|
[8267] | 1509 | try:
|
---|
| 1510 | PORT = int(sys.argv[2])
|
---|
| 1511 | except (IndexError,ValueError):
|
---|
| 1512 | PORT = 8000
|
---|
[9283] | 1513 |
|
---|
[8267] | 1514 | class MyCGIHTTPRequestHandler(CGIHTTPServer.CGIHTTPRequestHandler):
|
---|
| 1515 | """ Serve this CGI from the root of the webserver """
|
---|
| 1516 | def is_cgi(self):
|
---|
| 1517 | if "favicon" in self.path:
|
---|
| 1518 | return False
|
---|
[9283] | 1519 |
|
---|
[10364] | 1520 | self.cgi_info = (os.path.basename(__file__), self.path)
|
---|
[8267] | 1521 | self.path = ''
|
---|
| 1522 | return True
|
---|
| 1523 | handler = MyCGIHTTPRequestHandler
|
---|
[9807] | 1524 | SocketServer.TCPServer.allow_reuse_address = True
|
---|
[8267] | 1525 | httpd = SocketServer.TCPServer(("", PORT), handler)
|
---|
| 1526 | httpd.server_name = 'localhost'
|
---|
| 1527 | httpd.server_port = PORT
|
---|
[9283] | 1528 |
|
---|
[9728] | 1529 | logger.info("serving at port %s", PORT)
|
---|
[8860] | 1530 | try:
|
---|
| 1531 | httpd.serve_forever()
|
---|
| 1532 | except KeyboardInterrupt:
|
---|
| 1533 | httpd.shutdown()
|
---|
[9728] | 1534 | logger.info("All done goodbye")
|
---|
[8267] | 1535 | elif sys.argv[1] == "test":
|
---|
[10872] | 1536 | # Basic argument validation
|
---|
| 1537 | try:
|
---|
| 1538 | node = sys.argv[2]
|
---|
| 1539 | datadump = get_yaml(node)
|
---|
| 1540 | except IndexError:
|
---|
| 1541 | print "Invalid argument"
|
---|
| 1542 | exit(1)
|
---|
| 1543 | except IOError as e:
|
---|
| 1544 | print e
|
---|
| 1545 | exit(1)
|
---|
| 1546 |
|
---|
| 1547 |
|
---|
| 1548 | # Get files to generate
|
---|
| 1549 | gen_files = sys.argv[3:] if len(sys.argv) > 3 else files
|
---|
| 1550 |
|
---|
| 1551 | # Actual config generation
|
---|
| 1552 | for config in gen_files:
|
---|
| 1553 | logger.info("## Generating %s %s", node, config)
|
---|
| 1554 | print generate_config(node, config, datadump)
|
---|
| 1555 | elif sys.argv[1] == "test-cgi":
|
---|
[8267] | 1556 | os.environ['PATH_INFO'] = "/".join(sys.argv[2:])
|
---|
| 1557 | os.environ['SCRIPT_NAME'] = __file__
|
---|
[11427] | 1558 | response_headers, output = process_cgi_request()
|
---|
| 1559 | print_cgi_response(response_headers, output)
|
---|
[8296] | 1560 | elif sys.argv[1] == "static":
|
---|
| 1561 | items = dict()
|
---|
[10563] | 1562 | items['output_dir'] = sys.argv[2] if len(sys.argv) > 2 else "./static"
|
---|
[8296] | 1563 | for node in get_hostlist():
|
---|
| 1564 | items['node'] = node
|
---|
[10563] | 1565 | items['wdir'] = "%(output_dir)s/%(node)s" % items
|
---|
[8296] | 1566 | if not os.path.isdir(items['wdir']):
|
---|
| 1567 | os.makedirs(items['wdir'])
|
---|
[8298] | 1568 | datadump = get_yaml(node)
|
---|
[8296] | 1569 | for config in files:
|
---|
| 1570 | items['config'] = config
|
---|
[9728] | 1571 | logger.info("## Generating %(node)s %(config)s" % items)
|
---|
[8296] | 1572 | f = open("%(wdir)s/%(config)s" % items, "w")
|
---|
[8298] | 1573 | f.write(generate_config(node, config, datadump))
|
---|
[8296] | 1574 | f.close()
|
---|
[9514] | 1575 | elif sys.argv[1] == "wind-export":
|
---|
| 1576 | items = dict()
|
---|
| 1577 | for node in get_hostlist():
|
---|
| 1578 | datadump = get_yaml(node)
|
---|
| 1579 | sql = """INSERT IGNORE INTO nodes (name, name_ns, longitude, latitude)
|
---|
| 1580 | VALUES ('%(nodename)s', '%(nodename)s', %(latitude)s, %(longitude)s);""" % datadump;
|
---|
| 1581 | sql = """INSERT IGNORE INTO users_nodes (user_id, node_id, owner)
|
---|
| 1582 | VALUES (
|
---|
| 1583 | (SELECT id FROM users WHERE username = 'rvdzwet'),
|
---|
| 1584 | (SELECT id FROM nodes WHERE name = '%(nodename)s'),
|
---|
| 1585 | 'Y');""" % datadump
|
---|
| 1586 | #for config in files:
|
---|
| 1587 | # items['config'] = config
|
---|
| 1588 | # print "## Generating %(node)s %(config)s" % items
|
---|
| 1589 | # f = open("%(wdir)s/%(config)s" % items, "w")
|
---|
| 1590 | # f.write(generate_config(node, config, datadump))
|
---|
| 1591 | # f.close()
|
---|
| 1592 | for node in get_hostlist():
|
---|
| 1593 | datadump = get_yaml(node)
|
---|
| 1594 | for iface_key in sorted([elem for elem in datadump.keys() if elem.startswith('iface_')]):
|
---|
| 1595 | ifacedump = datadump[iface_key]
|
---|
| 1596 | if ifacedump.has_key('mode') and ifacedump['mode'] == 'ap-wds':
|
---|
| 1597 | ifacedump['nodename'] = datadump['nodename']
|
---|
| 1598 | if not ifacedump.has_key('channel') or not ifacedump['channel']:
|
---|
| 1599 | ifacedump['channel'] = 0
|
---|
| 1600 | sql = """INSERT INTO links (node_id, type, ssid, protocol, channel, status)
|
---|
| 1601 | VALUES ((SELECT id FROM nodes WHERE name = '%(nodename)s'), 'ap',
|
---|
| 1602 | '%(ssid)s', 'IEEE 802.11b', %(channel)s, 'active');""" % ifacedump
|
---|
[11326] | 1603 | elif sys.argv[1] == "nagios-export":
|
---|
| 1604 | try:
|
---|
| 1605 | heavy_load = (sys.argv[2] == "--heavy-load")
|
---|
| 1606 | except IndexError:
|
---|
| 1607 | heavy_load = False
|
---|
| 1608 |
|
---|
| 1609 | hostgroup_details = {
|
---|
| 1610 | 'wleiden' : 'Stichting Wireless Leiden - FreeBSD Nodes',
|
---|
| 1611 | 'wzoeterwoude' : 'Stichting Wireless Leiden - Afdeling Zoeterwoude - Free-WiFi Project',
|
---|
| 1612 | 'walphen' : 'Stichting Wireless Alphen',
|
---|
| 1613 | 'westeinder' : 'WestEinder Plassen',
|
---|
| 1614 | }
|
---|
| 1615 |
|
---|
| 1616 | params = {
|
---|
| 1617 | 'check_interval' : 5 if heavy_load else 60,
|
---|
| 1618 | 'retry_interval' : 1 if heavy_load else 5,
|
---|
| 1619 | 'max_check_attempts' : 10 if heavy_load else 3,
|
---|
| 1620 | }
|
---|
| 1621 |
|
---|
| 1622 | print '''\
|
---|
| 1623 | define host {
|
---|
| 1624 | name wleiden-node ; Default Node Template
|
---|
| 1625 | use generic-host ; Use the standard template as initial starting point
|
---|
| 1626 | check_period 24x7 ; By default, FreeBSD hosts are checked round the clock
|
---|
| 1627 | check_interval %(check_interval)s ; Actively check the host every 5 minutes
|
---|
| 1628 | retry_interval %(retry_interval)s ; Schedule host check retries at 1 minute intervals
|
---|
| 1629 | max_check_attempts %(max_check_attempts)s ; Check each FreeBSD host 10 times (max)
|
---|
| 1630 | register 0 ; DONT REGISTER THIS DEFINITION - ITS NOT A REAL HOST, JUST A TEMPLATE!
|
---|
| 1631 | }
|
---|
| 1632 |
|
---|
| 1633 | define service {
|
---|
| 1634 | name wleiden-service ; Default Service Template
|
---|
| 1635 | use generic-service ; Use the standard template as initial starting point
|
---|
| 1636 | check_period 24x7 ; By default, FreeBSD hosts are checked round the clock
|
---|
| 1637 | check_interval %(check_interval)s ; Actively check the host every 5 minutes
|
---|
| 1638 | retry_interval %(retry_interval)s ; Schedule host check retries at 1 minute intervals
|
---|
| 1639 | max_check_attempts %(max_check_attempts)s ; Check each FreeBSD host 10 times (max)
|
---|
| 1640 | register 0 ; DONT REGISTER THIS DEFINITION - ITS NOT A REAL HOST, JUST A TEMPLATE!
|
---|
| 1641 | }
|
---|
| 1642 |
|
---|
| 1643 | # Please make sure to install:
|
---|
| 1644 | # make -C /usr/ports/net-mgmt/nagios-check_netsnmp install clean
|
---|
| 1645 | #
|
---|
| 1646 | define command{
|
---|
| 1647 | command_name check_netsnmp_disk
|
---|
| 1648 | command_line $USER1$/check_netsnmp -H $HOSTADDRESS$ -o disk
|
---|
| 1649 | }
|
---|
| 1650 |
|
---|
| 1651 | define command{
|
---|
| 1652 | command_name check_netsnmp_load
|
---|
| 1653 | command_line $USER1$/check_netsnmp -H $HOSTADDRESS$ -o load
|
---|
| 1654 | }
|
---|
| 1655 |
|
---|
| 1656 | define command{
|
---|
| 1657 | command_name check_netsnmp_proc
|
---|
| 1658 | command_line $USER1$/check_netsnmp -H $HOSTADDRESS$ -o proc
|
---|
| 1659 | }
|
---|
| 1660 |
|
---|
| 1661 | # TDB: dhcp leases
|
---|
| 1662 | # /usr/local/libexec/nagios/check_netsnmp -H 192.168.178.47 --oid 1 exec
|
---|
| 1663 |
|
---|
| 1664 | # TDB: internet status
|
---|
| 1665 | # /usr/local/libexec/nagios/check_netsnmp -H 192.168.178.47 --oid 1 file
|
---|
| 1666 |
|
---|
| 1667 | # TDB: Advanced local passive checks
|
---|
| 1668 | # /usr/local/libexec/nagios/check_by_ssh
|
---|
| 1669 | ''' % params
|
---|
| 1670 |
|
---|
| 1671 | print '''\
|
---|
| 1672 | # Service Group, not displayed by default
|
---|
| 1673 | define hostgroup {
|
---|
| 1674 | hostgroup_name srv_hybrid
|
---|
| 1675 | alias All Hybrid Nodes
|
---|
| 1676 | register 0
|
---|
| 1677 | }
|
---|
| 1678 |
|
---|
| 1679 | define service {
|
---|
| 1680 | use wleiden-service
|
---|
| 1681 | hostgroup_name srv_hybrid
|
---|
| 1682 | service_description SSH
|
---|
| 1683 | check_command check_ssh
|
---|
| 1684 | }
|
---|
| 1685 |
|
---|
| 1686 | define service {
|
---|
| 1687 | use wleiden-service
|
---|
| 1688 | hostgroup_name srv_hybrid
|
---|
| 1689 | service_description HTTP
|
---|
| 1690 | check_command check_http
|
---|
| 1691 | }
|
---|
| 1692 |
|
---|
| 1693 | define service {
|
---|
| 1694 | use wleiden-service
|
---|
| 1695 | hostgroup_name srv_hybrid
|
---|
| 1696 | service_description DNS
|
---|
| 1697 | check_command check_dns
|
---|
| 1698 | }
|
---|
| 1699 |
|
---|
| 1700 | # TDB: Can only test this if we have the proxy listening to all addresses.
|
---|
| 1701 | # define service {
|
---|
| 1702 | # use wleiden-service
|
---|
| 1703 | # hostgroup_name srv_hybrid
|
---|
| 1704 | # service_description PROXY
|
---|
| 1705 | # check_command check_tcp!3128
|
---|
| 1706 | # }
|
---|
| 1707 | '''
|
---|
| 1708 |
|
---|
| 1709 | if heavy_load:
|
---|
| 1710 | print '''\
|
---|
| 1711 | define service {
|
---|
| 1712 | use wleiden-service
|
---|
| 1713 | hostgroup_name srv_hybrid
|
---|
| 1714 | service_description SNMP
|
---|
| 1715 | check_command check_snmp
|
---|
| 1716 | }
|
---|
| 1717 |
|
---|
| 1718 | define service {
|
---|
| 1719 | use wleiden-service
|
---|
| 1720 | hostgroup_name srv_hybrid
|
---|
| 1721 | service_description NTP
|
---|
| 1722 | check_command check_ntp_peer
|
---|
| 1723 | }
|
---|
| 1724 |
|
---|
| 1725 | define service {
|
---|
| 1726 | use wleiden-service
|
---|
| 1727 | hostgroup_name srv_hybrid
|
---|
| 1728 | service_description LOAD
|
---|
| 1729 | check_command check_netsnmp_load
|
---|
| 1730 | }
|
---|
| 1731 |
|
---|
| 1732 | define service {
|
---|
| 1733 | use wleiden-service
|
---|
| 1734 | hostgroup_name srv_hybrid
|
---|
| 1735 | service_description PROC
|
---|
| 1736 | check_command check_netsnmp_proc
|
---|
| 1737 | }
|
---|
| 1738 |
|
---|
| 1739 | define service {
|
---|
| 1740 | use wleiden-service
|
---|
| 1741 | hostgroup_name srv_hybrid
|
---|
| 1742 | service_description DISK
|
---|
| 1743 | check_command check_netsnmp_disk
|
---|
| 1744 | }
|
---|
| 1745 | '''
|
---|
| 1746 | for node in get_hostlist():
|
---|
| 1747 | datadump = get_yaml(node)
|
---|
| 1748 | if not datadump['status'] == 'up':
|
---|
| 1749 | continue
|
---|
| 1750 | if not hostgroup_details.has_key(datadump['monitoring_group']):
|
---|
| 1751 | hostgroup_details[datadump['monitoring_group']] = datadump['monitoring_group']
|
---|
| 1752 | print '''\
|
---|
| 1753 | define host {
|
---|
| 1754 | use wleiden-node
|
---|
| 1755 | host_name %(autogen_fqdn)s
|
---|
| 1756 | address %(masterip)s
|
---|
| 1757 | hostgroups srv_hybrid,%(monitoring_group)s
|
---|
| 1758 | }
|
---|
| 1759 | ''' % datadump
|
---|
| 1760 |
|
---|
| 1761 | for name,alias in hostgroup_details.iteritems():
|
---|
| 1762 | print '''\
|
---|
| 1763 | define hostgroup {
|
---|
| 1764 | hostgroup_name %s
|
---|
| 1765 | alias %s
|
---|
| 1766 | } ''' % (name, alias)
|
---|
| 1767 |
|
---|
| 1768 |
|
---|
[9589] | 1769 | elif sys.argv[1] == "full-export":
|
---|
| 1770 | hosts = {}
|
---|
| 1771 | for node in get_hostlist():
|
---|
| 1772 | datadump = get_yaml(node)
|
---|
| 1773 | hosts[datadump['nodename']] = datadump
|
---|
| 1774 | print yaml.dump(hosts)
|
---|
| 1775 |
|
---|
[8584] | 1776 | elif sys.argv[1] == "dns":
|
---|
[10264] | 1777 | make_dns(sys.argv[2] if len(sys.argv) > 2 else 'dns', 'external' in sys.argv)
|
---|
[9283] | 1778 | elif sys.argv[1] == "cleanup":
|
---|
[8588] | 1779 | # First generate all datadumps
|
---|
| 1780 | datadumps = dict()
|
---|
[10729] | 1781 | ssid_to_node = dict()
|
---|
[8588] | 1782 | for host in get_hostlist():
|
---|
[9728] | 1783 | logger.info("# Processing: %s", host)
|
---|
[10436] | 1784 | # Set some boring default values
|
---|
| 1785 | datadump = { 'board' : 'UNKNOWN' }
|
---|
| 1786 | datadump.update(get_yaml(host))
|
---|
[10391] | 1787 | datadumps[datadump['autogen_realname']] = datadump
|
---|
[9283] | 1788 |
|
---|
[10729] | 1789 | (poel, errors) = make_relations(datadumps)
|
---|
| 1790 | print "\n".join(["# WARNING: %s" % x for x in errors])
|
---|
[10455] | 1791 |
|
---|
[10156] | 1792 | for host,datadump in datadumps.iteritems():
|
---|
[10881] | 1793 | try:
|
---|
| 1794 | # Convert all yes and no to boolean values
|
---|
| 1795 | def fix_boolean(dump):
|
---|
| 1796 | for key in dump.keys():
|
---|
| 1797 | if type(dump[key]) == dict:
|
---|
| 1798 | dump[key] = fix_boolean(dump[key])
|
---|
| 1799 | elif str(dump[key]).lower() in ["yes", "true"]:
|
---|
| 1800 | dump[key] = True
|
---|
| 1801 | elif str(dump[key]).lower() in ["no", "false"]:
|
---|
| 1802 | # Compass richting no (Noord Oost) is valid input
|
---|
| 1803 | if key != "compass": dump[key] = False
|
---|
| 1804 | return dump
|
---|
| 1805 | datadump = fix_boolean(datadump)
|
---|
[10455] | 1806 |
|
---|
[10881] | 1807 | if datadump['rdnap_x'] and datadump['rdnap_y']:
|
---|
| 1808 | datadump['latitude'], datadump['longitude'] = rdnap.rd2etrs(datadump['rdnap_x'], datadump['rdnap_y'])
|
---|
| 1809 | elif datadump['latitude'] and datadump['longitude']:
|
---|
| 1810 | datadump['rdnap_x'], datadump['rdnap_y'] = rdnap.etrs2rd(datadump['latitude'], datadump['longitude'])
|
---|
[10400] | 1811 |
|
---|
[10881] | 1812 | if datadump['nodename'].startswith('Proxy'):
|
---|
| 1813 | datadump['nodename'] = datadump['nodename'].lower()
|
---|
[10319] | 1814 |
|
---|
[10881] | 1815 | for iface_key in datadump['autogen_iface_keys']:
|
---|
[10889] | 1816 | try:
|
---|
| 1817 | # All our normal wireless cards are normal APs now
|
---|
| 1818 | if datadump[iface_key]['type'] in ['11a', '11b', '11g', 'wireless']:
|
---|
| 1819 | datadump[iface_key]['mode'] = 'ap'
|
---|
| 1820 | # Wireless Leiden SSID have an consistent lowercase/uppercase
|
---|
| 1821 | if datadump[iface_key].has_key('ssid'):
|
---|
| 1822 | ssid = datadump[iface_key]['ssid']
|
---|
| 1823 | prefix = 'ap-WirelessLeiden-'
|
---|
| 1824 | if ssid.lower().startswith(prefix.lower()):
|
---|
| 1825 | datadump[iface_key]['ssid'] = prefix + ssid[len(prefix)].upper() + ssid[len(prefix) + 1:]
|
---|
| 1826 | if datadump[iface_key].has_key('ns_ip') and not datadump[iface_key].has_key('mode'):
|
---|
| 1827 | datadump[iface_key]['mode'] = 'autogen-FIXME'
|
---|
| 1828 | if not datadump[iface_key].has_key('comment'):
|
---|
| 1829 | datadump[iface_key]['comment'] = 'autogen-FIXME'
|
---|
[10882] | 1830 |
|
---|
[11732] | 1831 | if datadump[iface_key].has_key('ns_mac'):
|
---|
| 1832 | datadump[iface_key]['ns_mac'] = datadump[iface_key]['ns_mac'].lower()
|
---|
| 1833 |
|
---|
[10889] | 1834 | if datadump[iface_key]['comment'].startswith('autogen-') and datadump[iface_key].has_key('comment'):
|
---|
| 1835 | datadump[iface_key] = datadump[iface_key]['desc']
|
---|
[10882] | 1836 |
|
---|
[11555] | 1837 | # Mandatory interface keys
|
---|
| 1838 | if not datadump[iface_key].has_key('status'):
|
---|
| 1839 | datadump[iface_key]['status'] = 'planned'
|
---|
| 1840 |
|
---|
[10889] | 1841 | x = datadump[iface_key]['comment']
|
---|
| 1842 | datadump[iface_key]['comment'] = x[0].upper() + x[1:]
|
---|
| 1843 |
|
---|
[10884] | 1844 |
|
---|
[10889] | 1845 | if datadump[iface_key].has_key('desc'):
|
---|
| 1846 | if datadump[iface_key]['comment'].lower() == datadump[iface_key]['desc'].lower():
|
---|
[10885] | 1847 | del datadump[iface_key]['desc']
|
---|
[10889] | 1848 | else:
|
---|
| 1849 | print "# ERROR: At %s - %s" % (datadump['nodename'], iface_key)
|
---|
| 1850 | response = fix_conflict(datadump[iface_key]['comment'], datadump[iface_key]['desc'])
|
---|
| 1851 | if response:
|
---|
| 1852 | datadump[iface_key]['comment'] = response
|
---|
| 1853 | del datadump[iface_key]['desc']
|
---|
[10882] | 1854 |
|
---|
[10889] | 1855 | # Check DHCP configuration
|
---|
| 1856 | dhcp_type(datadump[iface_key])
|
---|
| 1857 |
|
---|
| 1858 | # Set the compass value based on the angle between the poels
|
---|
| 1859 | if datadump[iface_key].has_key('ns_ip'):
|
---|
| 1860 | my_pool = poel[network(datadump[iface_key]['ip'])]
|
---|
| 1861 | remote_hosts = list(set([x[0] for x in my_pool]) - set([host]))
|
---|
| 1862 | if remote_hosts:
|
---|
| 1863 | compass_target = remote_hosts[0]
|
---|
| 1864 | datadump[iface_key]['compass'] = cd_between_hosts(host, compass_target, datadumps)
|
---|
| 1865 | except Exception as e:
|
---|
| 1866 | print "# Error while processing interface %s" % iface_key
|
---|
| 1867 | raise
|
---|
[10881] | 1868 | store_yaml(datadump)
|
---|
| 1869 | except Exception as e:
|
---|
| 1870 | print "# Error while processing %s" % host
|
---|
| 1871 | raise
|
---|
[9971] | 1872 | elif sys.argv[1] == "list":
|
---|
[10611] | 1873 | use_fqdn = False
|
---|
[10567] | 1874 | if len(sys.argv) < 4 or not sys.argv[2] in ["up", "down", "planned", "all"]:
|
---|
| 1875 | usage()
|
---|
| 1876 | if sys.argv[3] == "nodes":
|
---|
[9971] | 1877 | systems = get_nodelist()
|
---|
[10567] | 1878 | elif sys.argv[3] == "proxies":
|
---|
[9971] | 1879 | systems = get_proxylist()
|
---|
[10567] | 1880 | elif sys.argv[3] == "systems":
|
---|
[10270] | 1881 | systems = get_hostlist()
|
---|
[9971] | 1882 | else:
|
---|
| 1883 | usage()
|
---|
[10611] | 1884 | if len(sys.argv) > 4:
|
---|
| 1885 | if sys.argv[4] == "fqdn":
|
---|
| 1886 | use_fqdn = True
|
---|
| 1887 | else:
|
---|
| 1888 | usage()
|
---|
| 1889 |
|
---|
[9971] | 1890 | for system in systems:
|
---|
| 1891 | datadump = get_yaml(system)
|
---|
[10611] | 1892 |
|
---|
| 1893 | output = datadump['autogen_fqdn'] if use_fqdn else system
|
---|
[10567] | 1894 | if sys.argv[2] == "all":
|
---|
[10611] | 1895 | print output
|
---|
[10567] | 1896 | elif datadump['status'] == sys.argv[2]:
|
---|
[10611] | 1897 | print output
|
---|
[10378] | 1898 | elif sys.argv[1] == "create":
|
---|
| 1899 | if sys.argv[2] == "network.kml":
|
---|
| 1900 | print make_network_kml.make_graph()
|
---|
[10998] | 1901 | elif sys.argv[2] == "host-ips.txt":
|
---|
| 1902 | for system in get_hostlist():
|
---|
| 1903 | datadump = get_yaml(system)
|
---|
| 1904 | ips = [datadump['masterip']]
|
---|
| 1905 | for ifkey in datadump['autogen_iface_keys']:
|
---|
| 1906 | ips.append(datadump[ifkey]['ip'].split('/')[0])
|
---|
| 1907 | print system, ' '.join(ips)
|
---|
[10999] | 1908 | elif sys.argv[2] == "host-pos.txt":
|
---|
| 1909 | for system in get_hostlist():
|
---|
| 1910 | datadump = get_yaml(system)
|
---|
| 1911 | print system, datadump['rdnap_x'], datadump['rdnap_y']
|
---|
[10378] | 1912 | else:
|
---|
[10998] | 1913 | usage()
|
---|
| 1914 | else:
|
---|
[9283] | 1915 | usage()
|
---|
| 1916 | else:
|
---|
[10070] | 1917 | # Do not enable debugging for config requests as it highly clutters the output
|
---|
| 1918 | if not is_text_request():
|
---|
| 1919 | cgitb.enable()
|
---|
[11427] | 1920 | response_headers, output = process_cgi_request()
|
---|
| 1921 | print_cgi_response(response_headers, output)
|
---|
[9283] | 1922 |
|
---|
[11426] | 1923 | def application(environ, start_response):
|
---|
| 1924 | status = '200 OK'
|
---|
| 1925 | response_headers, output = process_cgi_request(environ)
|
---|
| 1926 | start_response(status, response_headers)
|
---|
[9283] | 1927 |
|
---|
[11426] | 1928 | # Debugging only
|
---|
| 1929 | # output = 'wsgi.multithread = %s' % repr(environ['wsgi.multithread'])
|
---|
| 1930 | # soutput += '\nwsgi.multiprocess = %s' % repr(environ['wsgi.multiprocess'])
|
---|
| 1931 | return [output]
|
---|
| 1932 |
|
---|
[9283] | 1933 | if __name__ == "__main__":
|
---|
| 1934 | main()
|
---|