source: genesis/tools/gformat.py@ 12245

Last change on this file since 12245 was 12245, checked in by www, 12 years ago

Path to binary needs to be absolute

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