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