source: genesis/tools/gformat.py@ 13303

Last change on this file since 13303 was 13303, checked in by rick, 10 years ago

Removing old fixed IP configuration used by lvrouted and replacing with the new '-z' feature.

Related-To: beheer#968

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