source: genesis/tools/gformat.py@ 12508

Last change on this file since 12508 was 12490, checked in by rick, 11 years ago

Maak het linkje klikbaar.

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