source: genesis/tools/gformat.py@ 12483

Last change on this file since 12483 was 12482, checked in by rick, 11 years ago

beheer:ticket:367 - fixing host checking

  • Property svn:executable set to *
  • Property svn:keywords set to Id
File size: 67.4 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 12482 2013-10-18 21:00:48Z 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 has_item = True
1046 output += " - %(autogen_ifname)s || %(mode)s || %(ns_ip)s\n" % ifacedump
1047 if not has_item:
1048 output += " - none\n"
1049
1050 return output
1051
1052
1053def format_yaml_value(value):
1054 """ Get yaml value in right syntax for outputting """
1055 if isinstance(value,str):
1056 output = '"%s"' % value
1057 else:
1058 output = value
1059 return output
1060
1061
1062
1063def format_wleiden_yaml(datadump):
1064 """ Special formatting to ensure it is editable"""
1065 output = "# Genesis config yaml style\n"
1066 output += "# vim:ts=2:et:sw=2:ai\n"
1067 output += "#\n"
1068 iface_keys = [elem for elem in datadump.keys() if elem.startswith('iface_')]
1069 for key in sorted(set(datadump.keys()) - set(iface_keys)):
1070 if key == 'rdr_rules':
1071 output += '%-10s:\n' % 'rdr_rules'
1072 for rdr_rule in datadump[key]:
1073 output += '- %s\n' % rdr_rule
1074 else:
1075 output += "%-10s: %s\n" % (key, format_yaml_value(datadump[key]))
1076
1077 output += "\n\n"
1078
1079 # Format (key, required)
1080 key_order = (
1081 ('comment', True),
1082 ('ip', True),
1083 ('desc', True),
1084 ('sdesc', True),
1085 ('mode', True),
1086 ('type', True),
1087 ('extra_type', False),
1088 ('channel', False),
1089 ('ssid', False),
1090 ('dhcp', True),
1091 ('compass', False),
1092 ('distance', False),
1093 ('ns_ip', False),
1094 ('bullet2_ip', False),
1095 ('ns_mac', False),
1096 ('bullet2_mac', False),
1097 ('ns_type', False),
1098 ('bridge_type', False),
1099 ('status', True),
1100 )
1101
1102 for iface_key in sorted(iface_keys):
1103 try:
1104 remainder = set(datadump[iface_key].keys()) - set([x[0] for x in key_order])
1105 if remainder:
1106 raise KeyError("invalid keys: %s" % remainder)
1107
1108 output += "%s:\n" % iface_key
1109 for key,required in key_order:
1110 if datadump[iface_key].has_key(key):
1111 output += " %-11s: %s\n" % (key, format_yaml_value(datadump[iface_key][key]))
1112 output += "\n\n"
1113 except Exception as e:
1114 print "# Error while processing interface %s" % iface_key
1115 raise
1116
1117 return output
1118
1119
1120
1121def generate_wleiden_yaml(datadump, header=True):
1122 """ Generate (petty) version of wleiden.yaml"""
1123 output = generate_header(datadump, "#") if header else ''
1124
1125 for key in datadump.keys():
1126 if key.startswith('autogen_'):
1127 del datadump[key]
1128 # Interface autogen cleanups
1129 elif type(datadump[key]) == dict:
1130 for key2 in datadump[key].keys():
1131 if key2.startswith('autogen_'):
1132 del datadump[key][key2]
1133
1134 output += format_wleiden_yaml(datadump)
1135 return output
1136
1137def generate_nanostation_config(datadump, iface, ns_type):
1138 #TODO(rvdz): Make sure the proper nanostation IP and subnet is set
1139 datadump['iface_%s' % iface]['ns_ip'] = datadump['iface_%s' % iface]['ns_ip'].split('/')[0]
1140
1141 datadump.update(datadump['iface_%s' % iface])
1142
1143 return open(os.path.join(os.path.dirname(__file__), 'ns5m.cfg.tmpl'),'r').read() % datadump
1144
1145def generate_yaml(datadump):
1146 return generate_config(datadump['nodename'], "wleiden.yaml", datadump)
1147
1148
1149
1150def generate_config(node, config, datadump=None):
1151 """ Print configuration file 'config' of 'node' """
1152 output = ""
1153 try:
1154 # Load config file
1155 if datadump == None:
1156 datadump = get_yaml(node)
1157
1158 if config == 'wleiden.yaml':
1159 output += generate_wleiden_yaml(datadump)
1160 elif config == 'authorized_keys':
1161 f = open(os.path.join(NODE_DIR,"global_keys"), 'r')
1162 output += f.read()
1163 node_keys = os.path.join(NODE_DIR,node,'authorized_keys')
1164 # Fetch local keys if existing
1165 if os.path.exists(node_keys):
1166 output += open(node_keys, 'r').read()
1167 f.close()
1168 elif config == 'dnsmasq.conf':
1169 output += generate_dnsmasq_conf(datadump)
1170 elif config == 'dhcpd.conf':
1171 output += generate_dhcpd_conf(datadump)
1172 elif config == 'rc.conf.local':
1173 output += generate_rc_conf_local(datadump)
1174 elif config == 'resolv.conf':
1175 output += generate_resolv_conf(datadump)
1176 elif config == 'ntp.conf':
1177 output += generate_ntp_conf(datadump)
1178 elif config == 'motd':
1179 output += generate_motd(datadump)
1180 elif config == 'pf.hybrid.conf.local':
1181 output += generate_pf_hybrid_conf_local(datadump)
1182 elif config.startswith('vr'):
1183 interface, ns_type = config.strip('.yaml').split('-')
1184 output += generate_nanostation_config(datadump, interface, ns_type)
1185 else:
1186 assert False, "Config not found!"
1187 except IOError, e:
1188 output += "[ERROR] Config file not found"
1189 return output
1190
1191
1192
1193def process_cgi_request(environ=os.environ):
1194 """ When calling from CGI """
1195 response_headers = []
1196 content_type = 'text/plain'
1197
1198 # Update repository if requested
1199 form = urlparse.parse_qs(environ['QUERY_STRING']) if environ.has_key('QUERY_STRING') else None
1200 if form and form.has_key("action") and "update" in form["action"]:
1201 output = "[INFO] Updating subverion, please wait...\n"
1202 output += subprocess.Popen([SVN, 'cleanup', "%s/.." % NODE_DIR], stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0]
1203 output += subprocess.Popen([SVN, 'up', "%s/.." % NODE_DIR], stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0]
1204 output += "[INFO] All done, redirecting in 5 seconds"
1205 response_headers += [
1206 ('Refresh', '5; url=.'),
1207 ]
1208 reload_cache()
1209 else:
1210 base_uri = environ['PATH_INFO']
1211 uri = base_uri.strip('/').split('/')
1212
1213 output = "Template Holder"
1214 if base_uri.endswith('/create/network.kml'):
1215 content_type='application/vnd.google-earth.kml+xml'
1216 output = make_network_kml.make_graph()
1217 elif base_uri.endswith('/api/get/nodeplanner.json'):
1218 content_type='application/json'
1219 output = make_network_kml.make_nodeplanner_json()
1220 elif not uri[0]:
1221 if is_text_request(environ):
1222 output = '\n'.join(get_hostlist())
1223 else:
1224 content_type = 'text/html'
1225 output = generate_title(get_hostlist())
1226 elif len(uri) == 1:
1227 if is_text_request(environ):
1228 output = generate_node(uri[0])
1229 else:
1230 content_type = 'text/html'
1231 output = generate_node_overview(uri[0])
1232 elif len(uri) == 2:
1233 output = generate_config(uri[0], uri[1])
1234 else:
1235 assert False, "Invalid option"
1236
1237 # Return response
1238 response_headers += [
1239 ('Content-type', content_type),
1240 ('Content-Length', str(len(output))),
1241 ]
1242 return(response_headers, str(output))
1243
1244
1245def get_realname(datadump):
1246 # Proxy naming convention is special, as the proxy name is also included in
1247 # the nodename, when it comes to the numbered proxies.
1248 if datadump['nodetype'] == 'Proxy':
1249 realname = datadump['nodetype'] + datadump['nodename'].replace('proxy','')
1250 else:
1251 # By default the full name is listed and also a shortname CNAME for easy use.
1252 realname = datadump['nodetype'] + datadump['nodename']
1253 return(realname)
1254
1255
1256
1257def make_dns(output_dir = 'dns', external = False):
1258 items = dict()
1259
1260 # hostname is key, IP is value
1261 wleiden_zone = defaultdict(list)
1262 wleiden_cname = dict()
1263
1264 pool = dict()
1265 for node in get_hostlist():
1266 datadump = get_yaml(node)
1267
1268 # Proxy naming convention is special
1269 fqdn = datadump['autogen_realname']
1270 if datadump['nodetype'] in ['CNode', 'Hybrid']:
1271 wleiden_cname[datadump['nodename']] = fqdn
1272
1273 if datadump.has_key('rdr_host'):
1274 remote_target = datadump['rdr_host']
1275 elif datadump.has_key('remote_access') and datadump['remote_access']:
1276 remote_target = datadump['remote_access'].split(':')[0]
1277 else:
1278 remote_target = None
1279
1280 if remote_target:
1281 try:
1282 parseaddr(remote_target)
1283 wleiden_zone[datadump['nodename'] + '.gw'].append((remote_target, False))
1284 except (IndexError, ValueError):
1285 wleiden_cname[datadump['nodename'] + '.gw'] = remote_target + '.'
1286
1287
1288 wleiden_zone[fqdn].append((datadump['masterip'], True))
1289
1290 # Hacking to get proper DHCP IPs and hostnames
1291 for iface_key in get_interface_keys(datadump):
1292 iface_name = iface_key.replace('_','-')
1293 (ip, cidr) = datadump[iface_key]['ip'].split('/')
1294 try:
1295 (dhcp_start, dhcp_stop) = datadump[iface_key]['dhcp'].split('-')
1296 datadump[iface_key]['autogen_netmask'] = cidr2netmask(cidr)
1297 dhcp_part = ".".join(ip.split('.')[0:3])
1298 if ip != datadump['masterip']:
1299 wleiden_zone["dhcp-gateway-%s.%s" % (iface_name, fqdn)].append((ip, False))
1300 for i in range(int(dhcp_start), int(dhcp_stop) + 1):
1301 wleiden_zone["dhcp-%s-%s.%s" % (i, iface_name, fqdn)].append(("%s.%s" % (dhcp_part, i), True))
1302 except (AttributeError, ValueError, KeyError):
1303 # First push it into a pool, to indentify the counter-part later on
1304 addr = parseaddr(ip)
1305 cidr = int(cidr)
1306 addr = addr & ~((1 << (32 - cidr)) - 1)
1307 if pool.has_key(addr):
1308 pool[addr] += [(iface_name, fqdn, ip)]
1309 else:
1310 pool[addr] = [(iface_name, fqdn, ip)]
1311 continue
1312
1313
1314
1315 # WL uses an /29 to configure an interface. IP's are ordered like this:
1316 # MasterA (.1) -- DeviceA (.2) <<>> DeviceB (.3) --- SlaveB (.4)
1317
1318 sn = lambda x: re.sub(r'(?i)^cnode','',x)
1319
1320 # Automatic naming convention of interlinks namely 2 + remote.lower()
1321 for (key,value) in pool.iteritems():
1322 # Make sure they are sorted from low-ip to high-ip
1323 value = sorted(value, key=lambda x: parseaddr(x[2]))
1324
1325 if len(value) == 1:
1326 (iface_name, fqdn, ip) = value[0]
1327 wleiden_zone["2unused-%s.%s" % (iface_name, fqdn)].append((ip, True))
1328
1329 # Device DNS names
1330 if 'cnode' in fqdn.lower():
1331 wleiden_zone["d-at-%s.%s" % (iface_name, fqdn)].append((showaddr(parseaddr(ip) + 1), False))
1332 wleiden_cname["d-at-%s.%s" % (iface_name,sn(fqdn))] = "d-at-%s.%s" % ((iface_name, fqdn))
1333
1334 elif len(value) == 2:
1335 (a_iface_name, a_fqdn, a_ip) = value[0]
1336 (b_iface_name, b_fqdn, b_ip) = value[1]
1337 wleiden_zone["2%s.%s" % (b_fqdn,a_fqdn)].append((a_ip, True))
1338 wleiden_zone["2%s.%s" % (a_fqdn,b_fqdn)].append((b_ip, True))
1339
1340 # Device DNS names
1341 if 'cnode' in a_fqdn.lower() and 'cnode' in b_fqdn.lower():
1342 wleiden_zone["d-at-%s.%s" % (a_iface_name, a_fqdn)].append((showaddr(parseaddr(a_ip) + 1), False))
1343 wleiden_zone["d-at-%s.%s" % (b_iface_name, b_fqdn)].append((showaddr(parseaddr(b_ip) - 1), False))
1344 wleiden_cname["d-at-%s.%s" % (a_iface_name,sn(a_fqdn))] = "d-at-%s.%s" % (a_iface_name, a_fqdn)
1345 wleiden_cname["d-at-%s.%s" % (b_iface_name,sn(b_fqdn))] = "d-at-%s.%s" % (b_iface_name, b_fqdn)
1346 wleiden_cname["d2%s.%s" % (sn(b_fqdn),sn(a_fqdn))] = "d-at-%s.%s" % (a_iface_name, a_fqdn)
1347 wleiden_cname["d2%s.%s" % (sn(a_fqdn),sn(b_fqdn))] = "d-at-%s.%s" % (b_iface_name, b_fqdn)
1348
1349 else:
1350 pool_members = [k[1] for k in value]
1351 for item in value:
1352 (iface_name, fqdn, ip) = item
1353 wleiden_zone["2ring.%s" % (fqdn)].append((ip, True))
1354
1355 # Include static DNS entries
1356 # XXX: Should they override the autogenerated results?
1357 # XXX: Convert input to yaml more useable.
1358 # Format:
1359 ##; this is a comment
1360 ## roomburgh=CNodeRoomburgh1
1361 ## apkerk1.CNodeVosko=172.17.176.8 ;this as well
1362 dns_list = yaml.load(open(os.path.join(NODE_DIR,'../dns/staticDNS.yaml'),'r'))
1363
1364 # Hack to allow special entries, for development
1365 wleiden_raw = {}
1366
1367 for line in dns_list:
1368 reverse = False
1369 k, items = line.items()[0]
1370 if type(items) == dict:
1371 if items.has_key('reverse'):
1372 reverse = items['reverse']
1373 items = items['a']
1374 else:
1375 items = items['cname']
1376 items = [items] if type(items) != list else items
1377 for item in items:
1378 if item.startswith('IN '):
1379 wleiden_raw[k] = item
1380 elif valid_addr(item):
1381 wleiden_zone[k].append((item, reverse))
1382 else:
1383 wleiden_cname[k] = item
1384
1385 # Hack to get dynamic pool listing
1386 def chunks(l, n):
1387 return [l[i:i+n] for i in range(0, len(l), n)]
1388
1389 ntp_servers = [x[0] for x in get_nameservers()]
1390 for id, chunk in enumerate(chunks(ntp_servers,(len(ntp_servers)/4))):
1391 for ntp_server in chunk:
1392 wleiden_zone['%i.pool.ntp' % id].append((ntp_server, False))
1393
1394 details = dict()
1395 # 24 updates a day allowed
1396 details['serial'] = time.strftime('%Y%m%d%H')
1397
1398 if external:
1399 dns_masters = ['siteview.wirelessleiden.nl', 'ns1.vanderzwet.net']
1400 else:
1401 dns_masters = ['sunny.wleiden.net'] + ["%s.wleiden.net" % x[1] for x in get_nameservers(max_servers=3)]
1402
1403 details['master'] = dns_masters[0]
1404 details['ns_servers'] = '\n'.join(['\tNS\t%s.' % x for x in dns_masters])
1405
1406 dns_header = '''
1407$TTL 3h
1408%(zone)s. SOA %(master)s. beheer.lijst.wirelessleiden.nl. ( %(serial)s 15m 15m 1w 60s )
1409 ; Serial, Refresh, Retry, Expire, Neg. cache TTL
1410
1411%(ns_servers)s
1412 \n'''
1413
1414
1415 if not os.path.isdir(output_dir):
1416 os.makedirs(output_dir)
1417 details['zone'] = 'wleiden.net'
1418 f = open(os.path.join(output_dir,"db." + details['zone']), "w")
1419 f.write(dns_header % details)
1420
1421 for host,items in wleiden_zone.iteritems():
1422 for ip,reverse in items:
1423 if ip not in ['0.0.0.0']:
1424 f.write("%s.wleiden.net. IN A %s \n" % (host.lower(), ip))
1425 for source,dest in wleiden_cname.iteritems():
1426 dest = dest if dest.endswith('.') else dest + ".wleiden.net."
1427 f.write("%s.wleiden.net. IN CNAME %s\n" % (source.lower(), dest.lower()))
1428 for source, dest in wleiden_raw.iteritems():
1429 f.write("%s.wleiden.net. %s\n" % (source, dest))
1430 f.close()
1431
1432 # Create whole bunch of specific sub arpa zones. To keep it compliant
1433 for s in range(16,32):
1434 details['zone'] = '%i.172.in-addr.arpa' % s
1435 f = open(os.path.join(output_dir,"db." + details['zone']), "w")
1436 f.write(dns_header % details)
1437
1438 #XXX: Not effient, fix to proper data structure and do checks at other
1439 # stages
1440 for host,items in wleiden_zone.iteritems():
1441 for ip,reverse in items:
1442 if not reverse:
1443 continue
1444 if valid_addr(ip):
1445 if valid_addr(ip):
1446 if int(ip.split('.')[1]) == s:
1447 rev_ip = '.'.join(reversed(ip.split('.')))
1448 f.write("%s.in-addr.arpa. IN PTR %s.wleiden.net.\n" % (rev_ip.lower(), host.lower()))
1449 f.close()
1450
1451
1452def usage():
1453 print """Usage: %(prog)s <argument>
1454Argument:
1455\tstandalone [port] = Run configurator webserver [8000]
1456\tdns [outputdir] = Generate BIND compliant zone files in dns [./dns]
1457\tnagios-export [--heavy-load] = Generate basic nagios configuration file.
1458\tfull-export = Generate yaml export script for heatmap.
1459\tstatic [outputdir] = Generate all config files and store on disk
1460\t with format ./<outputdir>/%%NODE%%/%%FILE%% [./static]
1461\ttest <node> [<file>] = Receive output for certain node [all files].
1462\ttest-cgi <node> <file> = Receive output of CGI script [all files].
1463\tlist <status> <items> = List systems which have certain status
1464
1465Arguments:
1466\t<node> = NodeName (example: HybridRick)
1467\t<file> = %(files)s
1468\t<status> = all|up|down|planned
1469\t<items> = systems|nodes|proxies
1470
1471NOTE FOR DEVELOPERS; you can test your changes like this:
1472 BEFORE any changes in this code:
1473 $ ./gformat.py static /tmp/pre
1474 AFTER the changes:
1475 $ ./gformat.py static /tmp/post
1476 VIEW differences and VERIFY all are OK:
1477 $ diff -urI 'Generated' -r /tmp/pre /tmp/post
1478""" % { 'prog' : sys.argv[0], 'files' : '|'.join(files) }
1479 exit(0)
1480
1481
1482def is_text_request(environ=os.environ):
1483 """ Find out whether we are calling from the CLI or any text based CLI utility """
1484 try:
1485 return environ['HTTP_USER_AGENT'].split()[0] in ['curl', 'fetch', 'wget']
1486 except KeyError:
1487 return True
1488
1489def switchFormat(setting):
1490 if setting:
1491 return "YES"
1492 else:
1493 return "NO"
1494
1495def rlinput(prompt, prefill=''):
1496 import readline
1497 readline.set_startup_hook(lambda: readline.insert_text(prefill))
1498 try:
1499 return raw_input(prompt)
1500 finally:
1501 readline.set_startup_hook()
1502
1503def fix_conflict(left, right, default='i'):
1504 while True:
1505 print "## %-30s | %-30s" % (left, right)
1506 c = raw_input("## Solve Conflict (h for help) <l|r|e|i|> [%s]: " % default)
1507 if not c:
1508 c = default
1509
1510 if c in ['l','1']:
1511 return left
1512 elif c in ['r','2']:
1513 return right
1514 elif c in ['e', '3']:
1515 return rlinput("Edit: ", "%30s | %30s" % (left, right))
1516 elif c in ['i', '4']:
1517 return None
1518 else:
1519 print "#ERROR: '%s' is invalid input (left, right, edit or ignore)!" % c
1520
1521
1522
1523def print_cgi_response(response_headers, output):
1524 """Could we not use some kind of wsgi wrapper to make this output?"""
1525 for header in response_headers:
1526 print "%s: %s" % header
1527 print
1528 print output
1529
1530
1531def fill_cache():
1532 ''' Poor man re-loading of few cache items (the slow ones) '''
1533 for host in get_hostlist():
1534 get_yaml(host)
1535
1536
1537def reload_cache():
1538 clear_cache()
1539 fill_cache()
1540
1541
1542def main():
1543 """Hard working sub"""
1544 # Allow easy hacking using the CLI
1545 if not os.environ.has_key('PATH_INFO'):
1546 if len(sys.argv) < 2:
1547 usage()
1548
1549 if sys.argv[1] == "standalone":
1550 import SocketServer
1551 import CGIHTTPServer
1552 # Hop to the right working directory.
1553 os.chdir(os.path.dirname(__file__))
1554 try:
1555 PORT = int(sys.argv[2])
1556 except (IndexError,ValueError):
1557 PORT = 8000
1558
1559 class MyCGIHTTPRequestHandler(CGIHTTPServer.CGIHTTPRequestHandler):
1560 """ Serve this CGI from the root of the webserver """
1561 def is_cgi(self):
1562 if "favicon" in self.path:
1563 return False
1564
1565 self.cgi_info = (os.path.basename(__file__), self.path)
1566 self.path = ''
1567 return True
1568 handler = MyCGIHTTPRequestHandler
1569 SocketServer.TCPServer.allow_reuse_address = True
1570 httpd = SocketServer.TCPServer(("", PORT), handler)
1571 httpd.server_name = 'localhost'
1572 httpd.server_port = PORT
1573
1574 logger.info("serving at port %s", PORT)
1575 try:
1576 httpd.serve_forever()
1577 except KeyboardInterrupt:
1578 httpd.shutdown()
1579 logger.info("All done goodbye")
1580 elif sys.argv[1] == "test":
1581 # Basic argument validation
1582 try:
1583 node = sys.argv[2]
1584 datadump = get_yaml(node)
1585 except IndexError:
1586 print "Invalid argument"
1587 exit(1)
1588 except IOError as e:
1589 print e
1590 exit(1)
1591
1592
1593 # Get files to generate
1594 gen_files = sys.argv[3:] if len(sys.argv) > 3 else files
1595
1596 # Actual config generation
1597 for config in gen_files:
1598 logger.info("## Generating %s %s", node, config)
1599 print generate_config(node, config, datadump)
1600 elif sys.argv[1] == "test-cgi":
1601 os.environ['PATH_INFO'] = "/".join(sys.argv[2:])
1602 os.environ['SCRIPT_NAME'] = __file__
1603 response_headers, output = process_cgi_request()
1604 print_cgi_response(response_headers, output)
1605 elif sys.argv[1] == "static":
1606 items = dict()
1607 items['output_dir'] = sys.argv[2] if len(sys.argv) > 2 else "./static"
1608 for node in get_hostlist():
1609 items['node'] = node
1610 items['wdir'] = "%(output_dir)s/%(node)s" % items
1611 if not os.path.isdir(items['wdir']):
1612 os.makedirs(items['wdir'])
1613 datadump = get_yaml(node)
1614 for config in files:
1615 items['config'] = config
1616 logger.info("## Generating %(node)s %(config)s" % items)
1617 f = open("%(wdir)s/%(config)s" % items, "w")
1618 f.write(generate_config(node, config, datadump))
1619 f.close()
1620 elif sys.argv[1] == "wind-export":
1621 items = dict()
1622 for node in get_hostlist():
1623 datadump = get_yaml(node)
1624 sql = """INSERT IGNORE INTO nodes (name, name_ns, longitude, latitude)
1625 VALUES ('%(nodename)s', '%(nodename)s', %(latitude)s, %(longitude)s);""" % datadump;
1626 sql = """INSERT IGNORE INTO users_nodes (user_id, node_id, owner)
1627 VALUES (
1628 (SELECT id FROM users WHERE username = 'rvdzwet'),
1629 (SELECT id FROM nodes WHERE name = '%(nodename)s'),
1630 'Y');""" % datadump
1631 #for config in files:
1632 # items['config'] = config
1633 # print "## Generating %(node)s %(config)s" % items
1634 # f = open("%(wdir)s/%(config)s" % items, "w")
1635 # f.write(generate_config(node, config, datadump))
1636 # f.close()
1637 for node in get_hostlist():
1638 datadump = get_yaml(node)
1639 for iface_key in sorted([elem for elem in datadump.keys() if elem.startswith('iface_')]):
1640 ifacedump = datadump[iface_key]
1641 if ifacedump.has_key('mode') and ifacedump['mode'] == 'ap-wds':
1642 ifacedump['nodename'] = datadump['nodename']
1643 if not ifacedump.has_key('channel') or not ifacedump['channel']:
1644 ifacedump['channel'] = 0
1645 sql = """INSERT INTO links (node_id, type, ssid, protocol, channel, status)
1646 VALUES ((SELECT id FROM nodes WHERE name = '%(nodename)s'), 'ap',
1647 '%(ssid)s', 'IEEE 802.11b', %(channel)s, 'active');""" % ifacedump
1648 elif sys.argv[1] == "nagios-export":
1649 try:
1650 heavy_load = (sys.argv[2] == "--heavy-load")
1651 except IndexError:
1652 heavy_load = False
1653
1654 hostgroup_details = {
1655 'wleiden' : 'Stichting Wireless Leiden - FreeBSD Nodes',
1656 'wzoeterwoude' : 'Stichting Wireless Leiden - Afdeling Zoeterwoude - Free-WiFi Project',
1657 'walphen' : 'Stichting Wireless Alphen',
1658 'westeinder' : 'WestEinder Plassen',
1659 }
1660
1661 params = {
1662 'check_interval' : 5 if heavy_load else 60,
1663 'retry_interval' : 1 if heavy_load else 5,
1664 'max_check_attempts' : 10 if heavy_load else 3,
1665 }
1666
1667 print '''\
1668define host {
1669 name wleiden-node ; Default Node Template
1670 use generic-host ; Use the standard template as initial starting point
1671 check_period 24x7 ; By default, FreeBSD hosts are checked round the clock
1672 check_interval %(check_interval)s ; Actively check the host every 5 minutes
1673 retry_interval %(retry_interval)s ; Schedule host check retries at 1 minute intervals
1674 max_check_attempts %(max_check_attempts)s ; Check each FreeBSD host 10 times (max)
1675 check_command check-host-alive ; Default command to check FreeBSD hosts
1676 register 0 ; DONT REGISTER THIS DEFINITION - ITS NOT A REAL HOST, JUST A TEMPLATE!
1677}
1678
1679define service {
1680 name wleiden-service ; Default Service Template
1681 use generic-service ; Use the standard template as initial starting point
1682 check_period 24x7 ; By default, FreeBSD hosts are checked round the clock
1683 check_interval %(check_interval)s ; Actively check the host every 5 minutes
1684 retry_interval %(retry_interval)s ; Schedule host check retries at 1 minute intervals
1685 max_check_attempts %(max_check_attempts)s ; Check each FreeBSD host 10 times (max)
1686 register 0 ; DONT REGISTER THIS DEFINITION - ITS NOT A REAL HOST, JUST A TEMPLATE!
1687}
1688
1689# Please make sure to install:
1690# make -C /usr/ports/net-mgmt/nagios-check_netsnmp install clean
1691#
1692define command{
1693 command_name check_netsnmp_disk
1694 command_line $USER1$/check_netsnmp -H $HOSTADDRESS$ -o disk
1695}
1696
1697define command{
1698 command_name check_netsnmp_load
1699 command_line $USER1$/check_netsnmp -H $HOSTADDRESS$ -o load
1700}
1701
1702define command{
1703 command_name check_netsnmp_proc
1704 command_line $USER1$/check_netsnmp -H $HOSTADDRESS$ -o proc
1705}
1706
1707# TDB: dhcp leases
1708# /usr/local/libexec/nagios/check_netsnmp -H 192.168.178.47 --oid 1 exec
1709
1710# TDB: internet status
1711# /usr/local/libexec/nagios/check_netsnmp -H 192.168.178.47 --oid 1 file
1712
1713# TDB: Advanced local passive checks
1714# /usr/local/libexec/nagios/check_by_ssh
1715''' % params
1716
1717 print '''\
1718# Service Group, not displayed by default
1719define hostgroup {
1720 hostgroup_name srv_hybrid
1721 alias All Hybrid Nodes
1722 register 0
1723}
1724
1725define service {
1726 use wleiden-service
1727 hostgroup_name srv_hybrid
1728 service_description SSH
1729 check_command check_ssh
1730}
1731
1732define service {
1733 use wleiden-service
1734 hostgroup_name srv_hybrid
1735 service_description HTTP
1736 check_command check_http
1737}
1738
1739# Little bit broken from standard install
1740#define service {
1741# use wleiden-service
1742# hostgroup_name srv_hybrid
1743# service_description DNS
1744# check_command check_dns
1745#}
1746
1747# TDB: Can only test this if we have the proxy listening to all addresses.
1748# define service {
1749# use wleiden-service
1750# hostgroup_name srv_hybrid
1751# service_description PROXY
1752# check_command check_tcp!3128
1753# }
1754'''
1755
1756 if heavy_load:
1757 print '''\
1758define service {
1759 use wleiden-service
1760 hostgroup_name srv_hybrid
1761 service_description SNMP
1762 check_command check_snmp
1763}
1764
1765define service {
1766 use wleiden-service
1767 hostgroup_name srv_hybrid
1768 service_description NTP
1769 check_command check_ntp_peer
1770}
1771
1772define service {
1773 use wleiden-service
1774 hostgroup_name srv_hybrid
1775 service_description LOAD
1776 check_command check_netsnmp_load
1777}
1778
1779define service {
1780 use wleiden-service
1781 hostgroup_name srv_hybrid
1782 service_description PROC
1783 check_command check_netsnmp_proc
1784}
1785
1786define service {
1787 use wleiden-service
1788 hostgroup_name srv_hybrid
1789 service_description DISK
1790 check_command check_netsnmp_disk
1791}
1792'''
1793 for node in get_hostlist():
1794 datadump = get_yaml(node)
1795 if not datadump['status'] == 'up':
1796 continue
1797 if not hostgroup_details.has_key(datadump['monitoring_group']):
1798 hostgroup_details[datadump['monitoring_group']] = datadump['monitoring_group']
1799 print '''\
1800define host {
1801 use wleiden-node
1802 host_name %(autogen_fqdn)s
1803 address %(masterip)s
1804 hostgroups srv_hybrid,%(monitoring_group)s
1805}
1806''' % datadump
1807
1808 for name,alias in hostgroup_details.iteritems():
1809 print '''\
1810define hostgroup {
1811 hostgroup_name %s
1812 alias %s
1813} ''' % (name, alias)
1814
1815
1816 elif sys.argv[1] == "full-export":
1817 hosts = {}
1818 for node in get_hostlist():
1819 datadump = get_yaml(node)
1820 hosts[datadump['nodename']] = datadump
1821 print yaml.dump(hosts)
1822
1823 elif sys.argv[1] == "dns":
1824 make_dns(sys.argv[2] if len(sys.argv) > 2 else 'dns', 'external' in sys.argv)
1825 elif sys.argv[1] == "cleanup":
1826 # First generate all datadumps
1827 datadumps = dict()
1828 ssid_to_node = dict()
1829 for host in get_hostlist():
1830 logger.info("# Processing: %s", host)
1831 # Set some boring default values
1832 datadump = { 'board' : 'UNKNOWN' }
1833 datadump.update(get_yaml(host))
1834 datadumps[datadump['autogen_realname']] = datadump
1835
1836 (poel, errors) = make_relations(datadumps)
1837 print "\n".join(["# WARNING: %s" % x for x in errors])
1838
1839 for host,datadump in datadumps.iteritems():
1840 try:
1841 # Convert all yes and no to boolean values
1842 def fix_boolean(dump):
1843 for key in dump.keys():
1844 if type(dump[key]) == dict:
1845 dump[key] = fix_boolean(dump[key])
1846 elif str(dump[key]).lower() in ["yes", "true"]:
1847 dump[key] = True
1848 elif str(dump[key]).lower() in ["no", "false"]:
1849 # Compass richting no (Noord Oost) is valid input
1850 if key != "compass": dump[key] = False
1851 return dump
1852 datadump = fix_boolean(datadump)
1853
1854 if datadump['rdnap_x'] and datadump['rdnap_y']:
1855 datadump['latitude'], datadump['longitude'] = map(lambda x: "%.5f" % x, rd2etrs(datadump['rdnap_x'], datadump['rdnap_y']))
1856 elif datadump['latitude'] and datadump['longitude']:
1857 datadump['rdnap_x'], datadump['rdnap_y'] = etrs2rd(datadump['latitude'], datadump['longitude'])
1858
1859 if datadump['nodename'].startswith('Proxy'):
1860 datadump['nodename'] = datadump['nodename'].lower()
1861
1862 for iface_key in datadump['autogen_iface_keys']:
1863 try:
1864 # All our normal wireless cards are normal APs now
1865 if datadump[iface_key]['type'] in ['11a', '11b', '11g', 'wireless']:
1866 datadump[iface_key]['mode'] = 'ap'
1867 # Wireless Leiden SSID have an consistent lowercase/uppercase
1868 if datadump[iface_key].has_key('ssid'):
1869 ssid = datadump[iface_key]['ssid']
1870 prefix = 'ap-WirelessLeiden-'
1871 if ssid.lower().startswith(prefix.lower()):
1872 datadump[iface_key]['ssid'] = prefix + ssid[len(prefix)].upper() + ssid[len(prefix) + 1:]
1873 if datadump[iface_key].has_key('ns_ip') and not datadump[iface_key].has_key('mode'):
1874 datadump[iface_key]['mode'] = 'autogen-FIXME'
1875 if not datadump[iface_key].has_key('comment'):
1876 datadump[iface_key]['comment'] = 'autogen-FIXME'
1877
1878 if datadump[iface_key].has_key('ns_mac'):
1879 datadump[iface_key]['ns_mac'] = datadump[iface_key]['ns_mac'].lower()
1880
1881 if datadump[iface_key]['comment'].startswith('autogen-') and datadump[iface_key].has_key('comment'):
1882 datadump[iface_key] = datadump[iface_key]['desc']
1883
1884 # We are not using 802.11b anymore. OFDM is preferred over DSSS
1885 # due to better collision avoidance.
1886 if datadump[iface_key]['type'] == '11b':
1887 datadump[iface_key]['type'] = '11g'
1888
1889 # Setting 802.11g channels to de-facto standards, to avoid
1890 # un-detected sharing with other overlapping channels
1891 #
1892 # Technically we could also use channel 13 in NL, but this is not
1893 # recommended as foreign devices might not be able to select this
1894 # channel. Secondly using 1,5,9,13 instead is going to clash with
1895 # the de-facto usage of 1,6,11.
1896 #
1897 # See: https://en.wikipedia.org/wiki/List_of_WLAN_channels
1898 channels_at_2400Mhz = (1,6,11)
1899 if datadump[iface_key]['type'] == '11g' and datadump[iface_key].has_key('channel'):
1900 datadump[iface_key]['channel'] = int(datadump[iface_key]['channel'])
1901 if datadump[iface_key]['channel'] not in channels_at_2400Mhz:
1902 datadump[iface_key]['channel'] = random.choice(channels_at_2400Mhz)
1903
1904 # Mandatory interface keys
1905 if not datadump[iface_key].has_key('status'):
1906 datadump[iface_key]['status'] = 'planned'
1907
1908 x = datadump[iface_key]['comment']
1909 datadump[iface_key]['comment'] = x[0].upper() + x[1:]
1910
1911 # Fixing bridge_type if none is found
1912 if datadump[iface_key].get('extra_type', '') == 'eth2wifibridge':
1913 if not 'bridge_type' in datadump[iface_key]:
1914 datadump[iface_key]['bridge_type'] = 'NanoStation M5'
1915
1916 # Making sure description works
1917 if datadump[iface_key].has_key('desc'):
1918 if datadump[iface_key]['comment'].lower() == datadump[iface_key]['desc'].lower():
1919 del datadump[iface_key]['desc']
1920 else:
1921 print "# ERROR: At %s - %s" % (datadump['nodename'], iface_key)
1922 response = fix_conflict(datadump[iface_key]['comment'], datadump[iface_key]['desc'])
1923 if response:
1924 datadump[iface_key]['comment'] = response
1925 del datadump[iface_key]['desc']
1926
1927 # Check DHCP configuration
1928 dhcp_type(datadump[iface_key])
1929
1930 # Set the compass value based on the angle between the poels
1931 if datadump[iface_key].has_key('ns_ip'):
1932 my_pool = poel[network(datadump[iface_key]['ip'])]
1933 remote_hosts = list(set([x[0] for x in my_pool]) - set([host]))
1934 if remote_hosts:
1935 compass_target = remote_hosts[0]
1936 datadump[iface_key]['compass'] = cd_between_hosts(host, compass_target, datadumps)
1937
1938 # Monitoring Group default
1939 if not 'monitoring_group' in datadump:
1940 datadump['monitoring_group'] = 'wleiden'
1941
1942 except Exception as e:
1943 print "# Error while processing interface %s" % iface_key
1944 raise
1945 store_yaml(datadump)
1946 except Exception as e:
1947 print "# Error while processing %s" % host
1948 raise
1949 elif sys.argv[1] == "list":
1950 use_fqdn = False
1951 if len(sys.argv) < 4 or not sys.argv[2] in ["up", "down", "planned", "all"]:
1952 usage()
1953 if sys.argv[3] == "nodes":
1954 systems = get_nodelist()
1955 elif sys.argv[3] == "proxies":
1956 systems = get_proxylist()
1957 elif sys.argv[3] == "systems":
1958 systems = get_hostlist()
1959 else:
1960 usage()
1961 if len(sys.argv) > 4:
1962 if sys.argv[4] == "fqdn":
1963 use_fqdn = True
1964 else:
1965 usage()
1966
1967 for system in systems:
1968 datadump = get_yaml(system)
1969
1970 output = datadump['autogen_fqdn'] if use_fqdn else system
1971 if sys.argv[2] == "all":
1972 print output
1973 elif datadump['status'] == sys.argv[2]:
1974 print output
1975 elif sys.argv[1] == "create":
1976 if sys.argv[2] == "network.kml":
1977 print make_network_kml.make_graph()
1978 elif sys.argv[2] == "host-ips.txt":
1979 for system in get_hostlist():
1980 datadump = get_yaml(system)
1981 ips = [datadump['masterip']]
1982 for ifkey in datadump['autogen_iface_keys']:
1983 ips.append(datadump[ifkey]['ip'].split('/')[0])
1984 print system, ' '.join(ips)
1985 elif sys.argv[2] == "host-pos.txt":
1986 for system in get_hostlist():
1987 datadump = get_yaml(system)
1988 print system, datadump['rdnap_x'], datadump['rdnap_y']
1989 elif sys.argv[2] == 'ssh_config':
1990 print '''
1991Host *.wleiden.net
1992 User root
1993
1994Host 172.16.*.*
1995 User root
1996'''
1997 for system in get_hostlist():
1998 datadump = get_yaml(system)
1999 print '''\
2000Host %s
2001 User root
2002
2003Host %s
2004 User root
2005
2006Host %s
2007 User root
2008
2009Host %s
2010 User root
2011''' % (system, system.lower(), datadump['nodename'], datadump['nodename'].lower())
2012 else:
2013 usage()
2014 else:
2015 usage()
2016 else:
2017 # Do not enable debugging for config requests as it highly clutters the output
2018 if not is_text_request():
2019 cgitb.enable()
2020 response_headers, output = process_cgi_request()
2021 print_cgi_response(response_headers, output)
2022
2023def application(environ, start_response):
2024 status = '200 OK'
2025 response_headers, output = process_cgi_request(environ)
2026 start_response(status, response_headers)
2027
2028 # Debugging only
2029 # output = 'wsgi.multithread = %s' % repr(environ['wsgi.multithread'])
2030 # soutput += '\nwsgi.multiprocess = %s' % repr(environ['wsgi.multiprocess'])
2031 return [output]
2032
2033if __name__ == "__main__":
2034 main()
Note: See TracBrowser for help on using the repository browser.