source: genesis/tools/gformat.py@ 12624

Last change on this file since 12624 was 12570, checked in by rick, 11 years ago

Tijd om het script wat om te gaan bouwen

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