source: genesis/tools/gformat.py@ 11504

Last change on this file since 11504 was 11503, checked in by rick, 12 years ago

Now with proper caching and shared memory.

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