source: genesis/tools/gformat.py@ 11503

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

Now with proper caching and shared memory.

  • Property svn:executable set to *
  • Property svn:keywords set to Id
File size: 62.5 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 11503 2012-09-26 20:28:04Z 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
126
127NO_DHCP = 0
128DHCP_CLIENT = 10
129DHCP_SERVER = 20
130def dhcp_type(item):
131 if not item.has_key('dhcp'):
132 return NO_DHCP
133 elif not item['dhcp']:
134 return NO_DHCP
135 elif item['dhcp'].lower() == 'client':
136 return DHCP_CLIENT
137 else:
138 # Validation Checks
139 begin,end = map(int,item['dhcp'].split('-'))
140 if begin >= end:
141 raise ValueError("DHCP Start >= DHCP End")
142 return DHCP_SERVER
143
144
145
146def get_yaml(item,add_version_info=True):
147 try:
148 """ Get configuration yaml for 'item'"""
149 if datadump_cache.has_key(item):
150 return datadump_cache[item].copy()
151
152 gfile = os.path.join(NODE_DIR,item,'wleiden.yaml')
153
154 # Default values
155 datadump = {
156 'autogen_revision' : 'NOTFOUND',
157 'autogen_gfile' : gfile,
158 }
159 f = open(gfile, 'r')
160 datadump.update(yaml.load(f,Loader=Loader))
161 if datadump['nodetype'] == 'Hybrid':
162 # Some values are defined implicitly
163 if datadump.has_key('rdr_rules') and datadump['rdr_rules'] and not datadump.has_key('service_incoming_rdr'):
164 datadump['service_incoming_rdr'] = True
165 # Use some boring defaults
166 defaults = {
167 'service_proxy_normal' : False,
168 'service_proxy_ileiden' : False,
169 'service_accesspoint' : True,
170 'service_incoming_rdr' : 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 #
732
733 {% if service_proxy_ileiden %}
734 pf_rules="/etc/pf.hybrid.conf"
735 pf_flags="-D ext_if=$externalif -D ext_if_net=$externalif:network -D masterip=$masterip"
736 pf_flags="$pf_flags -D publicnat=80,443"
737 {% elif service_proxy_normal or service_incoming_rdr %}
738 pf_rules="/etc/pf.hybrid.conf"
739 pf_flags="-D ext_if=$externalif -D ext_if_net=$externalif:network -D masterip=$masterip"
740 pf_flags="$pf_flags -D publicnat=0"
741 lvrouted_flags="$lvrouted_flags -z `make_list "$list_ileiden_proxies" ","`"
742 named_setfib="1"
743 tinyproxy_setfib="1"
744 dnsmasq_setfib="1"
745 sshd_setfib="1"
746 {% else %}
747 named_auto_forward_only="YES"
748 pf_rules="/etc/pf.node.conf"
749 pf_flags=""
750 lvrouted_flags="$lvrouted_flags -z `make_list "$list_ileiden_proxies" ","`"
751 {% endif %}
752
753 {% if service_proxy_normal %}
754 tinyproxy_enable="yes"
755 {% else %}
756 pen_wrapper_enable="yes"
757 {% endif %}
758
759 {% if service_accesspoint %}
760 pf_flags="$pf_flags -D captive_portal_interfaces=$captive_portal_interfaces"
761 {% endif %}
762
763 {% if board == "ALIX2" %}
764 #
765 # ''Fat'' configuration, board has 256MB RAM
766 #
767 dnsmasq_enable="NO"
768 named_enable="YES"
769 {% if autogen_dhcp_interfaces -%}
770 dhcpd_enable="YES"
771 dhcpd_flags="$dhcpd_flags {{ autogen_dhcp_interfaces|join(' ') }}"
772 {% endif -%}
773 {% endif -%}
774
775 {% if gateway %}
776 defaultrouter="{{ gateway }}"
777 {% endif %}
778{% elif nodetype == "CNode" %}
779#
780# NODE iLeiden Configuration
781#
782
783# iLeiden Proxies {{ autogen_ileiden_proxies_names }}
784list_ileiden_proxies="{{ autogen_ileiden_proxies_ips }}"
785# normal Proxies {{ autogen_normal_proxies_names }}
786list_normal_proxies="{{ autogen_normal_proxies_ips }}"
787
788captive_portal_interfaces="{{ autogen_dhcp_interfaces|join(',') }}"
789
790lvrouted_flags="-u -s s00p3rs3kr3t -m 28 -z $list_ileiden_proxies"
791{% endif %}
792
793#
794# Interface definitions
795#\n
796""")
797
798 (addrs_list, dhclient_if, extra_ouput) = make_interface_list(datadump)
799 output += extra_ouput
800
801 # Print IP address which needs to be assigned over here
802 output += "\n"
803 for iface,addrs in sorted(addrs_list.iteritems()):
804 for addr, comment in sorted(addrs,key=lambda x: parseaddr(x[0].split('/')[0])):
805 output += "# %s || %s || %s\n" % (iface, addr, comment)
806
807 # Write DHCLIENT entry
808 if dhclient_if[iface]:
809 output += "ifconfig_%s='SYNCDHCP'\n\n" % (iface)
810 else:
811 # Make sure the external address is always first as this is needed in the
812 # firewall setup
813 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))
814 output += "ipv4_addrs_%s='%s'\n\n" % (iface, " ".join([x[0] for x in addrs]))
815
816 rc_conf_local_cache[datadump['autogen_item']] = output
817 return output
818
819
820
821
822def get_all_configs():
823 """ Get dict with key 'host' with all configs present """
824 configs = dict()
825 for host in get_hostlist():
826 datadump = get_yaml(host)
827 configs[host] = datadump
828 return configs
829
830
831def get_interface_keys(config):
832 """ Quick hack to get all interface keys, later stage convert this to a iterator """
833 return sorted([elem for elem in config.keys() if (elem.startswith('iface_') and not "lo0" in elem)])
834
835
836def get_used_ips(configs):
837 """ Return array of all IPs used in config files"""
838 ip_list = []
839 for config in configs:
840 ip_list.append(config['masterip'])
841 for iface_key in get_interface_keys(config):
842 l = config[iface_key]['ip']
843 addr, mask = l.split('/')
844 # Special case do not process
845 if valid_addr(addr):
846 ip_list.append(addr)
847 else:
848 logger.error("## IP '%s' in '%s' not valid" % (addr, config['nodename']))
849 return sorted(ip_list)
850
851
852
853def get_nameservers(max_servers=None):
854 if nameservers_cache:
855 return nameservers_cache[0:max_servers]
856
857 for host in get_hybridlist():
858 hostdump = get_yaml(host)
859 if hostdump['status'] == 'up' and (hostdump['service_proxy_ileiden'] or hostdump['service_proxy_normal']):
860 nameservers_cache.append((hostdump['masterip'], hostdump['autogen_realname']))
861 for host in get_proxylist():
862 hostdump = get_yaml(host)
863 if hostdump['status'] == 'up':
864 nameservers_cache.append((hostdump['masterip'], hostdump['autogen_realname']))
865
866 return nameservers_cache[0:max_servers]
867
868
869def generate_resolv_conf(datadump):
870 """ Generate configuration file '/etc/resolv.conf' """
871 # XXX: This should properly going to be an datastructure soon
872 datadump['autogen_header'] = generate_header(datadump, "#")
873 datadump['autogen_edge_nameservers'] = ''
874
875
876 for masterip,realname in get_nameservers():
877 datadump['autogen_edge_nameservers'] += "nameserver %-15s # %s\n" % (masterip, realname)
878
879 return Template("""\
880{{ autogen_header }}
881search wleiden.net
882
883# Try local (cache) first
884nameserver 127.0.0.1
885
886{% if service_proxy_normal or service_proxy_ileiden or nodetype == 'Proxy' -%}
887nameserver 8.8.8.8 # Google Public NameServer
888nameserver 8.8.4.4 # Google Public NameServer
889{% else -%}
890# START DYNAMIC LIST - updated by /tools/nameserver-shuffle
891{{ autogen_edge_nameservers }}
892{% endif -%}
893""").render(datadump)
894
895
896
897def generate_ntp_conf(datadump):
898 """ Generate configuration file '/etc/ntp.conf' """
899 # XXX: This should properly going to be an datastructure soon
900
901 datadump['autogen_header'] = generate_header(datadump, "#")
902 datadump['autogen_ntp_servers'] = ''
903 for host in get_proxylist():
904 hostdump = get_yaml(host)
905 datadump['autogen_ntp_servers'] += "server %(masterip)-15s iburst maxpoll 9 # %(autogen_realname)s\n" % hostdump
906 for host in get_hybridlist():
907 hostdump = get_yaml(host)
908 if hostdump['service_proxy_ileiden'] or hostdump['service_proxy_normal']:
909 datadump['autogen_ntp_servers'] += "server %(masterip)-15s iburst maxpoll 9 # %(autogen_realname)s\n" % hostdump
910
911 return Template("""\
912{{ autogen_header }}
913
914{% if service_proxy_normal or service_proxy_ileiden or nodetype == 'Proxy' -%}
915# Machine hooked to internet.
916server 0.nl.pool.ntp.org iburst maxpoll 9
917server 1.nl.pool.ntp.org iburst maxpoll 9
918server 2.nl.pool.ntp.org iburst maxpoll 9
919server 3.nl.pool.ntp.org iburst maxpoll 9
920{% else -%}
921# Local Wireless Leiden NTP Servers.
922server 0.pool.ntp.wleiden.net iburst maxpoll 9
923server 1.pool.ntp.wleiden.net iburst maxpoll 9
924server 2.pool.ntp.wleiden.net iburst maxpoll 9
925server 3.pool.ntp.wleiden.net iburst maxpoll 9
926
927# All the configured NTP servers
928{{ autogen_ntp_servers }}
929{% endif %}
930
931# If a server loses sync with all upstream servers, NTP clients
932# no longer follow that server. The local clock can be configured
933# to provide a time source when this happens, but it should usually
934# be configured on just one server on a network. For more details see
935# http://support.ntp.org/bin/view/Support/UndisciplinedLocalClock
936# The use of Orphan Mode may be preferable.
937#
938server 127.127.1.0
939fudge 127.127.1.0 stratum 10
940""").render(datadump)
941
942
943def generate_pf_hybrid_conf_local(datadump):
944 """ Generate configuration file '/etc/pf.hybrid.conf.local' """
945 datadump['autogen_header'] = generate_header(datadump, "#")
946 return Template("""\
947{{ autogen_header }}
948
949# Redirect some internal facing services outside (7)
950# INFO: {{ rdr_rules|count }} rdr_rules (outside to internal redirect rules) defined.
951{% for protocol, src_port,dest_ip,dest_port in rdr_rules -%}
952rdr on $ext_if inet proto {{ protocol }} from any to $ext_if port {{ src_port }} tag SRV -> {{ dest_ip }} port {{ dest_port }}
953{% endfor -%}
954""").render(datadump)
955
956def generate_motd(datadump):
957 """ Generate configuration file '/etc/motd' """
958 output = Template("""\
959FreeBSD run ``service motd onestart'' to make me look normal
960
961 WWW: {{ autogen_fqdn }} - http://www.wirelessleiden.nl
962 Loc: {{ location }}
963
964Services:
965{% if board == "ALIX2" -%}
966{{" -"}} Core Node ({{ board }})
967{% else -%}
968{{" -"}} Hulp Node ({{ board }})
969{% endif -%}
970{% if service_proxy_normal -%}
971{{" -"}} Normal Proxy
972{% endif -%}
973{% if service_proxy_ileiden -%}
974{{" -"}} iLeiden Proxy
975{% endif -%}
976{% if service_incoming_rdr -%}
977{{" -"}} Incoming port redirects
978{% endif %}
979Interlinks:\n
980""").render(datadump)
981
982 (addrs_list, dhclient_if, extra_ouput) = make_interface_list(datadump)
983 # Just nasty hack to make the formatting looks nice
984 iface_len = max(map(len,addrs_list.keys()))
985 addr_len = max(map(len,[x[0] for x in [x[0] for x in addrs_list.values()]]))
986 for iface,addrs in sorted(addrs_list.iteritems()):
987 if iface in ['lo0']:
988 continue
989 for addr, comment in sorted(addrs,key=lambda x: parseaddr(x[0].split('/')[0])):
990 output += " - %s || %s || %s\n" % (iface.ljust(iface_len), addr.ljust(addr_len), comment)
991
992 output += '\n'
993 output += """\
994Attached bridges:
995"""
996 has_item = False
997 for iface_key in datadump['autogen_iface_keys']:
998 ifacedump = datadump[iface_key]
999 if ifacedump.has_key('ns_ip'):
1000 has_item = True
1001 output += " - %(autogen_ifname)s || %(mode)s || %(ns_ip)s\n" % ifacedump
1002 if not has_item:
1003 output += " - none\n"
1004
1005 return output
1006
1007
1008def format_yaml_value(value):
1009 """ Get yaml value in right syntax for outputting """
1010 if isinstance(value,str):
1011 output = '"%s"' % value
1012 else:
1013 output = value
1014 return output
1015
1016
1017
1018def format_wleiden_yaml(datadump):
1019 """ Special formatting to ensure it is editable"""
1020 output = "# Genesis config yaml style\n"
1021 output += "# vim:ts=2:et:sw=2:ai\n"
1022 output += "#\n"
1023 iface_keys = [elem for elem in datadump.keys() if elem.startswith('iface_')]
1024 for key in sorted(set(datadump.keys()) - set(iface_keys)):
1025 if key == 'rdr_rules':
1026 output += '%-10s:\n' % 'rdr_rules'
1027 for rdr_rule in datadump[key]:
1028 output += '- %s\n' % rdr_rule
1029 else:
1030 output += "%-10s: %s\n" % (key, format_yaml_value(datadump[key]))
1031
1032 output += "\n\n"
1033
1034 # Format (key, required)
1035 key_order = (
1036 ('comment', True),
1037 ('ip', True),
1038 ('desc', True),
1039 ('sdesc', True),
1040 ('mode', True),
1041 ('type', True),
1042 ('extra_type', False),
1043 ('channel', False),
1044 ('ssid', False),
1045 ('dhcp', True),
1046 ('compass', False),
1047 ('distance', False),
1048 ('ns_ip', False),
1049 ('bullet2_ip', False),
1050 ('ns_mac', False),
1051 ('bullet2_mac', False),
1052 ('ns_type', False),
1053 ('bridge_type', False),
1054 ('status', True),
1055 )
1056
1057 for iface_key in sorted(iface_keys):
1058 try:
1059 remainder = set(datadump[iface_key].keys()) - set([x[0] for x in key_order])
1060 if remainder:
1061 raise KeyError("invalid keys: %s" % remainder)
1062
1063 output += "%s:\n" % iface_key
1064 for key,required in key_order:
1065 if datadump[iface_key].has_key(key):
1066 output += " %-11s: %s\n" % (key, format_yaml_value(datadump[iface_key][key]))
1067 output += "\n\n"
1068 except Exception as e:
1069 print "# Error while processing interface %s" % iface_key
1070 raise
1071
1072 return output
1073
1074
1075
1076def generate_wleiden_yaml(datadump, header=True):
1077 """ Generate (petty) version of wleiden.yaml"""
1078 output = generate_header(datadump, "#") if header else ''
1079
1080 for key in datadump.keys():
1081 if key.startswith('autogen_'):
1082 del datadump[key]
1083 # Interface autogen cleanups
1084 elif type(datadump[key]) == dict:
1085 for key2 in datadump[key].keys():
1086 if key2.startswith('autogen_'):
1087 del datadump[key][key2]
1088
1089 output += format_wleiden_yaml(datadump)
1090 return output
1091
1092
1093def generate_yaml(datadump):
1094 return generate_config(datadump['nodename'], "wleiden.yaml", datadump)
1095
1096
1097
1098def generate_config(node, config, datadump=None):
1099 """ Print configuration file 'config' of 'node' """
1100 output = ""
1101 try:
1102 # Load config file
1103 if datadump == None:
1104 datadump = get_yaml(node)
1105
1106 if config == 'wleiden.yaml':
1107 output += generate_wleiden_yaml(datadump)
1108 elif config == 'authorized_keys':
1109 f = open(os.path.join(NODE_DIR,"global_keys"), 'r')
1110 output += f.read()
1111 f.close()
1112 elif config == 'dnsmasq.conf':
1113 output += generate_dnsmasq_conf(datadump)
1114 elif config == 'dhcpd.conf':
1115 output += generate_dhcpd_conf(datadump)
1116 elif config == 'rc.conf.local':
1117 output += generate_rc_conf_local(datadump)
1118 elif config == 'resolv.conf':
1119 output += generate_resolv_conf(datadump)
1120 elif config == 'ntp.conf':
1121 output += generate_ntp_conf(datadump)
1122 elif config == 'motd':
1123 output += generate_motd(datadump)
1124 elif config == 'pf.hybrid.conf.local':
1125 output += generate_pf_hybrid_conf_local(datadump)
1126 else:
1127 assert False, "Config not found!"
1128 except IOError, e:
1129 output += "[ERROR] Config file not found"
1130 return output
1131
1132
1133
1134def process_cgi_request(environ=os.environ):
1135 """ When calling from CGI """
1136 response_headers = []
1137 content_type = 'text/plain'
1138
1139 # Update repository if requested
1140 form = urlparse.parse_qs(environ['QUERY_STRING']) if environ.has_key('QUERY_STRING') else None
1141 if form and form.has_key("action") and "update" in form["action"]:
1142 output = "[INFO] Updating subverion, please wait...\n"
1143 output += subprocess.Popen(['svn', 'cleanup', "%s/.." % NODE_DIR], stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0]
1144 output += subprocess.Popen(['svn', 'up', "%s/.." % NODE_DIR], stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0]
1145 output += "[INFO] All done, redirecting in 5 seconds"
1146 response_headers += [
1147 ('Refresh', '5; url=.'),
1148 ]
1149 clear_cache()
1150 else:
1151 base_uri = environ['PATH_INFO']
1152 uri = base_uri.strip('/').split('/')
1153
1154 output = "Template Holder"
1155 if base_uri.endswith('/create/network.kml'):
1156 content_type='application/vnd.google-earth.kml+xml'
1157 output = make_network_kml.make_graph()
1158 elif base_uri.endswith('/api/get/nodeplanner.json'):
1159 content_type='application/json'
1160 output = make_network_kml.make_nodeplanner_json()
1161 elif not uri[0]:
1162 if is_text_request(environ):
1163 output = '\n'.join(get_hostlist())
1164 else:
1165 content_type = 'text/html'
1166 output = generate_title(get_hostlist())
1167 elif len(uri) == 1:
1168 if is_text_request(environ):
1169 output = generate_node(uri[0])
1170 else:
1171 content_type = 'text/html'
1172 output = generate_node_overview(uri[0])
1173 elif len(uri) == 2:
1174 output = generate_config(uri[0], uri[1])
1175 else:
1176 assert False, "Invalid option"
1177
1178 # Return response
1179 response_headers += [
1180 ('Content-type', content_type),
1181 ('Content-Length', str(len(output))),
1182 ]
1183 return(response_headers, str(output))
1184
1185
1186def get_realname(datadump):
1187 # Proxy naming convention is special, as the proxy name is also included in
1188 # the nodename, when it comes to the numbered proxies.
1189 if datadump['nodetype'] == 'Proxy':
1190 realname = datadump['nodetype'] + datadump['nodename'].replace('proxy','')
1191 else:
1192 # By default the full name is listed and also a shortname CNAME for easy use.
1193 realname = datadump['nodetype'] + datadump['nodename']
1194 return(realname)
1195
1196
1197
1198def make_dns(output_dir = 'dns', external = False):
1199 items = dict()
1200
1201 # hostname is key, IP is value
1202 wleiden_zone = defaultdict(list)
1203 wleiden_cname = dict()
1204
1205 pool = dict()
1206 for node in get_hostlist():
1207 datadump = get_yaml(node)
1208
1209 # Proxy naming convention is special
1210 fqdn = datadump['autogen_realname']
1211 if datadump['nodetype'] in ['CNode', 'Hybrid']:
1212 wleiden_cname[datadump['nodename']] = fqdn
1213
1214 if datadump.has_key('rdr_host'):
1215 remote_target = datadump['rdr_host']
1216 elif datadump.has_key('remote_access') and datadump['remote_access']:
1217 remote_target = datadump['remote_access'].split(':')[0]
1218 else:
1219 remote_target = None
1220
1221 if remote_target:
1222 try:
1223 parseaddr(remote_target)
1224 wleiden_zone[datadump['nodename'] + '.gw'].append((remote_target, False))
1225 except (IndexError, ValueError):
1226 wleiden_cname[datadump['nodename'] + '.gw'] = remote_target + '.'
1227
1228
1229 wleiden_zone[fqdn].append((datadump['masterip'], True))
1230
1231 # Hacking to get proper DHCP IPs and hostnames
1232 for iface_key in get_interface_keys(datadump):
1233 iface_name = iface_key.replace('_','-')
1234 (ip, cidr) = datadump[iface_key]['ip'].split('/')
1235 try:
1236 (dhcp_start, dhcp_stop) = datadump[iface_key]['dhcp'].split('-')
1237 datadump[iface_key]['autogen_netmask'] = cidr2netmask(cidr)
1238 dhcp_part = ".".join(ip.split('.')[0:3])
1239 if ip != datadump['masterip']:
1240 wleiden_zone["dhcp-gateway-%s.%s" % (iface_name, fqdn)].append((ip, False))
1241 for i in range(int(dhcp_start), int(dhcp_stop) + 1):
1242 wleiden_zone["dhcp-%s-%s.%s" % (i, iface_name, fqdn)].append(("%s.%s" % (dhcp_part, i), True))
1243 except (AttributeError, ValueError, KeyError):
1244 # First push it into a pool, to indentify the counter-part later on
1245 addr = parseaddr(ip)
1246 cidr = int(cidr)
1247 addr = addr & ~((1 << (32 - cidr)) - 1)
1248 if pool.has_key(addr):
1249 pool[addr] += [(iface_name, fqdn, ip)]
1250 else:
1251 pool[addr] = [(iface_name, fqdn, ip)]
1252 continue
1253
1254
1255
1256 # WL uses an /29 to configure an interface. IP's are ordered like this:
1257 # MasterA (.1) -- DeviceA (.2) <<>> DeviceB (.3) --- SlaveB (.4)
1258
1259 sn = lambda x: re.sub(r'(?i)^cnode','',x)
1260
1261 # Automatic naming convention of interlinks namely 2 + remote.lower()
1262 for (key,value) in pool.iteritems():
1263 # Make sure they are sorted from low-ip to high-ip
1264 value = sorted(value, key=lambda x: parseaddr(x[2]))
1265
1266 if len(value) == 1:
1267 (iface_name, fqdn, ip) = value[0]
1268 wleiden_zone["2unused-%s.%s" % (iface_name, fqdn)].append((ip, True))
1269
1270 # Device DNS names
1271 if 'cnode' in fqdn.lower():
1272 wleiden_zone["d-at-%s.%s" % (iface_name, fqdn)].append((showaddr(parseaddr(ip) + 1), False))
1273 wleiden_cname["d-at-%s.%s" % (iface_name,sn(fqdn))] = "d-at-%s.%s" % ((iface_name, fqdn))
1274
1275 elif len(value) == 2:
1276 (a_iface_name, a_fqdn, a_ip) = value[0]
1277 (b_iface_name, b_fqdn, b_ip) = value[1]
1278 wleiden_zone["2%s.%s" % (b_fqdn,a_fqdn)].append((a_ip, True))
1279 wleiden_zone["2%s.%s" % (a_fqdn,b_fqdn)].append((b_ip, True))
1280
1281 # Device DNS names
1282 if 'cnode' in a_fqdn.lower() and 'cnode' in b_fqdn.lower():
1283 wleiden_zone["d-at-%s.%s" % (a_iface_name, a_fqdn)].append((showaddr(parseaddr(a_ip) + 1), False))
1284 wleiden_zone["d-at-%s.%s" % (b_iface_name, b_fqdn)].append((showaddr(parseaddr(b_ip) - 1), False))
1285 wleiden_cname["d-at-%s.%s" % (a_iface_name,sn(a_fqdn))] = "d-at-%s.%s" % (a_iface_name, a_fqdn)
1286 wleiden_cname["d-at-%s.%s" % (b_iface_name,sn(b_fqdn))] = "d-at-%s.%s" % (b_iface_name, b_fqdn)
1287 wleiden_cname["d2%s.%s" % (sn(b_fqdn),sn(a_fqdn))] = "d-at-%s.%s" % (a_iface_name, a_fqdn)
1288 wleiden_cname["d2%s.%s" % (sn(a_fqdn),sn(b_fqdn))] = "d-at-%s.%s" % (b_iface_name, b_fqdn)
1289
1290 else:
1291 pool_members = [k[1] for k in value]
1292 for item in value:
1293 (iface_name, fqdn, ip) = item
1294 wleiden_zone["2ring.%s" % (fqdn)].append((ip, True))
1295
1296 # Include static DNS entries
1297 # XXX: Should they override the autogenerated results?
1298 # XXX: Convert input to yaml more useable.
1299 # Format:
1300 ##; this is a comment
1301 ## roomburgh=CNodeRoomburgh1
1302 ## apkerk1.CNodeVosko=172.17.176.8 ;this as well
1303 dns_list = yaml.load(open(os.path.join(NODE_DIR,'../dns/staticDNS.yaml'),'r'))
1304
1305 # Hack to allow special entries, for development
1306 wleiden_raw = {}
1307
1308 for line in dns_list:
1309 reverse = False
1310 k, items = line.items()[0]
1311 if type(items) == dict:
1312 if items.has_key('reverse'):
1313 reverse = items['reverse']
1314 items = items['a']
1315 else:
1316 items = items['cname']
1317 items = [items] if type(items) != list else items
1318 for item in items:
1319 if item.startswith('IN '):
1320 wleiden_raw[k] = item
1321 elif valid_addr(item):
1322 wleiden_zone[k].append((item, reverse))
1323 else:
1324 wleiden_cname[k] = item
1325
1326 # Hack to get dynamic pool listing
1327 def chunks(l, n):
1328 return [l[i:i+n] for i in range(0, len(l), n)]
1329
1330 ntp_servers = [x[0] for x in get_nameservers()]
1331 for id, chunk in enumerate(chunks(ntp_servers,(len(ntp_servers)/4))):
1332 for ntp_server in chunk:
1333 wleiden_zone['%i.pool.ntp' % id].append((ntp_server, False))
1334
1335 details = dict()
1336 # 24 updates a day allowed
1337 details['serial'] = time.strftime('%Y%m%d%H')
1338
1339 if external:
1340 dns_masters = ['siteview.wirelessleiden.nl', 'ns1.vanderzwet.net']
1341 else:
1342 dns_masters = ['sunny.wleiden.net'] + ["%s.wleiden.net" % x[1] for x in get_nameservers(max_servers=3)]
1343
1344 details['master'] = dns_masters[0]
1345 details['ns_servers'] = '\n'.join(['\tNS\t%s.' % x for x in dns_masters])
1346
1347 dns_header = '''
1348$TTL 3h
1349%(zone)s. SOA %(master)s. beheer.lijst.wirelessleiden.nl. ( %(serial)s 1d 12h 1w 60s )
1350 ; Serial, Refresh, Retry, Expire, Neg. cache TTL
1351
1352%(ns_servers)s
1353 \n'''
1354
1355
1356 if not os.path.isdir(output_dir):
1357 os.makedirs(output_dir)
1358 details['zone'] = 'wleiden.net'
1359 f = open(os.path.join(output_dir,"db." + details['zone']), "w")
1360 f.write(dns_header % details)
1361
1362 for host,items in wleiden_zone.iteritems():
1363 for ip,reverse in items:
1364 if ip not in ['0.0.0.0']:
1365 f.write("%s.wleiden.net. IN A %s \n" % (host.lower(), ip))
1366 for source,dest in wleiden_cname.iteritems():
1367 dest = dest if dest.endswith('.') else dest + ".wleiden.net."
1368 f.write("%s.wleiden.net. IN CNAME %s\n" % (source.lower(), dest.lower()))
1369 for source, dest in wleiden_raw.iteritems():
1370 f.write("%s.wleiden.net. %s\n" % (source, dest))
1371 f.close()
1372
1373 # Create whole bunch of specific sub arpa zones. To keep it compliant
1374 for s in range(16,32):
1375 details['zone'] = '%i.172.in-addr.arpa' % s
1376 f = open(os.path.join(output_dir,"db." + details['zone']), "w")
1377 f.write(dns_header % details)
1378
1379 #XXX: Not effient, fix to proper data structure and do checks at other
1380 # stages
1381 for host,items in wleiden_zone.iteritems():
1382 for ip,reverse in items:
1383 if not reverse:
1384 continue
1385 if valid_addr(ip):
1386 if valid_addr(ip):
1387 if int(ip.split('.')[1]) == s:
1388 rev_ip = '.'.join(reversed(ip.split('.')))
1389 f.write("%s.in-addr.arpa. IN PTR %s.wleiden.net.\n" % (rev_ip.lower(), host.lower()))
1390 f.close()
1391
1392
1393def usage():
1394 print """Usage: %(prog)s <argument>
1395Argument:
1396\tstandalone [port] = Run configurator webserver [8000]
1397\tdns [outputdir] = Generate BIND compliant zone files in dns [./dns]
1398\tnagios-export [--heavy-load] = Generate basic nagios configuration file.
1399\tfull-export = Generate yaml export script for heatmap.
1400\tstatic [outputdir] = Generate all config files and store on disk
1401\t with format ./<outputdir>/%%NODE%%/%%FILE%% [./static]
1402\ttest <node> [<file>] = Receive output for certain node [all files].
1403\ttest-cgi <node> <file> = Receive output of CGI script [all files].
1404\tlist <status> <items> = List systems which have certain status
1405
1406Arguments:
1407\t<node> = NodeName (example: HybridRick)
1408\t<file> = %(files)s
1409\t<status> = all|up|down|planned
1410\t<items> = systems|nodes|proxies
1411
1412NOTE FOR DEVELOPERS; you can test your changes like this:
1413 BEFORE any changes in this code:
1414 $ ./gformat.py static /tmp/pre
1415 AFTER the changes:
1416 $ ./gformat.py static /tmp/post
1417 VIEW differences and VERIFY all are OK:
1418 $ diff -urI 'Generated' -r /tmp/pre /tmp/post
1419""" % { 'prog' : sys.argv[0], 'files' : '|'.join(files) }
1420 exit(0)
1421
1422
1423def is_text_request(environ=os.environ):
1424 """ Find out whether we are calling from the CLI or any text based CLI utility """
1425 try:
1426 return environ['HTTP_USER_AGENT'].split()[0] in ['curl', 'fetch', 'wget']
1427 except KeyError:
1428 return True
1429
1430def switchFormat(setting):
1431 if setting:
1432 return "YES"
1433 else:
1434 return "NO"
1435
1436def rlinput(prompt, prefill=''):
1437 import readline
1438 readline.set_startup_hook(lambda: readline.insert_text(prefill))
1439 try:
1440 return raw_input(prompt)
1441 finally:
1442 readline.set_startup_hook()
1443
1444def fix_conflict(left, right, default='i'):
1445 while True:
1446 print "## %-30s | %-30s" % (left, right)
1447 c = raw_input("## Solve Conflict (h for help) <l|r|e|i|> [%s]: " % default)
1448 if not c:
1449 c = default
1450
1451 if c in ['l','1']:
1452 return left
1453 elif c in ['r','2']:
1454 return right
1455 elif c in ['e', '3']:
1456 return rlinput("Edit: ", "%30s | %30s" % (left, right))
1457 elif c in ['i', '4']:
1458 return None
1459 else:
1460 print "#ERROR: '%s' is invalid input (left, right, edit or ignore)!" % c
1461
1462
1463
1464def print_cgi_response(response_headers, output):
1465 """Could we not use some kind of wsgi wrapper to make this output?"""
1466 for header in response_headers:
1467 print "%s: %s" % header
1468 print
1469 print output
1470
1471
1472
1473def main():
1474 """Hard working sub"""
1475 # Allow easy hacking using the CLI
1476 if not os.environ.has_key('PATH_INFO'):
1477 if len(sys.argv) < 2:
1478 usage()
1479
1480 if sys.argv[1] == "standalone":
1481 import SocketServer
1482 import CGIHTTPServer
1483 # Hop to the right working directory.
1484 os.chdir(os.path.dirname(__file__))
1485 try:
1486 PORT = int(sys.argv[2])
1487 except (IndexError,ValueError):
1488 PORT = 8000
1489
1490 class MyCGIHTTPRequestHandler(CGIHTTPServer.CGIHTTPRequestHandler):
1491 """ Serve this CGI from the root of the webserver """
1492 def is_cgi(self):
1493 if "favicon" in self.path:
1494 return False
1495
1496 self.cgi_info = (os.path.basename(__file__), self.path)
1497 self.path = ''
1498 return True
1499 handler = MyCGIHTTPRequestHandler
1500 SocketServer.TCPServer.allow_reuse_address = True
1501 httpd = SocketServer.TCPServer(("", PORT), handler)
1502 httpd.server_name = 'localhost'
1503 httpd.server_port = PORT
1504
1505 logger.info("serving at port %s", PORT)
1506 try:
1507 httpd.serve_forever()
1508 except KeyboardInterrupt:
1509 httpd.shutdown()
1510 logger.info("All done goodbye")
1511 elif sys.argv[1] == "test":
1512 # Basic argument validation
1513 try:
1514 node = sys.argv[2]
1515 datadump = get_yaml(node)
1516 except IndexError:
1517 print "Invalid argument"
1518 exit(1)
1519 except IOError as e:
1520 print e
1521 exit(1)
1522
1523
1524 # Get files to generate
1525 gen_files = sys.argv[3:] if len(sys.argv) > 3 else files
1526
1527 # Actual config generation
1528 for config in gen_files:
1529 logger.info("## Generating %s %s", node, config)
1530 print generate_config(node, config, datadump)
1531 elif sys.argv[1] == "test-cgi":
1532 os.environ['PATH_INFO'] = "/".join(sys.argv[2:])
1533 os.environ['SCRIPT_NAME'] = __file__
1534 response_headers, output = process_cgi_request()
1535 print_cgi_response(response_headers, output)
1536 elif sys.argv[1] == "static":
1537 items = dict()
1538 items['output_dir'] = sys.argv[2] if len(sys.argv) > 2 else "./static"
1539 for node in get_hostlist():
1540 items['node'] = node
1541 items['wdir'] = "%(output_dir)s/%(node)s" % items
1542 if not os.path.isdir(items['wdir']):
1543 os.makedirs(items['wdir'])
1544 datadump = get_yaml(node)
1545 for config in files:
1546 items['config'] = config
1547 logger.info("## Generating %(node)s %(config)s" % items)
1548 f = open("%(wdir)s/%(config)s" % items, "w")
1549 f.write(generate_config(node, config, datadump))
1550 f.close()
1551 elif sys.argv[1] == "wind-export":
1552 items = dict()
1553 for node in get_hostlist():
1554 datadump = get_yaml(node)
1555 sql = """INSERT IGNORE INTO nodes (name, name_ns, longitude, latitude)
1556 VALUES ('%(nodename)s', '%(nodename)s', %(latitude)s, %(longitude)s);""" % datadump;
1557 sql = """INSERT IGNORE INTO users_nodes (user_id, node_id, owner)
1558 VALUES (
1559 (SELECT id FROM users WHERE username = 'rvdzwet'),
1560 (SELECT id FROM nodes WHERE name = '%(nodename)s'),
1561 'Y');""" % datadump
1562 #for config in files:
1563 # items['config'] = config
1564 # print "## Generating %(node)s %(config)s" % items
1565 # f = open("%(wdir)s/%(config)s" % items, "w")
1566 # f.write(generate_config(node, config, datadump))
1567 # f.close()
1568 for node in get_hostlist():
1569 datadump = get_yaml(node)
1570 for iface_key in sorted([elem for elem in datadump.keys() if elem.startswith('iface_')]):
1571 ifacedump = datadump[iface_key]
1572 if ifacedump.has_key('mode') and ifacedump['mode'] == 'ap-wds':
1573 ifacedump['nodename'] = datadump['nodename']
1574 if not ifacedump.has_key('channel') or not ifacedump['channel']:
1575 ifacedump['channel'] = 0
1576 sql = """INSERT INTO links (node_id, type, ssid, protocol, channel, status)
1577 VALUES ((SELECT id FROM nodes WHERE name = '%(nodename)s'), 'ap',
1578 '%(ssid)s', 'IEEE 802.11b', %(channel)s, 'active');""" % ifacedump
1579 elif sys.argv[1] == "nagios-export":
1580 try:
1581 heavy_load = (sys.argv[2] == "--heavy-load")
1582 except IndexError:
1583 heavy_load = False
1584
1585 hostgroup_details = {
1586 'wleiden' : 'Stichting Wireless Leiden - FreeBSD Nodes',
1587 'wzoeterwoude' : 'Stichting Wireless Leiden - Afdeling Zoeterwoude - Free-WiFi Project',
1588 'walphen' : 'Stichting Wireless Alphen',
1589 'westeinder' : 'WestEinder Plassen',
1590 }
1591
1592 params = {
1593 'check_interval' : 5 if heavy_load else 60,
1594 'retry_interval' : 1 if heavy_load else 5,
1595 'max_check_attempts' : 10 if heavy_load else 3,
1596 }
1597
1598 print '''\
1599define host {
1600 name wleiden-node ; Default Node Template
1601 use generic-host ; Use the standard template as initial starting point
1602 check_period 24x7 ; By default, FreeBSD hosts are checked round the clock
1603 check_interval %(check_interval)s ; Actively check the host every 5 minutes
1604 retry_interval %(retry_interval)s ; Schedule host check retries at 1 minute intervals
1605 max_check_attempts %(max_check_attempts)s ; Check each FreeBSD host 10 times (max)
1606 register 0 ; DONT REGISTER THIS DEFINITION - ITS NOT A REAL HOST, JUST A TEMPLATE!
1607}
1608
1609define service {
1610 name wleiden-service ; Default Service Template
1611 use generic-service ; Use the standard template as initial starting point
1612 check_period 24x7 ; By default, FreeBSD hosts are checked round the clock
1613 check_interval %(check_interval)s ; Actively check the host every 5 minutes
1614 retry_interval %(retry_interval)s ; Schedule host check retries at 1 minute intervals
1615 max_check_attempts %(max_check_attempts)s ; Check each FreeBSD host 10 times (max)
1616 register 0 ; DONT REGISTER THIS DEFINITION - ITS NOT A REAL HOST, JUST A TEMPLATE!
1617}
1618
1619# Please make sure to install:
1620# make -C /usr/ports/net-mgmt/nagios-check_netsnmp install clean
1621#
1622define command{
1623 command_name check_netsnmp_disk
1624 command_line $USER1$/check_netsnmp -H $HOSTADDRESS$ -o disk
1625}
1626
1627define command{
1628 command_name check_netsnmp_load
1629 command_line $USER1$/check_netsnmp -H $HOSTADDRESS$ -o load
1630}
1631
1632define command{
1633 command_name check_netsnmp_proc
1634 command_line $USER1$/check_netsnmp -H $HOSTADDRESS$ -o proc
1635}
1636
1637# TDB: dhcp leases
1638# /usr/local/libexec/nagios/check_netsnmp -H 192.168.178.47 --oid 1 exec
1639
1640# TDB: internet status
1641# /usr/local/libexec/nagios/check_netsnmp -H 192.168.178.47 --oid 1 file
1642
1643# TDB: Advanced local passive checks
1644# /usr/local/libexec/nagios/check_by_ssh
1645''' % params
1646
1647 print '''\
1648# Service Group, not displayed by default
1649define hostgroup {
1650 hostgroup_name srv_hybrid
1651 alias All Hybrid Nodes
1652 register 0
1653}
1654
1655define service {
1656 use wleiden-service
1657 hostgroup_name srv_hybrid
1658 service_description SSH
1659 check_command check_ssh
1660}
1661
1662define service {
1663 use wleiden-service
1664 hostgroup_name srv_hybrid
1665 service_description HTTP
1666 check_command check_http
1667}
1668
1669define service {
1670 use wleiden-service
1671 hostgroup_name srv_hybrid
1672 service_description DNS
1673 check_command check_dns
1674}
1675
1676# TDB: Can only test this if we have the proxy listening to all addresses.
1677# define service {
1678# use wleiden-service
1679# hostgroup_name srv_hybrid
1680# service_description PROXY
1681# check_command check_tcp!3128
1682# }
1683'''
1684
1685 if heavy_load:
1686 print '''\
1687define service {
1688 use wleiden-service
1689 hostgroup_name srv_hybrid
1690 service_description SNMP
1691 check_command check_snmp
1692}
1693
1694define service {
1695 use wleiden-service
1696 hostgroup_name srv_hybrid
1697 service_description NTP
1698 check_command check_ntp_peer
1699}
1700
1701define service {
1702 use wleiden-service
1703 hostgroup_name srv_hybrid
1704 service_description LOAD
1705 check_command check_netsnmp_load
1706}
1707
1708define service {
1709 use wleiden-service
1710 hostgroup_name srv_hybrid
1711 service_description PROC
1712 check_command check_netsnmp_proc
1713}
1714
1715define service {
1716 use wleiden-service
1717 hostgroup_name srv_hybrid
1718 service_description DISK
1719 check_command check_netsnmp_disk
1720}
1721'''
1722 for node in get_hostlist():
1723 datadump = get_yaml(node)
1724 if not datadump['status'] == 'up':
1725 continue
1726 if not hostgroup_details.has_key(datadump['monitoring_group']):
1727 hostgroup_details[datadump['monitoring_group']] = datadump['monitoring_group']
1728 print '''\
1729define host {
1730 use wleiden-node
1731 host_name %(autogen_fqdn)s
1732 address %(masterip)s
1733 hostgroups srv_hybrid,%(monitoring_group)s
1734}
1735''' % datadump
1736
1737 for name,alias in hostgroup_details.iteritems():
1738 print '''\
1739define hostgroup {
1740 hostgroup_name %s
1741 alias %s
1742} ''' % (name, alias)
1743
1744
1745 elif sys.argv[1] == "full-export":
1746 hosts = {}
1747 for node in get_hostlist():
1748 datadump = get_yaml(node)
1749 hosts[datadump['nodename']] = datadump
1750 print yaml.dump(hosts)
1751
1752 elif sys.argv[1] == "dns":
1753 make_dns(sys.argv[2] if len(sys.argv) > 2 else 'dns', 'external' in sys.argv)
1754 elif sys.argv[1] == "cleanup":
1755 # First generate all datadumps
1756 datadumps = dict()
1757 ssid_to_node = dict()
1758 for host in get_hostlist():
1759 logger.info("# Processing: %s", host)
1760 # Set some boring default values
1761 datadump = { 'board' : 'UNKNOWN' }
1762 datadump.update(get_yaml(host))
1763 datadumps[datadump['autogen_realname']] = datadump
1764
1765 (poel, errors) = make_relations(datadumps)
1766 print "\n".join(["# WARNING: %s" % x for x in errors])
1767
1768 for host,datadump in datadumps.iteritems():
1769 try:
1770 # Convert all yes and no to boolean values
1771 def fix_boolean(dump):
1772 for key in dump.keys():
1773 if type(dump[key]) == dict:
1774 dump[key] = fix_boolean(dump[key])
1775 elif str(dump[key]).lower() in ["yes", "true"]:
1776 dump[key] = True
1777 elif str(dump[key]).lower() in ["no", "false"]:
1778 # Compass richting no (Noord Oost) is valid input
1779 if key != "compass": dump[key] = False
1780 return dump
1781 datadump = fix_boolean(datadump)
1782
1783 if datadump['rdnap_x'] and datadump['rdnap_y']:
1784 datadump['latitude'], datadump['longitude'] = rdnap.rd2etrs(datadump['rdnap_x'], datadump['rdnap_y'])
1785 elif datadump['latitude'] and datadump['longitude']:
1786 datadump['rdnap_x'], datadump['rdnap_y'] = rdnap.etrs2rd(datadump['latitude'], datadump['longitude'])
1787
1788 if datadump['nodename'].startswith('Proxy'):
1789 datadump['nodename'] = datadump['nodename'].lower()
1790
1791 for iface_key in datadump['autogen_iface_keys']:
1792 try:
1793 # All our normal wireless cards are normal APs now
1794 if datadump[iface_key]['type'] in ['11a', '11b', '11g', 'wireless']:
1795 datadump[iface_key]['mode'] = 'ap'
1796 # Wireless Leiden SSID have an consistent lowercase/uppercase
1797 if datadump[iface_key].has_key('ssid'):
1798 ssid = datadump[iface_key]['ssid']
1799 prefix = 'ap-WirelessLeiden-'
1800 if ssid.lower().startswith(prefix.lower()):
1801 datadump[iface_key]['ssid'] = prefix + ssid[len(prefix)].upper() + ssid[len(prefix) + 1:]
1802 if datadump[iface_key].has_key('ns_ip') and not datadump[iface_key].has_key('mode'):
1803 datadump[iface_key]['mode'] = 'autogen-FIXME'
1804 if not datadump[iface_key].has_key('comment'):
1805 datadump[iface_key]['comment'] = 'autogen-FIXME'
1806
1807 if datadump[iface_key]['comment'].startswith('autogen-') and datadump[iface_key].has_key('comment'):
1808 datadump[iface_key] = datadump[iface_key]['desc']
1809
1810 x = datadump[iface_key]['comment']
1811 datadump[iface_key]['comment'] = x[0].upper() + x[1:]
1812
1813
1814 if datadump[iface_key].has_key('desc'):
1815 if datadump[iface_key]['comment'].lower() == datadump[iface_key]['desc'].lower():
1816 del datadump[iface_key]['desc']
1817 else:
1818 print "# ERROR: At %s - %s" % (datadump['nodename'], iface_key)
1819 response = fix_conflict(datadump[iface_key]['comment'], datadump[iface_key]['desc'])
1820 if response:
1821 datadump[iface_key]['comment'] = response
1822 del datadump[iface_key]['desc']
1823
1824 # Check DHCP configuration
1825 dhcp_type(datadump[iface_key])
1826
1827 # Set the compass value based on the angle between the poels
1828 if datadump[iface_key].has_key('ns_ip'):
1829 my_pool = poel[network(datadump[iface_key]['ip'])]
1830 remote_hosts = list(set([x[0] for x in my_pool]) - set([host]))
1831 if remote_hosts:
1832 compass_target = remote_hosts[0]
1833 datadump[iface_key]['compass'] = cd_between_hosts(host, compass_target, datadumps)
1834 except Exception as e:
1835 print "# Error while processing interface %s" % iface_key
1836 raise
1837 store_yaml(datadump)
1838 except Exception as e:
1839 print "# Error while processing %s" % host
1840 raise
1841 elif sys.argv[1] == "list":
1842 use_fqdn = False
1843 if len(sys.argv) < 4 or not sys.argv[2] in ["up", "down", "planned", "all"]:
1844 usage()
1845 if sys.argv[3] == "nodes":
1846 systems = get_nodelist()
1847 elif sys.argv[3] == "proxies":
1848 systems = get_proxylist()
1849 elif sys.argv[3] == "systems":
1850 systems = get_hostlist()
1851 else:
1852 usage()
1853 if len(sys.argv) > 4:
1854 if sys.argv[4] == "fqdn":
1855 use_fqdn = True
1856 else:
1857 usage()
1858
1859 for system in systems:
1860 datadump = get_yaml(system)
1861
1862 output = datadump['autogen_fqdn'] if use_fqdn else system
1863 if sys.argv[2] == "all":
1864 print output
1865 elif datadump['status'] == sys.argv[2]:
1866 print output
1867 elif sys.argv[1] == "create":
1868 if sys.argv[2] == "network.kml":
1869 print make_network_kml.make_graph()
1870 elif sys.argv[2] == "host-ips.txt":
1871 for system in get_hostlist():
1872 datadump = get_yaml(system)
1873 ips = [datadump['masterip']]
1874 for ifkey in datadump['autogen_iface_keys']:
1875 ips.append(datadump[ifkey]['ip'].split('/')[0])
1876 print system, ' '.join(ips)
1877 elif sys.argv[2] == "host-pos.txt":
1878 for system in get_hostlist():
1879 datadump = get_yaml(system)
1880 print system, datadump['rdnap_x'], datadump['rdnap_y']
1881 else:
1882 usage()
1883 else:
1884 usage()
1885 else:
1886 # Do not enable debugging for config requests as it highly clutters the output
1887 if not is_text_request():
1888 cgitb.enable()
1889 response_headers, output = process_cgi_request()
1890 print_cgi_response(response_headers, output)
1891
1892def application(environ, start_response):
1893 status = '200 OK'
1894 response_headers, output = process_cgi_request(environ)
1895 start_response(status, response_headers)
1896
1897 # Debugging only
1898 # output = 'wsgi.multithread = %s' % repr(environ['wsgi.multithread'])
1899 # soutput += '\nwsgi.multiprocess = %s' % repr(environ['wsgi.multiprocess'])
1900 return [output]
1901
1902if __name__ == "__main__":
1903 main()
Note: See TracBrowser for help on using the repository browser.