source: genesis/tools/gformat.py@ 12248

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

Making sure all iLeiden proxies will have lvrouted -g flag configured any time
soon. This allows smooth transition to new lvrouted iLeiden default route
management.

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