source: genesis/tools/gformat.py@ 12366

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

Initial configuration of automatic nanostion configuration

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