source: genesis/tools/gformat.py@ 11533

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

Make cache re-loading penalty part of update process, this will avoid timeouts at later stages.

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