source: genesis/tools/gformat.py@ 12442

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

Workaround quick for different version of notation

  • Property svn:executable set to *
  • Property svn:keywords set to Id
File size: 66.0 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 12441 2013-10-10 11:40:17Z 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):
[12441]1113 #TODO(rvdz): Make sure the proper nanostation IP and subnet is set
1114 datadump['iface_%s' % iface]['ns_ip'] = datadump['iface_%s' % iface]['ns_ip'].split('/')[0]
1115
[12349]1116 datadump.update(datadump['iface_%s' % iface])
[8267]1117
[12349]1118 return open(os.path.join(os.path.dirname(__file__), 'ns5m.cfg.tmpl'),'r').read() % datadump
1119
[8588]1120def generate_yaml(datadump):
1121 return generate_config(datadump['nodename'], "wleiden.yaml", datadump)
[8267]1122
[8588]1123
[9283]1124
[8298]1125def generate_config(node, config, datadump=None):
[8257]1126 """ Print configuration file 'config' of 'node' """
[8267]1127 output = ""
[8242]1128 try:
1129 # Load config file
[8298]1130 if datadump == None:
1131 datadump = get_yaml(node)
[9283]1132
[8242]1133 if config == 'wleiden.yaml':
[8267]1134 output += generate_wleiden_yaml(datadump)
1135 elif config == 'authorized_keys':
[10051]1136 f = open(os.path.join(NODE_DIR,"global_keys"), 'r')
[8267]1137 output += f.read()
[12433]1138 node_keys = os.path.join(NODE_DIR,node,'authorized_keys')
1139 # Fetch local keys if existing
1140 if os.path.exists(node_keys):
1141 output += open(node_keys, 'r').read()
[8242]1142 f.close()
1143 elif config == 'dnsmasq.conf':
[10281]1144 output += generate_dnsmasq_conf(datadump)
[10410]1145 elif config == 'dhcpd.conf':
1146 output += generate_dhcpd_conf(datadump)
[8242]1147 elif config == 'rc.conf.local':
[10281]1148 output += generate_rc_conf_local(datadump)
[8242]1149 elif config == 'resolv.conf':
[10281]1150 output += generate_resolv_conf(datadump)
[10654]1151 elif config == 'ntp.conf':
1152 output += generate_ntp_conf(datadump)
[10069]1153 elif config == 'motd':
[10281]1154 output += generate_motd(datadump)
[10705]1155 elif config == 'pf.hybrid.conf.local':
1156 output += generate_pf_hybrid_conf_local(datadump)
[12349]1157 elif config.startswith('vr'):
1158 interface, ns_type = config.strip('.yaml').split('-')
1159 output += generate_nanostation_config(datadump, interface, ns_type)
[8242]1160 else:
[9283]1161 assert False, "Config not found!"
[8242]1162 except IOError, e:
[8267]1163 output += "[ERROR] Config file not found"
1164 return output
[8242]1165
1166
[8257]1167
[11426]1168def process_cgi_request(environ=os.environ):
[8258]1169 """ When calling from CGI """
[11426]1170 response_headers = []
1171 content_type = 'text/plain'
1172
[8258]1173 # Update repository if requested
[11427]1174 form = urlparse.parse_qs(environ['QUERY_STRING']) if environ.has_key('QUERY_STRING') else None
1175 if form and form.has_key("action") and "update" in form["action"]:
[11426]1176 output = "[INFO] Updating subverion, please wait...\n"
[12245]1177 output += subprocess.Popen([SVN, 'cleanup', "%s/.." % NODE_DIR], stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0]
1178 output += subprocess.Popen([SVN, 'up', "%s/.." % NODE_DIR], stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0]
[11426]1179 output += "[INFO] All done, redirecting in 5 seconds"
1180 response_headers += [
1181 ('Refresh', '5; url=.'),
1182 ]
[11533]1183 reload_cache()
[11426]1184 else:
1185 base_uri = environ['PATH_INFO']
1186 uri = base_uri.strip('/').split('/')
[9283]1187
[11426]1188 output = "Template Holder"
1189 if base_uri.endswith('/create/network.kml'):
1190 content_type='application/vnd.google-earth.kml+xml'
1191 output = make_network_kml.make_graph()
[11444]1192 elif base_uri.endswith('/api/get/nodeplanner.json'):
1193 content_type='application/json'
1194 output = make_network_kml.make_nodeplanner_json()
[11426]1195 elif not uri[0]:
1196 if is_text_request(environ):
1197 output = '\n'.join(get_hostlist())
1198 else:
1199 content_type = 'text/html'
1200 output = generate_title(get_hostlist())
1201 elif len(uri) == 1:
1202 if is_text_request(environ):
1203 output = generate_node(uri[0])
1204 else:
1205 content_type = 'text/html'
1206 output = generate_node_overview(uri[0])
1207 elif len(uri) == 2:
1208 output = generate_config(uri[0], uri[1])
1209 else:
1210 assert False, "Invalid option"
[9283]1211
[11426]1212 # Return response
1213 response_headers += [
1214 ('Content-type', content_type),
1215 ('Content-Length', str(len(output))),
1216 ]
1217 return(response_headers, str(output))
[10270]1218
[10681]1219
[10391]1220def get_realname(datadump):
[10365]1221 # Proxy naming convention is special, as the proxy name is also included in
1222 # the nodename, when it comes to the numbered proxies.
[8588]1223 if datadump['nodetype'] == 'Proxy':
[10391]1224 realname = datadump['nodetype'] + datadump['nodename'].replace('proxy','')
[8588]1225 else:
1226 # By default the full name is listed and also a shortname CNAME for easy use.
[10391]1227 realname = datadump['nodetype'] + datadump['nodename']
1228 return(realname)
[8259]1229
[9283]1230
1231
[10264]1232def make_dns(output_dir = 'dns', external = False):
[8588]1233 items = dict()
[8598]1234
[8588]1235 # hostname is key, IP is value
[10642]1236 wleiden_zone = defaultdict(list)
[8588]1237 wleiden_cname = dict()
[8598]1238
[8588]1239 pool = dict()
1240 for node in get_hostlist():
1241 datadump = get_yaml(node)
[9283]1242
[8588]1243 # Proxy naming convention is special
[10391]1244 fqdn = datadump['autogen_realname']
[10461]1245 if datadump['nodetype'] in ['CNode', 'Hybrid']:
[8588]1246 wleiden_cname[datadump['nodename']] = fqdn
[10730]1247
1248 if datadump.has_key('rdr_host'):
1249 remote_target = datadump['rdr_host']
1250 elif datadump.has_key('remote_access') and datadump['remote_access']:
1251 remote_target = datadump['remote_access'].split(':')[0]
1252 else:
1253 remote_target = None
[8588]1254
[10730]1255 if remote_target:
1256 try:
1257 parseaddr(remote_target)
1258 wleiden_zone[datadump['nodename'] + '.gw'].append((remote_target, False))
1259 except (IndexError, ValueError):
1260 wleiden_cname[datadump['nodename'] + '.gw'] = remote_target + '.'
1261
1262
[10655]1263 wleiden_zone[fqdn].append((datadump['masterip'], True))
[8588]1264
[8598]1265 # Hacking to get proper DHCP IPs and hostnames
[8588]1266 for iface_key in get_interface_keys(datadump):
[10890]1267 iface_name = iface_key.replace('_','-')
[10410]1268 (ip, cidr) = datadump[iface_key]['ip'].split('/')
[8588]1269 try:
1270 (dhcp_start, dhcp_stop) = datadump[iface_key]['dhcp'].split('-')
[10882]1271 datadump[iface_key]['autogen_netmask'] = cidr2netmask(cidr)
[8588]1272 dhcp_part = ".".join(ip.split('.')[0:3])
1273 if ip != datadump['masterip']:
[10655]1274 wleiden_zone["dhcp-gateway-%s.%s" % (iface_name, fqdn)].append((ip, False))
[8588]1275 for i in range(int(dhcp_start), int(dhcp_stop) + 1):
[10655]1276 wleiden_zone["dhcp-%s-%s.%s" % (i, iface_name, fqdn)].append(("%s.%s" % (dhcp_part, i), True))
[10825]1277 except (AttributeError, ValueError, KeyError):
[8588]1278 # First push it into a pool, to indentify the counter-part later on
1279 addr = parseaddr(ip)
[10461]1280 cidr = int(cidr)
1281 addr = addr & ~((1 << (32 - cidr)) - 1)
[9283]1282 if pool.has_key(addr):
[8588]1283 pool[addr] += [(iface_name, fqdn, ip)]
[9283]1284 else:
[8588]1285 pool[addr] = [(iface_name, fqdn, ip)]
1286 continue
1287
[9286]1288
1289
[9957]1290 # WL uses an /29 to configure an interface. IP's are ordered like this:
[9958]1291 # MasterA (.1) -- DeviceA (.2) <<>> DeviceB (.3) --- SlaveB (.4)
[9957]1292
1293 sn = lambda x: re.sub(r'(?i)^cnode','',x)
1294
[8598]1295 # Automatic naming convention of interlinks namely 2 + remote.lower()
[8588]1296 for (key,value) in pool.iteritems():
[9958]1297 # Make sure they are sorted from low-ip to high-ip
1298 value = sorted(value, key=lambda x: parseaddr(x[2]))
1299
[8588]1300 if len(value) == 1:
1301 (iface_name, fqdn, ip) = value[0]
[10655]1302 wleiden_zone["2unused-%s.%s" % (iface_name, fqdn)].append((ip, True))
[9957]1303
1304 # Device DNS names
1305 if 'cnode' in fqdn.lower():
[10655]1306 wleiden_zone["d-at-%s.%s" % (iface_name, fqdn)].append((showaddr(parseaddr(ip) + 1), False))
1307 wleiden_cname["d-at-%s.%s" % (iface_name,sn(fqdn))] = "d-at-%s.%s" % ((iface_name, fqdn))
[9957]1308
[8588]1309 elif len(value) == 2:
1310 (a_iface_name, a_fqdn, a_ip) = value[0]
1311 (b_iface_name, b_fqdn, b_ip) = value[1]
[10655]1312 wleiden_zone["2%s.%s" % (b_fqdn,a_fqdn)].append((a_ip, True))
1313 wleiden_zone["2%s.%s" % (a_fqdn,b_fqdn)].append((b_ip, True))
[9957]1314
1315 # Device DNS names
1316 if 'cnode' in a_fqdn.lower() and 'cnode' in b_fqdn.lower():
[10655]1317 wleiden_zone["d-at-%s.%s" % (a_iface_name, a_fqdn)].append((showaddr(parseaddr(a_ip) + 1), False))
1318 wleiden_zone["d-at-%s.%s" % (b_iface_name, b_fqdn)].append((showaddr(parseaddr(b_ip) - 1), False))
[9957]1319 wleiden_cname["d-at-%s.%s" % (a_iface_name,sn(a_fqdn))] = "d-at-%s.%s" % (a_iface_name, a_fqdn)
1320 wleiden_cname["d-at-%s.%s" % (b_iface_name,sn(b_fqdn))] = "d-at-%s.%s" % (b_iface_name, b_fqdn)
1321 wleiden_cname["d2%s.%s" % (sn(b_fqdn),sn(a_fqdn))] = "d-at-%s.%s" % (a_iface_name, a_fqdn)
1322 wleiden_cname["d2%s.%s" % (sn(a_fqdn),sn(b_fqdn))] = "d-at-%s.%s" % (b_iface_name, b_fqdn)
1323
[8588]1324 else:
1325 pool_members = [k[1] for k in value]
1326 for item in value:
[9283]1327 (iface_name, fqdn, ip) = item
[10919]1328 wleiden_zone["2ring.%s" % (fqdn)].append((ip, True))
[8598]1329
1330 # Include static DNS entries
1331 # XXX: Should they override the autogenerated results?
1332 # XXX: Convert input to yaml more useable.
1333 # Format:
1334 ##; this is a comment
1335 ## roomburgh=CNodeRoomburgh1
1336 ## apkerk1.CNodeVosko=172.17.176.8 ;this as well
[10642]1337 dns_list = yaml.load(open(os.path.join(NODE_DIR,'../dns/staticDNS.yaml'),'r'))
[9938]1338
1339 # Hack to allow special entries, for development
[10642]1340 wleiden_raw = {}
[9938]1341
[10642]1342 for line in dns_list:
[10660]1343 reverse = False
[10642]1344 k, items = line.items()[0]
[10660]1345 if type(items) == dict:
1346 if items.has_key('reverse'):
1347 reverse = items['reverse']
1348 items = items['a']
1349 else:
1350 items = items['cname']
1351 items = [items] if type(items) != list else items
[10642]1352 for item in items:
1353 if item.startswith('IN '):
1354 wleiden_raw[k] = item
1355 elif valid_addr(item):
[10660]1356 wleiden_zone[k].append((item, reverse))
[8598]1357 else:
[10642]1358 wleiden_cname[k] = item
[9283]1359
[10986]1360 # Hack to get dynamic pool listing
1361 def chunks(l, n):
1362 return [l[i:i+n] for i in range(0, len(l), n)]
1363
1364 ntp_servers = [x[0] for x in get_nameservers()]
1365 for id, chunk in enumerate(chunks(ntp_servers,(len(ntp_servers)/4))):
1366 for ntp_server in chunk:
1367 wleiden_zone['%i.pool.ntp' % id].append((ntp_server, False))
1368
[8598]1369 details = dict()
1370 # 24 updates a day allowed
1371 details['serial'] = time.strftime('%Y%m%d%H')
1372
[10264]1373 if external:
1374 dns_masters = ['siteview.wirelessleiden.nl', 'ns1.vanderzwet.net']
1375 else:
[10980]1376 dns_masters = ['sunny.wleiden.net'] + ["%s.wleiden.net" % x[1] for x in get_nameservers(max_servers=3)]
[10264]1377
1378 details['master'] = dns_masters[0]
1379 details['ns_servers'] = '\n'.join(['\tNS\t%s.' % x for x in dns_masters])
1380
[8598]1381 dns_header = '''
1382$TTL 3h
[11725]1383%(zone)s. SOA %(master)s. beheer.lijst.wirelessleiden.nl. ( %(serial)s 15m 15m 1w 60s )
[8598]1384 ; Serial, Refresh, Retry, Expire, Neg. cache TTL
1385
[10264]1386%(ns_servers)s
[8598]1387 \n'''
1388
[9283]1389
[10264]1390 if not os.path.isdir(output_dir):
1391 os.makedirs(output_dir)
[8598]1392 details['zone'] = 'wleiden.net'
[9284]1393 f = open(os.path.join(output_dir,"db." + details['zone']), "w")
[8598]1394 f.write(dns_header % details)
1395
[10655]1396 for host,items in wleiden_zone.iteritems():
1397 for ip,reverse in items:
[10730]1398 if ip not in ['0.0.0.0']:
[10642]1399 f.write("%s.wleiden.net. IN A %s \n" % (host.lower(), ip))
[8588]1400 for source,dest in wleiden_cname.iteritems():
[10730]1401 dest = dest if dest.endswith('.') else dest + ".wleiden.net."
1402 f.write("%s.wleiden.net. IN CNAME %s\n" % (source.lower(), dest.lower()))
[9938]1403 for source, dest in wleiden_raw.iteritems():
1404 f.write("%s.wleiden.net. %s\n" % (source, dest))
[8588]1405 f.close()
[9283]1406
[8598]1407 # Create whole bunch of specific sub arpa zones. To keep it compliant
1408 for s in range(16,32):
1409 details['zone'] = '%i.172.in-addr.arpa' % s
[9284]1410 f = open(os.path.join(output_dir,"db." + details['zone']), "w")
[8598]1411 f.write(dns_header % details)
[8588]1412
[8598]1413 #XXX: Not effient, fix to proper data structure and do checks at other
1414 # stages
[10655]1415 for host,items in wleiden_zone.iteritems():
1416 for ip,reverse in items:
1417 if not reverse:
1418 continue
[10642]1419 if valid_addr(ip):
[10655]1420 if valid_addr(ip):
1421 if int(ip.split('.')[1]) == s:
1422 rev_ip = '.'.join(reversed(ip.split('.')))
1423 f.write("%s.in-addr.arpa. IN PTR %s.wleiden.net.\n" % (rev_ip.lower(), host.lower()))
[8598]1424 f.close()
[8588]1425
[8598]1426
[8259]1427def usage():
[10567]1428 print """Usage: %(prog)s <argument>
1429Argument:
1430\tstandalone [port] = Run configurator webserver [8000]
1431\tdns [outputdir] = Generate BIND compliant zone files in dns [./dns]
[11326]1432\tnagios-export [--heavy-load] = Generate basic nagios configuration file.
[9589]1433\tfull-export = Generate yaml export script for heatmap.
[10567]1434\tstatic [outputdir] = Generate all config files and store on disk
1435\t with format ./<outputdir>/%%NODE%%/%%FILE%% [./static]
[10872]1436\ttest <node> [<file>] = Receive output for certain node [all files].
1437\ttest-cgi <node> <file> = Receive output of CGI script [all files].
[10567]1438\tlist <status> <items> = List systems which have certain status
[10563]1439
[10567]1440Arguments:
1441\t<node> = NodeName (example: HybridRick)
1442\t<file> = %(files)s
1443\t<status> = all|up|down|planned
1444\t<items> = systems|nodes|proxies
1445
[10563]1446NOTE FOR DEVELOPERS; you can test your changes like this:
1447 BEFORE any changes in this code:
1448 $ ./gformat.py static /tmp/pre
1449 AFTER the changes:
1450 $ ./gformat.py static /tmp/post
1451 VIEW differences and VERIFY all are OK:
[10564]1452 $ diff -urI 'Generated' -r /tmp/pre /tmp/post
[10567]1453""" % { 'prog' : sys.argv[0], 'files' : '|'.join(files) }
[8259]1454 exit(0)
1455
1456
[11426]1457def is_text_request(environ=os.environ):
[10107]1458 """ Find out whether we are calling from the CLI or any text based CLI utility """
1459 try:
[11426]1460 return environ['HTTP_USER_AGENT'].split()[0] in ['curl', 'fetch', 'wget']
[10107]1461 except KeyError:
1462 return True
[8259]1463
[10547]1464def switchFormat(setting):
1465 if setting:
1466 return "YES"
1467 else:
1468 return "NO"
1469
[10885]1470def rlinput(prompt, prefill=''):
1471 import readline
1472 readline.set_startup_hook(lambda: readline.insert_text(prefill))
1473 try:
1474 return raw_input(prompt)
1475 finally:
1476 readline.set_startup_hook()
1477
1478def fix_conflict(left, right, default='i'):
1479 while True:
1480 print "## %-30s | %-30s" % (left, right)
1481 c = raw_input("## Solve Conflict (h for help) <l|r|e|i|> [%s]: " % default)
1482 if not c:
1483 c = default
1484
1485 if c in ['l','1']:
1486 return left
1487 elif c in ['r','2']:
1488 return right
1489 elif c in ['e', '3']:
1490 return rlinput("Edit: ", "%30s | %30s" % (left, right))
1491 elif c in ['i', '4']:
1492 return None
1493 else:
1494 print "#ERROR: '%s' is invalid input (left, right, edit or ignore)!" % c
1495
[11427]1496
1497
1498def print_cgi_response(response_headers, output):
1499 """Could we not use some kind of wsgi wrapper to make this output?"""
1500 for header in response_headers:
1501 print "%s: %s" % header
[11444]1502 print
[11427]1503 print output
1504
1505
[11534]1506def fill_cache():
1507 ''' Poor man re-loading of few cache items (the slow ones) '''
1508 for host in get_hostlist():
[11535]1509 get_yaml(host)
[11427]1510
[11534]1511
1512def reload_cache():
1513 clear_cache()
1514 fill_cache()
1515
1516
[8267]1517def main():
1518 """Hard working sub"""
1519 # Allow easy hacking using the CLI
1520 if not os.environ.has_key('PATH_INFO'):
1521 if len(sys.argv) < 2:
1522 usage()
[9283]1523
[8267]1524 if sys.argv[1] == "standalone":
1525 import SocketServer
1526 import CGIHTTPServer
[10105]1527 # Hop to the right working directory.
1528 os.chdir(os.path.dirname(__file__))
[8267]1529 try:
1530 PORT = int(sys.argv[2])
1531 except (IndexError,ValueError):
1532 PORT = 8000
[9283]1533
[8267]1534 class MyCGIHTTPRequestHandler(CGIHTTPServer.CGIHTTPRequestHandler):
1535 """ Serve this CGI from the root of the webserver """
1536 def is_cgi(self):
1537 if "favicon" in self.path:
1538 return False
[9283]1539
[10364]1540 self.cgi_info = (os.path.basename(__file__), self.path)
[8267]1541 self.path = ''
1542 return True
1543 handler = MyCGIHTTPRequestHandler
[9807]1544 SocketServer.TCPServer.allow_reuse_address = True
[8267]1545 httpd = SocketServer.TCPServer(("", PORT), handler)
1546 httpd.server_name = 'localhost'
1547 httpd.server_port = PORT
[9283]1548
[9728]1549 logger.info("serving at port %s", PORT)
[8860]1550 try:
1551 httpd.serve_forever()
1552 except KeyboardInterrupt:
1553 httpd.shutdown()
[9728]1554 logger.info("All done goodbye")
[8267]1555 elif sys.argv[1] == "test":
[10872]1556 # Basic argument validation
1557 try:
1558 node = sys.argv[2]
1559 datadump = get_yaml(node)
1560 except IndexError:
1561 print "Invalid argument"
1562 exit(1)
1563 except IOError as e:
1564 print e
1565 exit(1)
1566
1567
1568 # Get files to generate
1569 gen_files = sys.argv[3:] if len(sys.argv) > 3 else files
1570
1571 # Actual config generation
1572 for config in gen_files:
1573 logger.info("## Generating %s %s", node, config)
1574 print generate_config(node, config, datadump)
1575 elif sys.argv[1] == "test-cgi":
[8267]1576 os.environ['PATH_INFO'] = "/".join(sys.argv[2:])
1577 os.environ['SCRIPT_NAME'] = __file__
[11427]1578 response_headers, output = process_cgi_request()
1579 print_cgi_response(response_headers, output)
[8296]1580 elif sys.argv[1] == "static":
1581 items = dict()
[10563]1582 items['output_dir'] = sys.argv[2] if len(sys.argv) > 2 else "./static"
[8296]1583 for node in get_hostlist():
1584 items['node'] = node
[10563]1585 items['wdir'] = "%(output_dir)s/%(node)s" % items
[8296]1586 if not os.path.isdir(items['wdir']):
1587 os.makedirs(items['wdir'])
[8298]1588 datadump = get_yaml(node)
[8296]1589 for config in files:
1590 items['config'] = config
[9728]1591 logger.info("## Generating %(node)s %(config)s" % items)
[8296]1592 f = open("%(wdir)s/%(config)s" % items, "w")
[8298]1593 f.write(generate_config(node, config, datadump))
[8296]1594 f.close()
[9514]1595 elif sys.argv[1] == "wind-export":
1596 items = dict()
1597 for node in get_hostlist():
1598 datadump = get_yaml(node)
1599 sql = """INSERT IGNORE INTO nodes (name, name_ns, longitude, latitude)
1600 VALUES ('%(nodename)s', '%(nodename)s', %(latitude)s, %(longitude)s);""" % datadump;
1601 sql = """INSERT IGNORE INTO users_nodes (user_id, node_id, owner)
1602 VALUES (
1603 (SELECT id FROM users WHERE username = 'rvdzwet'),
1604 (SELECT id FROM nodes WHERE name = '%(nodename)s'),
1605 'Y');""" % datadump
1606 #for config in files:
1607 # items['config'] = config
1608 # print "## Generating %(node)s %(config)s" % items
1609 # f = open("%(wdir)s/%(config)s" % items, "w")
1610 # f.write(generate_config(node, config, datadump))
1611 # f.close()
1612 for node in get_hostlist():
1613 datadump = get_yaml(node)
1614 for iface_key in sorted([elem for elem in datadump.keys() if elem.startswith('iface_')]):
1615 ifacedump = datadump[iface_key]
1616 if ifacedump.has_key('mode') and ifacedump['mode'] == 'ap-wds':
1617 ifacedump['nodename'] = datadump['nodename']
1618 if not ifacedump.has_key('channel') or not ifacedump['channel']:
1619 ifacedump['channel'] = 0
1620 sql = """INSERT INTO links (node_id, type, ssid, protocol, channel, status)
1621 VALUES ((SELECT id FROM nodes WHERE name = '%(nodename)s'), 'ap',
1622 '%(ssid)s', 'IEEE 802.11b', %(channel)s, 'active');""" % ifacedump
[11326]1623 elif sys.argv[1] == "nagios-export":
1624 try:
1625 heavy_load = (sys.argv[2] == "--heavy-load")
1626 except IndexError:
1627 heavy_load = False
1628
1629 hostgroup_details = {
1630 'wleiden' : 'Stichting Wireless Leiden - FreeBSD Nodes',
1631 'wzoeterwoude' : 'Stichting Wireless Leiden - Afdeling Zoeterwoude - Free-WiFi Project',
1632 'walphen' : 'Stichting Wireless Alphen',
1633 'westeinder' : 'WestEinder Plassen',
1634 }
1635
1636 params = {
1637 'check_interval' : 5 if heavy_load else 60,
1638 'retry_interval' : 1 if heavy_load else 5,
1639 'max_check_attempts' : 10 if heavy_load else 3,
1640 }
1641
1642 print '''\
1643define host {
1644 name wleiden-node ; Default Node Template
1645 use generic-host ; Use the standard template as initial starting point
1646 check_period 24x7 ; By default, FreeBSD hosts are checked round the clock
1647 check_interval %(check_interval)s ; Actively check the host every 5 minutes
1648 retry_interval %(retry_interval)s ; Schedule host check retries at 1 minute intervals
1649 max_check_attempts %(max_check_attempts)s ; Check each FreeBSD host 10 times (max)
1650 register 0 ; DONT REGISTER THIS DEFINITION - ITS NOT A REAL HOST, JUST A TEMPLATE!
1651}
1652
1653define service {
1654 name wleiden-service ; Default Service Template
1655 use generic-service ; Use the standard template as initial starting point
1656 check_period 24x7 ; By default, FreeBSD hosts are checked round the clock
1657 check_interval %(check_interval)s ; Actively check the host every 5 minutes
1658 retry_interval %(retry_interval)s ; Schedule host check retries at 1 minute intervals
1659 max_check_attempts %(max_check_attempts)s ; Check each FreeBSD host 10 times (max)
1660 register 0 ; DONT REGISTER THIS DEFINITION - ITS NOT A REAL HOST, JUST A TEMPLATE!
1661}
1662
1663# Please make sure to install:
1664# make -C /usr/ports/net-mgmt/nagios-check_netsnmp install clean
1665#
1666define command{
1667 command_name check_netsnmp_disk
1668 command_line $USER1$/check_netsnmp -H $HOSTADDRESS$ -o disk
1669}
1670
1671define command{
1672 command_name check_netsnmp_load
1673 command_line $USER1$/check_netsnmp -H $HOSTADDRESS$ -o load
1674}
1675
1676define command{
1677 command_name check_netsnmp_proc
1678 command_line $USER1$/check_netsnmp -H $HOSTADDRESS$ -o proc
1679}
1680
1681# TDB: dhcp leases
1682# /usr/local/libexec/nagios/check_netsnmp -H 192.168.178.47 --oid 1 exec
1683
1684# TDB: internet status
1685# /usr/local/libexec/nagios/check_netsnmp -H 192.168.178.47 --oid 1 file
1686
1687# TDB: Advanced local passive checks
1688# /usr/local/libexec/nagios/check_by_ssh
1689''' % params
1690
1691 print '''\
1692# Service Group, not displayed by default
1693define hostgroup {
1694 hostgroup_name srv_hybrid
1695 alias All Hybrid Nodes
1696 register 0
1697}
1698
1699define service {
1700 use wleiden-service
1701 hostgroup_name srv_hybrid
1702 service_description SSH
1703 check_command check_ssh
1704}
1705
1706define service {
1707 use wleiden-service
1708 hostgroup_name srv_hybrid
1709 service_description HTTP
1710 check_command check_http
1711}
1712
1713define service {
1714 use wleiden-service
1715 hostgroup_name srv_hybrid
1716 service_description DNS
1717 check_command check_dns
1718}
1719
1720# TDB: Can only test this if we have the proxy listening to all addresses.
1721# define service {
1722# use wleiden-service
1723# hostgroup_name srv_hybrid
1724# service_description PROXY
1725# check_command check_tcp!3128
1726# }
1727'''
1728
1729 if heavy_load:
1730 print '''\
1731define service {
1732 use wleiden-service
1733 hostgroup_name srv_hybrid
1734 service_description SNMP
1735 check_command check_snmp
1736}
1737
1738define service {
1739 use wleiden-service
1740 hostgroup_name srv_hybrid
1741 service_description NTP
1742 check_command check_ntp_peer
1743}
1744
1745define service {
1746 use wleiden-service
1747 hostgroup_name srv_hybrid
1748 service_description LOAD
1749 check_command check_netsnmp_load
1750}
1751
1752define service {
1753 use wleiden-service
1754 hostgroup_name srv_hybrid
1755 service_description PROC
1756 check_command check_netsnmp_proc
1757}
1758
1759define service {
1760 use wleiden-service
1761 hostgroup_name srv_hybrid
1762 service_description DISK
1763 check_command check_netsnmp_disk
1764}
1765'''
1766 for node in get_hostlist():
1767 datadump = get_yaml(node)
1768 if not datadump['status'] == 'up':
1769 continue
1770 if not hostgroup_details.has_key(datadump['monitoring_group']):
1771 hostgroup_details[datadump['monitoring_group']] = datadump['monitoring_group']
1772 print '''\
1773define host {
1774 use wleiden-node
1775 host_name %(autogen_fqdn)s
1776 address %(masterip)s
1777 hostgroups srv_hybrid,%(monitoring_group)s
1778}
1779''' % datadump
1780
1781 for name,alias in hostgroup_details.iteritems():
1782 print '''\
1783define hostgroup {
1784 hostgroup_name %s
1785 alias %s
1786} ''' % (name, alias)
1787
1788
[9589]1789 elif sys.argv[1] == "full-export":
1790 hosts = {}
1791 for node in get_hostlist():
1792 datadump = get_yaml(node)
1793 hosts[datadump['nodename']] = datadump
1794 print yaml.dump(hosts)
1795
[8584]1796 elif sys.argv[1] == "dns":
[10264]1797 make_dns(sys.argv[2] if len(sys.argv) > 2 else 'dns', 'external' in sys.argv)
[9283]1798 elif sys.argv[1] == "cleanup":
[8588]1799 # First generate all datadumps
1800 datadumps = dict()
[10729]1801 ssid_to_node = dict()
[8588]1802 for host in get_hostlist():
[9728]1803 logger.info("# Processing: %s", host)
[10436]1804 # Set some boring default values
1805 datadump = { 'board' : 'UNKNOWN' }
1806 datadump.update(get_yaml(host))
[10391]1807 datadumps[datadump['autogen_realname']] = datadump
[9283]1808
[10729]1809 (poel, errors) = make_relations(datadumps)
1810 print "\n".join(["# WARNING: %s" % x for x in errors])
[10455]1811
[10156]1812 for host,datadump in datadumps.iteritems():
[10881]1813 try:
1814 # Convert all yes and no to boolean values
1815 def fix_boolean(dump):
1816 for key in dump.keys():
1817 if type(dump[key]) == dict:
1818 dump[key] = fix_boolean(dump[key])
1819 elif str(dump[key]).lower() in ["yes", "true"]:
1820 dump[key] = True
1821 elif str(dump[key]).lower() in ["no", "false"]:
1822 # Compass richting no (Noord Oost) is valid input
1823 if key != "compass": dump[key] = False
1824 return dump
1825 datadump = fix_boolean(datadump)
[10455]1826
[10881]1827 if datadump['rdnap_x'] and datadump['rdnap_y']:
1828 datadump['latitude'], datadump['longitude'] = rdnap.rd2etrs(datadump['rdnap_x'], datadump['rdnap_y'])
1829 elif datadump['latitude'] and datadump['longitude']:
1830 datadump['rdnap_x'], datadump['rdnap_y'] = rdnap.etrs2rd(datadump['latitude'], datadump['longitude'])
[10400]1831
[10881]1832 if datadump['nodename'].startswith('Proxy'):
1833 datadump['nodename'] = datadump['nodename'].lower()
[10319]1834
[10881]1835 for iface_key in datadump['autogen_iface_keys']:
[10889]1836 try:
1837 # All our normal wireless cards are normal APs now
1838 if datadump[iface_key]['type'] in ['11a', '11b', '11g', 'wireless']:
1839 datadump[iface_key]['mode'] = 'ap'
1840 # Wireless Leiden SSID have an consistent lowercase/uppercase
1841 if datadump[iface_key].has_key('ssid'):
1842 ssid = datadump[iface_key]['ssid']
1843 prefix = 'ap-WirelessLeiden-'
1844 if ssid.lower().startswith(prefix.lower()):
1845 datadump[iface_key]['ssid'] = prefix + ssid[len(prefix)].upper() + ssid[len(prefix) + 1:]
1846 if datadump[iface_key].has_key('ns_ip') and not datadump[iface_key].has_key('mode'):
1847 datadump[iface_key]['mode'] = 'autogen-FIXME'
1848 if not datadump[iface_key].has_key('comment'):
1849 datadump[iface_key]['comment'] = 'autogen-FIXME'
[10882]1850
[11732]1851 if datadump[iface_key].has_key('ns_mac'):
1852 datadump[iface_key]['ns_mac'] = datadump[iface_key]['ns_mac'].lower()
1853
[10889]1854 if datadump[iface_key]['comment'].startswith('autogen-') and datadump[iface_key].has_key('comment'):
1855 datadump[iface_key] = datadump[iface_key]['desc']
[10882]1856
[11738]1857 # We are not using 802.11b anymore. OFDM is preferred over DSSS
1858 # due to better collision avoidance.
1859 if datadump[iface_key]['type'] == '11b':
1860 datadump[iface_key]['type'] = '11g'
1861
1862 # Setting 802.11g channels to de-facto standards, to avoid
1863 # un-detected sharing with other overlapping channels
1864 #
1865 # Technically we could also use channel 13 in NL, but this is not
1866 # recommended as foreign devices might not be able to select this
1867 # channel. Secondly using 1,5,9,13 instead is going to clash with
1868 # the de-facto usage of 1,6,11.
1869 #
1870 # See: https://en.wikipedia.org/wiki/List_of_WLAN_channels
1871 channels_at_2400Mhz = (1,6,11)
1872 if datadump[iface_key]['type'] == '11g' and datadump[iface_key].has_key('channel'):
1873 datadump[iface_key]['channel'] = int(datadump[iface_key]['channel'])
1874 if datadump[iface_key]['channel'] not in channels_at_2400Mhz:
1875 datadump[iface_key]['channel'] = random.choice(channels_at_2400Mhz)
1876
[11555]1877 # Mandatory interface keys
1878 if not datadump[iface_key].has_key('status'):
1879 datadump[iface_key]['status'] = 'planned'
1880
[10889]1881 x = datadump[iface_key]['comment']
1882 datadump[iface_key]['comment'] = x[0].upper() + x[1:]
1883
[10884]1884
[10889]1885 if datadump[iface_key].has_key('desc'):
1886 if datadump[iface_key]['comment'].lower() == datadump[iface_key]['desc'].lower():
[10885]1887 del datadump[iface_key]['desc']
[10889]1888 else:
1889 print "# ERROR: At %s - %s" % (datadump['nodename'], iface_key)
1890 response = fix_conflict(datadump[iface_key]['comment'], datadump[iface_key]['desc'])
1891 if response:
1892 datadump[iface_key]['comment'] = response
1893 del datadump[iface_key]['desc']
[10882]1894
[10889]1895 # Check DHCP configuration
1896 dhcp_type(datadump[iface_key])
1897
1898 # Set the compass value based on the angle between the poels
1899 if datadump[iface_key].has_key('ns_ip'):
1900 my_pool = poel[network(datadump[iface_key]['ip'])]
1901 remote_hosts = list(set([x[0] for x in my_pool]) - set([host]))
1902 if remote_hosts:
1903 compass_target = remote_hosts[0]
1904 datadump[iface_key]['compass'] = cd_between_hosts(host, compass_target, datadumps)
1905 except Exception as e:
1906 print "# Error while processing interface %s" % iface_key
1907 raise
[10881]1908 store_yaml(datadump)
1909 except Exception as e:
1910 print "# Error while processing %s" % host
1911 raise
[9971]1912 elif sys.argv[1] == "list":
[10611]1913 use_fqdn = False
[10567]1914 if len(sys.argv) < 4 or not sys.argv[2] in ["up", "down", "planned", "all"]:
1915 usage()
1916 if sys.argv[3] == "nodes":
[9971]1917 systems = get_nodelist()
[10567]1918 elif sys.argv[3] == "proxies":
[9971]1919 systems = get_proxylist()
[10567]1920 elif sys.argv[3] == "systems":
[10270]1921 systems = get_hostlist()
[9971]1922 else:
1923 usage()
[10611]1924 if len(sys.argv) > 4:
1925 if sys.argv[4] == "fqdn":
1926 use_fqdn = True
1927 else:
1928 usage()
1929
[9971]1930 for system in systems:
1931 datadump = get_yaml(system)
[10611]1932
1933 output = datadump['autogen_fqdn'] if use_fqdn else system
[10567]1934 if sys.argv[2] == "all":
[10611]1935 print output
[10567]1936 elif datadump['status'] == sys.argv[2]:
[10611]1937 print output
[10378]1938 elif sys.argv[1] == "create":
1939 if sys.argv[2] == "network.kml":
1940 print make_network_kml.make_graph()
[10998]1941 elif sys.argv[2] == "host-ips.txt":
1942 for system in get_hostlist():
1943 datadump = get_yaml(system)
1944 ips = [datadump['masterip']]
1945 for ifkey in datadump['autogen_iface_keys']:
1946 ips.append(datadump[ifkey]['ip'].split('/')[0])
1947 print system, ' '.join(ips)
[10999]1948 elif sys.argv[2] == "host-pos.txt":
1949 for system in get_hostlist():
1950 datadump = get_yaml(system)
1951 print system, datadump['rdnap_x'], datadump['rdnap_y']
[12233]1952 elif sys.argv[2] == 'ssh_config':
1953 print '''
1954Host *.wleiden.net
1955 User root
1956
1957Host 172.16.*.*
1958 User root
1959'''
1960 for system in get_hostlist():
1961 datadump = get_yaml(system)
1962 print '''\
1963Host %s
1964 User root
1965
1966Host %s
1967 User root
1968
1969Host %s
1970 User root
1971
1972Host %s
1973 User root
1974''' % (system, system.lower(), datadump['nodename'], datadump['nodename'].lower())
[10378]1975 else:
[10998]1976 usage()
1977 else:
[9283]1978 usage()
1979 else:
[10070]1980 # Do not enable debugging for config requests as it highly clutters the output
1981 if not is_text_request():
1982 cgitb.enable()
[11427]1983 response_headers, output = process_cgi_request()
1984 print_cgi_response(response_headers, output)
[9283]1985
[11426]1986def application(environ, start_response):
1987 status = '200 OK'
1988 response_headers, output = process_cgi_request(environ)
1989 start_response(status, response_headers)
[9283]1990
[11426]1991 # Debugging only
1992 # output = 'wsgi.multithread = %s' % repr(environ['wsgi.multithread'])
1993 # soutput += '\nwsgi.multiprocess = %s' % repr(environ['wsgi.multiprocess'])
1994 return [output]
1995
[9283]1996if __name__ == "__main__":
1997 main()
Note: See TracBrowser for help on using the repository browser.