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