source: genesis/tools/gformat.py@ 12224

Last change on this file since 12224 was 11740, checked in by rick, 12 years ago

Making sure that 11g actually gets set, not sure why to hard-code it back to some boring default.

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