source: genesis/tools/gformat.py@ 11444

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

Quick om export te maken van nodeplanner applicatie.

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