source: genesis/tools/gformat.py@ 11609

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

Running as webprocess does not find /usr/local/bin/svn as proper path for svn binary.

Forcing it

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