source: genesis/tools/gformat.py@ 11739

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

Grumble aliases on DHCP interfaces proved to be a interesting challenge.

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