source: genesis/tools/gformat.py@ 11535

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

Damm dry-coding, time to go to sleep I guess.

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