source: genesis/tools/gformat.py@ 12247

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

Making sure all iLeiden proxies will have lvrouted -g flag configured any time
soon. This allows smooth transition to new lvrouted iLeiden default route
management.

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