source: genesis/tools/gformat.py@ 11498

Last change on this file since 11498 was 11444, checked in by rick, 13 years ago

Quick om export te maken van nodeplanner applicatie.

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