source: genesis/tools/gformat.py@ 11736

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

Make DHCP flagging persistent, allowing static aliases on a DHCP interface.

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