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