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