source: genesis/tools/gformat.py@ 11538

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

Magical concentrator 'trick'

Def concentrator: Route all traffic to VPN concentrator on the internet to
'secure' the sponsored internet connection from over active spam/virus
controller messages and actions.

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