source: genesis/tools/gformat.py@ 12441

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

Workaround quick for different version of notation

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