source: genesis/tools/gformat.py@ 12224

Last change on this file since 12224 was 11740, checked in by rick, 12 years ago

Making sure that 11g actually gets set, not sure why to hard-code it back to some boring default.

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