source: genesis/tools/gformat.py@ 11386

Last change on this file since 11386 was 11326, checked in by rick, 12 years ago

Poor mans one-click-nagios-solution-for-light-based-systems.

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