source: genesis/tools/gformat.py@ 10109

Last change on this file since 10109 was 10108, checked in by rick, 13 years ago

First error found with unit testing. MasterIP if not used had no comment.

  • Property svn:executable set to *
  • Property svn:keywords set to Id
File size: 30.0 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# Rick van der Zwet <info@rickvanderzwet.nl>
16#
17
18# Hack to make the script directory is also threated as a module search path.
19import sys
20import os
21import re
22sys.path.append(os.path.dirname(__file__))
23
24import cgi
25import cgitb
26import copy
27import glob
28import socket
29import string
30import subprocess
31import time
32import rdnap
33from pprint import pprint
34try:
35 import yaml
36except ImportError, e:
37 print e
38 print "[ERROR] Please install the python-yaml or devel/py-yaml package"
39 exit(1)
40
41try:
42 from yaml import CLoader as Loader
43 from yaml import CDumper as Dumper
44except ImportError:
45 from yaml import Loader, Dumper
46
47import logging
48logging.basicConfig(format='# %(levelname)s: %(message)s' )
49logger = logging.getLogger()
50logger.setLevel(logging.DEBUG)
51
52
53if os.environ.has_key('CONFIGROOT'):
54 NODE_DIR = os.environ['CONFIGROOT']
55else:
56 NODE_DIR = os.path.abspath(os.path.dirname(__file__)) + '/../nodes'
57__version__ = '$Id: gformat.py 10108 2012-03-11 11:41:06Z rick $'
58
59
60files = [
61 'authorized_keys',
62 'dnsmasq.conf',
63 'rc.conf.local',
64 'resolv.conf',
65 'motd',
66 'wleiden.yaml',
67 ]
68
69# Global variables uses
70OK = 10
71DOWN = 20
72UNKNOWN = 90
73
74
75def get_proxylist():
76 """Get all available proxies proxyX sorting based on X number"""
77 proxylist = sorted([os.path.basename(x) for x in glob.glob("%s/proxy*" % NODE_DIR)],
78 key=lambda name: int(''.join([c for c in name if c in string.digits])),
79 cmp=lambda x,y: x - y)
80 return proxylist
81
82
83
84def valid_addr(addr):
85 """ Show which address is valid in which are not """
86 return str(addr).startswith('172.')
87
88
89def get_nodelist():
90 """ Get all available nodes - sorted """
91 nodelist = sorted([os.path.basename(x) for x in glob.glob("%s/CNode*" % NODE_DIR)])
92 return nodelist
93
94def get_hostlist():
95 """ Combined hosts and proxy list"""
96 return get_nodelist() + get_proxylist()
97
98def angle_between_points(lat1,lat2,long1,long2):
99 """
100 Return Angle in radians between two GPS coordinates
101 See: http://stackoverflow.com/questions/3809179/angle-between-2-gps-coordinates
102 """
103 dy = lat2 - lat1
104 dx = math.cos(math.pi/180*lat1)*(long2 - long1)
105 angle = math.atan2(dy,dx)
106 return angle
107
108def angle_to_cd(angle):
109 """ Return Dutch Cardinal Direction estimation in 'one digit' of radian angle """
110
111 # For easy conversion get positive degree
112 degrees = math.degrees(angle)
113 if degrees < 0:
114 360 - abs(degrees)
115
116 # Numbers can be confusing calculate from the 4 main directions
117 p = 22.5
118 if degrees < p:
119 return "n"
120 elif degrees < (90 - p):
121 return "no"
122 elif degrees < (90 + p):
123 return "o"
124 elif degrees < (180 - p):
125 return "zo"
126 elif degrees < (180 + p):
127 return "z"
128 elif degrees < (270 - p):
129 return "zw"
130 elif degrees < (270 + p):
131 return "w"
132 elif degrees < (360 - p):
133 return "nw"
134 else:
135 return "n"
136
137
138def generate_title(nodelist):
139 """ Main overview page """
140 items = {'root' : "." }
141 output = """
142<html>
143 <head>
144 <title>Wireless leiden Configurator - GFormat</title>
145 <style type="text/css">
146 th {background-color: #999999}
147 tr:nth-child(odd) {background-color: #cccccc}
148 tr:nth-child(even) {background-color: #ffffff}
149 th, td {padding: 0.1em 1em}
150 </style>
151 </head>
152 <body>
153 <center>
154 <form type="GET" action="%(root)s">
155 <input type="hidden" name="action" value="update">
156 <input type="submit" value="Update Configuration Database (SVN)">
157 </form>
158 <table>
159 <caption><h3>Wireless Leiden Configurator</h3></caption>
160 """ % items
161
162 for node in nodelist:
163 items['node'] = node
164 output += '<tr><td><a href="%(root)s/%(node)s">%(node)s</a></td>' % items
165 for config in files:
166 items['config'] = config
167 output += '<td><a href="%(root)s/%(node)s/%(config)s">%(config)s</a></td>' % items
168 output += "</tr>"
169 output += """
170 </table>
171 <hr />
172 <em>%s</em>
173 </center>
174 </body>
175</html>
176 """ % __version__
177
178 return output
179
180
181
182def generate_node(node):
183 """ Print overview of all files available for node """
184 return "\n".join(files)
185
186
187
188def generate_header(ctag="#"):
189 return """\
190%(ctag)s
191%(ctag)s DO NOT EDIT - Automatically generated by 'gformat'
192%(ctag)s Generated at %(date)s by %(host)s
193%(ctag)s
194""" % { 'ctag' : ctag, 'date' : time.ctime(), 'host' : socket.gethostname() }
195
196
197
198def parseaddr(s):
199 """ Process IPv4 CIDR notation addr to a (binary) number """
200 f = s.split('.')
201 return (long(f[0]) << 24L) + \
202 (long(f[1]) << 16L) + \
203 (long(f[2]) << 8L) + \
204 long(f[3])
205
206
207
208def showaddr(a):
209 """ Display IPv4 addr in (dotted) CIDR notation """
210 return "%d.%d.%d.%d" % ((a >> 24) & 0xff, (a >> 16) & 0xff, (a >> 8) & 0xff, a & 0xff)
211
212
213def is_member(ip, mask, canidate):
214 """ Return True if canidate is part of ip/mask block"""
215 ip_addr = gformat.parseaddr(ip)
216 ip_canidate = gformat.parseaddr(canidate)
217 mask = int(mask)
218 ip_addr = ip_addr & ~((1 << (32 - mask)) - 1)
219 ip_canidate = ip_canidate & ~((1 << (32 - mask)) - 1)
220 return ip_addr == ip_canidate
221
222
223
224
225def netmask2subnet(netmask):
226 """ Given a 'netmask' return corresponding CIDR """
227 return showaddr(0xffffffff & (0xffffffff << (32 - int(netmask))))
228
229
230
231def generate_dnsmasq_conf(datadump):
232 """ Generate configuration file '/usr/local/etc/dnsmasq.conf' """
233 output = generate_header()
234 output += """\
235# DHCP server options
236dhcp-authoritative
237dhcp-fqdn
238domain=dhcp.%(nodename_lower)s.%(domain)s
239domain-needed
240expand-hosts
241
242# Low memory footprint
243cache-size=10000
244 \n""" % datadump
245
246 for iface_key in datadump['iface_keys']:
247 if not datadump[iface_key].has_key('comment'):
248 datadump[iface_key]['comment'] = None
249 output += "## %(interface)s - %(desc)s - %(comment)s\n" % datadump[iface_key]
250
251 try:
252 (dhcp_start, dhcp_stop) = datadump[iface_key]['dhcp'].split('-')
253 (ip, netmask) = datadump[iface_key]['ip'].split('/')
254 datadump[iface_key]['subnet'] = netmask2subnet(netmask)
255 except (AttributeError, ValueError):
256 output += "# not autoritive\n\n"
257 continue
258
259 dhcp_part = ".".join(ip.split('.')[0:3])
260 datadump[iface_key]['dhcp_start'] = dhcp_part + "." + dhcp_start
261 datadump[iface_key]['dhcp_stop'] = dhcp_part + "." + dhcp_stop
262 output += "dhcp-range=%(interface)s,%(dhcp_start)s,%(dhcp_stop)s,%(subnet)s,24h\n\n" % datadump[iface_key]
263
264 return output
265
266
267
268def generate_rc_conf_local(datadump):
269 """ Generate configuration file '/etc/rc.conf.local' """
270 output = generate_header("#");
271 output += """\
272hostname='%(autogen_fqdn)s.%(domain)s'
273location='%(location)s'
274""" % datadump
275
276 # TProxy configuration
277 output += "\n"
278 try:
279 if datadump['tproxy']:
280 output += """\
281tproxy_enable='YES'
282tproxy_range='%(tproxy)s'
283""" % datadump
284 except KeyError:
285 output += "tproxy_enable='NO'\n"
286
287 # Extra Proxy configuration
288 datadump['ileiden_enable'] = 'yes' if datadump['ileiden'] else 'no'
289 if datadump['nodetype'] == 'Proxy':
290 output += """
291#
292# PROXY Configuration
293#
294sshtun_enable="YES"
295sshtun_flags="-R 22%(proxyid)02i:localhost:22"
296
297static_routes="wleiden"
298route_wleiden="-net 172.16.0.0/12 %(internalroute)s"
299defaultrouter="%(gateway)s"
300
301internalif="%(internalif)s"
302
303# PROXY iLeiden Configuration
304ileiden_enable="%(ileiden_enable)s"
305gateway_enable="%(ileiden_enable)s"
306firewall_enable="%(ileiden_enable)s"
307firewall_script="/etc/ipfw.sh"
308firewall_nat_enable="%(ileiden_enable)s"
309""" % datadump
310
311 if datadump['nodetype'] == 'CNode' and datadump['ileiden']:
312 output += """
313# NODE iLeiden Configuration
314ileiden_enable="%(ileiden_enable)s"
315
316captive_portal_whitelist=""
317captive_portal_interfaces="%(autogen_dhcp_interfaces)s"
318""" % datadump
319
320 # lo0 configuration:
321 # - 172.32.255.1/32 is the proxy.wleiden.net deflector
322 # - masterip is special as it needs to be assigned to at
323 # least one interface, so if not used assign to lo0
324 addrs_list = { 'lo0' : [("127.0.0.1/8", "LocalHost"), ("172.31.255.1/32","Proxy IP")] }
325 iface_map = {'lo0' : 'lo0'}
326
327 masterip_used = False
328 for iface_key in datadump['iface_keys']:
329 if datadump[iface_key]['ip'].startswith(datadump['masterip']):
330 masterip_used = True
331 break
332 if not masterip_used:
333 addrs_list['lo0'].append((datadump['masterip'] + "/32", 'Master IP Not used in interface'))
334
335 for iface_key in datadump['iface_keys']:
336 ifacedump = datadump[iface_key]
337 interface = ifacedump['interface'].split(':')[0]
338 # By default no special interface mapping
339 iface_map[interface] = interface
340
341 # Add interface IP to list
342 item = (ifacedump['ip'], ifacedump['desc'])
343 if addrs_list.has_key(interface):
344 addrs_list[interface].append(item)
345 else:
346 addrs_list[interface] = [item]
347
348 # Alias only needs IP assignment for now, this might change if we
349 # are going to use virtual accesspoints
350 if "alias" in iface_key:
351 continue
352
353 # XXX: Might want to deduct type directly from interface name
354 if ifacedump['type'] in ['11a', '11b', '11g', 'wireless']:
355 # Default to station (client) mode
356 ifacedump['wlanmode'] = "sta"
357 if ifacedump['mode'] in ['master', 'master-wds']:
358 ifacedump['wlanmode'] = "ap"
359 # Default to 802.11b mode
360 ifacedump['mode'] = '11b'
361 if ifacedump['type'] in ['11a', '11b' '11g']:
362 ifacedump['mode'] = ifacedump['type']
363
364 if not ifacedump.has_key('channel'):
365 if ifacedump['type'] == '11a':
366 ifacedump['channel'] = 36
367 else:
368 ifacedump['channel'] = 1
369
370 # Allow special hacks at the back like wds and stuff
371 if not ifacedump.has_key('extra'):
372 ifacedump['extra'] = 'regdomain ETSI country NL'
373
374 output += "wlans_%(interface)s='%(autogen_ifname)s'\n" % ifacedump
375 output += ("create_args_%(autogen_ifname)s='wlanmode %(wlanmode)s mode " +\
376 "%(mode)s ssid %(ssid)s %(extra)s channel %(channel)s'\n") % ifacedump
377
378 elif ifacedump['type'] in ['ethernet', 'eth']:
379 # No special config needed besides IP
380 pass
381 else:
382 assert False, "Unknown type " + ifacedump['type']
383
384 # Print IP address which needs to be assigned over here
385 output += "\n"
386 for iface,addrs in sorted(addrs_list.iteritems()):
387 for addr, comment in sorted(addrs,key=lambda x: parseaddr(x[0].split('/')[0])):
388 ifacedump['iface'] = iface
389 output += "# %s || %s || %s\n" % (iface, addr, comment)
390 output += "ipv4_addrs_%s='%s'\n\n" % (iface_map[iface], " ".join([x[0] for x in addrs]))
391
392 return output
393
394
395
396def get_yaml(item):
397 """ Get configuration yaml for 'item'"""
398 gfile = os.path.join(NODE_DIR,item,'wleiden.yaml')
399
400 f = open(gfile, 'r')
401 datadump = yaml.load(f,Loader=Loader)
402 datadump['autogen_iface_keys'] = get_interface_keys(datadump)
403
404 wlan_count=0
405 for key in datadump['autogen_iface_keys']:
406 if datadump[key]['type'] in ['11a', '11b', '11g', 'wireless']:
407 datadump[key]['autogen_ifname'] = 'wlan%i' % wlan_count
408 wlan_count += 1
409 else:
410 datadump[key]['autogen_ifname'] = datadump[key]['interface']
411
412
413 dhcp_interfaces = [datadump[key]['autogen_ifname'] for key in datadump['autogen_iface_keys'] if datadump[key]['dhcp'] != 'no']
414 datadump['autogen_dhcp_interfaces'] = ' '.join(dhcp_interfaces)
415 datadump['autogen_item'] = item
416 datadump['autogen_fqdn'] = get_fqdn(datadump)
417 f.close()
418
419 return datadump
420
421def store_yaml(datadump, header=False):
422 """ Store configuration yaml for 'item'"""
423 item = datadump['autogen_item']
424 gfile = os.path.join(NODE_DIR,item,'wleiden.yaml')
425
426 f = open(gfile, 'w')
427 f.write(generate_wleiden_yaml(datadump, header))
428 f.close()
429
430
431
432def get_all_configs():
433 """ Get dict with key 'host' with all configs present """
434 configs = dict()
435 for host in get_hostlist():
436 datadump = get_yaml(host)
437 configs[host] = datadump
438 return configs
439
440
441def get_interface_keys(config):
442 """ Quick hack to get all interface keys, later stage convert this to a iterator """
443 return sorted([elem for elem in config.keys() if (elem.startswith('iface_') and not "lo0" in elem)])
444
445
446def get_used_ips(configs):
447 """ Return array of all IPs used in config files"""
448 ip_list = []
449 for config in configs:
450 ip_list.append(config['masterip'])
451 for iface_key in get_interface_keys(config):
452 l = config[iface_key]['ip']
453 addr, mask = l.split('/')
454 # Special case do not process
455 if valid_addr(addr):
456 ip_list.append(addr)
457 else:
458 logger.error("## IP '%s' in '%s' not valid" % (addr, config['nodename']))
459 return sorted(ip_list)
460
461
462
463def generate_resolv_conf(datadump):
464 """ Generate configuration file '/etc/resolv.conf' """
465 output = generate_header("#");
466 output += """\
467search wleiden.net
468# Try local (cache) first
469nameserver 127.0.0.1
470"""
471 if datadump['nodetype'] == 'Proxy':
472 output += """\
473nameserver 8.8.8.8 # Google Public NameServer
474nameserver 8.8.4.4 # Google Public NameServer
475"""
476 else:
477 output += """\
478# Proxies are recursive nameservers
479# needs to be in resolv.conf for dnsmasq as well
480""" % datadump
481 for proxy in get_proxylist():
482 proxy_ip = get_yaml(proxy)['masterip']
483 output += "nameserver %-15s # %s\n" % (proxy_ip, proxy)
484
485 return output
486
487def generate_motd(datadump):
488 """ Generate configuration file '/etc/motd' """
489 output = """\
490FreeBSD 9.0-RELEASE (kernel.wleiden) #0 r230587: Sun Jan 29 17:09:57 CET 2012
491
492 WWW: %(autogen_fqdn)s.wleiden.net - http://www.wirelessleiden.nl
493
494Interlinks:
495""" % datadump
496
497 # XXX: This is a hacky way to get the required data
498 for line in generate_rc_conf_local(datadump).split('\n'):
499 if '||' in line and not line[1:].split()[0] in ['lo0', 'ath0'] :
500 output += " - %s \n" % line[1:]
501 output += """\
502Attached bridges:
503"""
504 for iface_key in datadump['autogen_iface_keys']:
505 ifacedump = datadump[iface_key]
506 if ifacedump.has_key('ns_ip'):
507 output += " - %(interface)s || %(mode)s || %(ns_ip)s\n" % ifacedump
508
509 return output
510
511
512def format_yaml_value(value):
513 """ Get yaml value in right syntax for outputting """
514 if isinstance(value,str):
515 output = '"%s"' % value
516 else:
517 output = value
518 return output
519
520
521
522def format_wleiden_yaml(datadump):
523 """ Special formatting to ensure it is editable"""
524 output = "# Genesis config yaml style\n"
525 output += "# vim:ts=2:et:sw=2:ai\n"
526 output += "#\n"
527 iface_keys = [elem for elem in datadump.keys() if elem.startswith('iface_')]
528 for key in sorted(set(datadump.keys()) - set(iface_keys)):
529 output += "%-10s: %s\n" % (key, format_yaml_value(datadump[key]))
530
531 output += "\n\n"
532
533 key_order = [ 'comment', 'interface', 'ip', 'desc', 'sdesc', 'mode', 'type',
534 'extra_type', 'channel', 'ssid', 'dhcp' ]
535
536 for iface_key in sorted(iface_keys):
537 output += "%s:\n" % iface_key
538 for key in key_order + list(sorted(set(datadump[iface_key].keys()) - set(key_order))):
539 if datadump[iface_key].has_key(key):
540 output += " %-11s: %s\n" % (key, format_yaml_value(datadump[iface_key][key]))
541 output += "\n\n"
542
543 return output
544
545
546
547def generate_wleiden_yaml(datadump, header=True):
548 """ Generate (petty) version of wleiden.yaml"""
549 for key in datadump.keys():
550 if key.startswith('autogen_'):
551 del datadump[key]
552 # Interface autogen cleanups
553 elif type(datadump[key]) == dict:
554 for key2 in datadump[key].keys():
555 if key2.startswith('autogen_'):
556 del datadump[key][key2]
557
558 output = generate_header("#") if header else ''
559 output += format_wleiden_yaml(datadump)
560 return output
561
562
563def generate_yaml(datadump):
564 return generate_config(datadump['nodename'], "wleiden.yaml", datadump)
565
566
567
568def generate_config(node, config, datadump=None):
569 """ Print configuration file 'config' of 'node' """
570 output = ""
571 try:
572 # Load config file
573 if datadump == None:
574 datadump = get_yaml(node)
575
576 # Preformat certain needed variables for formatting and push those into special object
577 datadump_extra = copy.deepcopy(datadump)
578 if not datadump_extra.has_key('domain'):
579 datadump_extra['domain'] = 'wleiden.net'
580 datadump_extra['nodename_lower'] = datadump_extra['nodename'].lower()
581 datadump_extra['iface_keys'] = sorted([elem for elem in datadump.keys() if elem.startswith('iface_')])
582
583 if config == 'wleiden.yaml':
584 output += generate_wleiden_yaml(datadump)
585 elif config == 'authorized_keys':
586 f = open(os.path.join(NODE_DIR,"global_keys"), 'r')
587 output += f.read()
588 f.close()
589 elif config == 'dnsmasq.conf':
590 output += generate_dnsmasq_conf(datadump_extra)
591 elif config == 'rc.conf.local':
592 output += generate_rc_conf_local(datadump_extra)
593 elif config == 'resolv.conf':
594 output += generate_resolv_conf(datadump_extra)
595 elif config == 'motd':
596 output += generate_motd(datadump_extra)
597 else:
598 assert False, "Config not found!"
599 except IOError, e:
600 output += "[ERROR] Config file not found"
601 return output
602
603
604
605def process_cgi_request():
606 """ When calling from CGI """
607 # Update repository if requested
608 form = cgi.FieldStorage()
609 if form.getvalue("action") == "update":
610 print "Refresh: 5; url=."
611 print "Content-type:text/plain\r\n\r\n",
612 print "[INFO] Updating subverion, please wait..."
613 print subprocess.Popen(['svn', 'up', "%s/.." % NODE_DIR], stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0],
614 print "[INFO] All done, redirecting in 5 seconds"
615 sys.exit(0)
616
617
618 uri = os.environ['PATH_INFO'].strip('/').split('/')
619 output = ""
620 if not uri[0]:
621 if is_text_request():
622 output += "Content-type:text/plain\r\n\r\n"
623 output += '\n'.join(get_hostlist())
624 else:
625 output += "Content-type:text/html\r\n\r\n"
626 output += generate_title(get_hostlist())
627 elif len(uri) == 1:
628 output += "Content-type:text/plain\r\n\r\n"
629 output += generate_node(uri[0])
630 elif len(uri) == 2:
631 output += "Content-type:text/plain\r\n\r\n"
632 output += generate_config(uri[0], uri[1])
633 else:
634 assert False, "Invalid option"
635 print output
636
637def get_fqdn(datadump):
638 # Proxy naming convention is special
639 if datadump['nodetype'] == 'Proxy':
640 fqdn = datadump['nodename']
641 else:
642 # By default the full name is listed and also a shortname CNAME for easy use.
643 fqdn = datadump['nodetype'] + datadump['nodename']
644 return(fqdn)
645
646
647
648def make_dns(output_dir = 'dns'):
649 items = dict()
650
651 # hostname is key, IP is value
652 wleiden_zone = dict()
653 wleiden_cname = dict()
654
655 pool = dict()
656 for node in get_hostlist():
657 logger.info("Processing host %s", node)
658 datadump = get_yaml(node)
659
660 # Proxy naming convention is special
661 fqdn = get_fqdn(datadump)
662 if datadump['nodetype'] == 'CNode':
663 wleiden_cname[datadump['nodename']] = fqdn
664
665 wleiden_zone[fqdn] = datadump['masterip']
666
667 # Hacking to get proper DHCP IPs and hostnames
668 for iface_key in get_interface_keys(datadump):
669 iface_name = datadump[iface_key]['interface'].replace(':',"-alias-")
670 (ip, netmask) = datadump[iface_key]['ip'].split('/')
671 try:
672 (dhcp_start, dhcp_stop) = datadump[iface_key]['dhcp'].split('-')
673 datadump[iface_key]['subnet'] = netmask2subnet(netmask)
674 dhcp_part = ".".join(ip.split('.')[0:3])
675 if ip != datadump['masterip']:
676 wleiden_zone["dhcp-gateway-%s.%s" % (iface_name, fqdn)] = ip
677 for i in range(int(dhcp_start), int(dhcp_stop) + 1):
678 wleiden_zone["dhcp-%s-%s.%s" % (i, iface_name, fqdn)] = "%s.%s" % (dhcp_part, i)
679 except (AttributeError, ValueError):
680 # First push it into a pool, to indentify the counter-part later on
681 addr = parseaddr(ip)
682 netmask = int(netmask)
683 addr = addr & ~((1 << (32 - netmask)) - 1)
684 if pool.has_key(addr):
685 pool[addr] += [(iface_name, fqdn, ip)]
686 else:
687 pool[addr] = [(iface_name, fqdn, ip)]
688 continue
689
690
691 def pool_to_name(node, pool_members):
692 """Convert the joined name to a usable pool name"""
693
694 # Get rid of the own entry
695 pool_members = list(set(pool_members) - set([fqdn]))
696
697 target = oldname = ''
698 for node in sorted(pool_members):
699 (name, number) = re.match('^([A-Za-z]+)([0-9]*)$',node).group(1,2)
700 target += "-" + number if name == oldname else "-" + node if target else node
701 oldname = name
702
703 return target
704
705
706 # WL uses an /29 to configure an interface. IP's are ordered like this:
707 # MasterA (.1) -- DeviceA (.2) <<>> DeviceB (.3) --- SlaveB (.4)
708
709 sn = lambda x: re.sub(r'(?i)^cnode','',x)
710
711 # Automatic naming convention of interlinks namely 2 + remote.lower()
712 for (key,value) in pool.iteritems():
713 # Make sure they are sorted from low-ip to high-ip
714 value = sorted(value, key=lambda x: parseaddr(x[2]))
715
716 if len(value) == 1:
717 (iface_name, fqdn, ip) = value[0]
718 wleiden_zone["2unused-%s.%s" % (iface_name, fqdn)] = ip
719
720 # Device DNS names
721 if 'cnode' in fqdn.lower():
722 wleiden_zone["d-at-%s.%s" % (iface_name, fqdn)] = showaddr(parseaddr(ip) + 1)
723 wleiden_cname["d-at-%s.%s" % (iface_name,sn(fqdn))] = "d-at-%s.%s" % (iface_name, fqdn)
724
725 elif len(value) == 2:
726 (a_iface_name, a_fqdn, a_ip) = value[0]
727 (b_iface_name, b_fqdn, b_ip) = value[1]
728 wleiden_zone["2%s.%s" % (b_fqdn,a_fqdn)] = a_ip
729 wleiden_zone["2%s.%s" % (a_fqdn,b_fqdn)] = b_ip
730
731 # Device DNS names
732 if 'cnode' in a_fqdn.lower() and 'cnode' in b_fqdn.lower():
733 wleiden_zone["d-at-%s.%s" % (a_iface_name, a_fqdn)] = showaddr(parseaddr(a_ip) + 1)
734 wleiden_zone["d-at-%s.%s" % (b_iface_name, b_fqdn)] = showaddr(parseaddr(b_ip) - 1)
735 wleiden_cname["d-at-%s.%s" % (a_iface_name,sn(a_fqdn))] = "d-at-%s.%s" % (a_iface_name, a_fqdn)
736 wleiden_cname["d-at-%s.%s" % (b_iface_name,sn(b_fqdn))] = "d-at-%s.%s" % (b_iface_name, b_fqdn)
737 wleiden_cname["d2%s.%s" % (sn(b_fqdn),sn(a_fqdn))] = "d-at-%s.%s" % (a_iface_name, a_fqdn)
738 wleiden_cname["d2%s.%s" % (sn(a_fqdn),sn(b_fqdn))] = "d-at-%s.%s" % (b_iface_name, b_fqdn)
739
740 else:
741 pool_members = [k[1] for k in value]
742 for item in value:
743 (iface_name, fqdn, ip) = item
744 pool_name = "2pool-" + showaddr(key).replace('.','-') + "-" + pool_to_name(fqdn,pool_members)
745 wleiden_zone["%s.%s" % (pool_name, fqdn)] = ip
746
747 # Include static DNS entries
748 # XXX: Should they override the autogenerated results?
749 # XXX: Convert input to yaml more useable.
750 # Format:
751 ##; this is a comment
752 ## roomburgh=CNodeRoomburgh1
753 ## apkerk1.CNodeVosko=172.17.176.8 ;this as well
754 dns = yaml.load(open(os.path.join(NODE_DIR,'../dns/staticDNS.yaml'),'r'))
755
756 # Hack to allow special entries, for development
757 wleiden_raw = dns['raw']
758 del dns['raw']
759
760 for comment, block in dns.iteritems():
761 for k,v in block.iteritems():
762 if valid_addr(v):
763 wleiden_zone[k] = v
764 else:
765 wleiden_cname[k] = v
766
767 details = dict()
768 # 24 updates a day allowed
769 details['serial'] = time.strftime('%Y%m%d%H')
770
771 dns_header = '''
772$TTL 3h
773%(zone)s. SOA sunny.wleiden.net. beheer.lijst.wirelessleiden.nl. ( %(serial)s 1d 12h 1w 3h )
774 ; Serial, Refresh, Retry, Expire, Neg. cache TTL
775
776 NS sunny.wleiden.net.
777 \n'''
778
779
780 if not os.path.isdir('dns'):
781 os.makedirs('dns')
782 details['zone'] = 'wleiden.net'
783 f = open(os.path.join(output_dir,"db." + details['zone']), "w")
784 f.write(dns_header % details)
785
786 for host,ip in wleiden_zone.iteritems():
787 if valid_addr(ip):
788 f.write("%s.wleiden.net. IN A %s \n" % (host.lower(), ip))
789 for source,dest in wleiden_cname.iteritems():
790 f.write("%s.wleiden.net. IN CNAME %s.wleiden.net.\n" % (source.lower(), dest.lower()))
791 for source, dest in wleiden_raw.iteritems():
792 f.write("%s.wleiden.net. %s\n" % (source, dest))
793 f.close()
794
795 # Create whole bunch of specific sub arpa zones. To keep it compliant
796 for s in range(16,32):
797 details['zone'] = '%i.172.in-addr.arpa' % s
798 f = open(os.path.join(output_dir,"db." + details['zone']), "w")
799 f.write(dns_header % details)
800
801 #XXX: Not effient, fix to proper data structure and do checks at other
802 # stages
803 for host,ip in wleiden_zone.iteritems():
804 if valid_addr(ip):
805 if int(ip.split('.')[1]) == s:
806 rev_ip = '.'.join(reversed(ip.split('.')))
807 f.write("%s.in-addr.arpa. IN PTR %s.wleiden.net.\n" % (rev_ip.lower(), host.lower()))
808 f.close()
809
810
811def usage():
812 print """Usage: %s <standalone [port] |test [test arguments]|static|dns>
813Examples:
814\tdns [outputdir] = Generate BIND compliant zone files in dns.
815\tstandalone = Run configurator webserver [default port=8000]
816\twind-export = Generate SQL import scripts for WIND database
817\tfull-export = Generate yaml export script for heatmap.
818\tstatic = Generate all config files and store on disk
819\t with format ./static/%%NODE%%/%%FILE%%
820\ttest CNodeRick dnsmasq.conf = Receive output of CGI script
821\t for arguments CNodeRick/dnsmasq.conf
822\tlist <nodes|proxies> = List systems which marked up.
823"""
824 exit(0)
825
826
827def is_text_request():
828 """ Find out whether we are calling from the CLI or any text based CLI utility """
829 try:
830 return os.environ['HTTP_USER_AGENT'].split()[0] in ['curl', 'fetch', 'wget']
831 except KeyError:
832 return True
833
834def main():
835 """Hard working sub"""
836 # Allow easy hacking using the CLI
837 if not os.environ.has_key('PATH_INFO'):
838 if len(sys.argv) < 2:
839 usage()
840
841 if sys.argv[1] == "standalone":
842 import SocketServer
843 import CGIHTTPServer
844 # Hop to the right working directory.
845 os.chdir(os.path.dirname(__file__))
846 try:
847 PORT = int(sys.argv[2])
848 except (IndexError,ValueError):
849 PORT = 8000
850
851 class MyCGIHTTPRequestHandler(CGIHTTPServer.CGIHTTPRequestHandler):
852 """ Serve this CGI from the root of the webserver """
853 def is_cgi(self):
854 if "favicon" in self.path:
855 return False
856
857 self.cgi_info = (__file__, self.path)
858 self.path = ''
859 return True
860 handler = MyCGIHTTPRequestHandler
861 SocketServer.TCPServer.allow_reuse_address = True
862 httpd = SocketServer.TCPServer(("", PORT), handler)
863 httpd.server_name = 'localhost'
864 httpd.server_port = PORT
865
866 logger.info("serving at port %s", PORT)
867 try:
868 httpd.serve_forever()
869 except KeyboardInterrupt:
870 httpd.shutdown()
871 logger.info("All done goodbye")
872 elif sys.argv[1] == "test":
873 os.environ['PATH_INFO'] = "/".join(sys.argv[2:])
874 os.environ['SCRIPT_NAME'] = __file__
875 process_cgi_request()
876 elif sys.argv[1] == "unit-test":
877 os.environ['SCRIPT_NAME'] = __file__
878 for host in get_hostlist():
879 for outfile in files:
880 os.environ['PATH_INFO'] = "/".join([host,outfile])
881 try:
882 process_cgi_request()
883 except Exception:
884 print "# ERROR: %s" % os.environ['PATH_INFO']
885 raise
886
887
888 elif sys.argv[1] == "static":
889 items = dict()
890 for node in get_hostlist():
891 items['node'] = node
892 items['wdir'] = "./static/%(node)s" % items
893 if not os.path.isdir(items['wdir']):
894 os.makedirs(items['wdir'])
895 datadump = get_yaml(node)
896 for config in files:
897 items['config'] = config
898 logger.info("## Generating %(node)s %(config)s" % items)
899 f = open("%(wdir)s/%(config)s" % items, "w")
900 f.write(generate_config(node, config, datadump))
901 f.close()
902 elif sys.argv[1] == "wind-export":
903 items = dict()
904 for node in get_hostlist():
905 datadump = get_yaml(node)
906 sql = """INSERT IGNORE INTO nodes (name, name_ns, longitude, latitude)
907 VALUES ('%(nodename)s', '%(nodename)s', %(latitude)s, %(longitude)s);""" % datadump;
908 sql = """INSERT IGNORE INTO users_nodes (user_id, node_id, owner)
909 VALUES (
910 (SELECT id FROM users WHERE username = 'rvdzwet'),
911 (SELECT id FROM nodes WHERE name = '%(nodename)s'),
912 'Y');""" % datadump
913 #for config in files:
914 # items['config'] = config
915 # print "## Generating %(node)s %(config)s" % items
916 # f = open("%(wdir)s/%(config)s" % items, "w")
917 # f.write(generate_config(node, config, datadump))
918 # f.close()
919 for node in get_hostlist():
920 datadump = get_yaml(node)
921 for iface_key in sorted([elem for elem in datadump.keys() if elem.startswith('iface_')]):
922 ifacedump = datadump[iface_key]
923 if ifacedump.has_key('mode') and ifacedump['mode'] == 'ap-wds':
924 ifacedump['nodename'] = datadump['nodename']
925 if not ifacedump.has_key('channel') or not ifacedump['channel']:
926 ifacedump['channel'] = 0
927 sql = """INSERT INTO links (node_id, type, ssid, protocol, channel, status)
928 VALUES ((SELECT id FROM nodes WHERE name = '%(nodename)s'), 'ap',
929 '%(ssid)s', 'IEEE 802.11b', %(channel)s, 'active');""" % ifacedump
930 elif sys.argv[1] == "full-export":
931 hosts = {}
932 for node in get_hostlist():
933 datadump = get_yaml(node)
934 hosts[datadump['nodename']] = datadump
935 print yaml.dump(hosts)
936
937 elif sys.argv[1] == "dns":
938 make_dns(sys.argv[2] if len(sys.argv) > 2 else 'dns')
939 elif sys.argv[1] == "cleanup":
940 # First generate all datadumps
941 datadumps = dict()
942 for host in get_hostlist():
943 logger.info("# Processing: %s", host)
944 datadump = get_yaml(host)
945 datadumps[get_fqdn(datadump)] = datadump
946
947 for key,datadump in datadumps.iteritems():
948 datadump['latitude'], datadump['longitude'] = rdnap.rd2etrs(datadump['rdnap_x'], datadump['rdnap_y'])
949 store_yaml(datadump)
950 elif sys.argv[1] == "list":
951 if sys.argv[2] == "nodes":
952 systems = get_nodelist()
953 elif sys.argv[2] == "proxies":
954 systems = get_proxylist()
955 else:
956 usage()
957 for system in systems:
958 datadump = get_yaml(system)
959 if datadump['status'] == "up":
960 print system
961 else:
962 usage()
963 else:
964 # Do not enable debugging for config requests as it highly clutters the output
965 if not is_text_request():
966 cgitb.enable()
967 process_cgi_request()
968
969
970if __name__ == "__main__":
971 main()
Note: See TracBrowser for help on using the repository browser.