source: genesis/tools/gformat.py@ 13029

Last change on this file since 13029 was 12787, checked in by rick, 11 years ago

Try to generate current nagios configuration file as seen at sunny

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