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