source: genesis/tools/gformat.py@ 10071

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

Lazy update functionality.

  • Property svn:executable set to *
  • Property svn:keywords set to Id
File size: 29.5 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 10071 2012-03-09 21:20:56Z 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"
299
300internalif="%(internalif)s"
301
302# PROXY iLeiden Configuration
303ileiden_enable="%(ileiden_enable)s"
304gateway_enable="%(ileiden_enable)s"
305firewall_enable="%(ileiden_enable)s"
306firewall_script="/etc/ipfw.sh"
307firewall_nat_enable="%(ileiden_enable)s"
308""" % datadump
309
310 if datadump['nodetype'] == 'CNode' and datadump['ileiden']:
311 output += """
312# NODE iLeiden Configuration
313ileiden_enable="%(ileiden_enable)s"
314
315captive_portal_whitelist=""
316captive_portal_interfaces="%(autogen_dhcp_interfaces)s"
317""" % datadump
318
319 # lo0 configuration:
320 # - 172.32.255.1/32 is the proxy.wleiden.net deflector
321 # - masterip is special as it needs to be assigned to at
322 # least one interface, so if not used assign to lo0
323 addrs_list = { 'lo0' : [("127.0.0.1/8", "LocalHost"), ("172.31.255.1/32","Proxy IP")] }
324 iface_map = {'lo0' : 'lo0'}
325
326 masterip_used = False
327 for iface_key in datadump['iface_keys']:
328 if datadump[iface_key]['ip'].startswith(datadump['masterip']):
329 masterip_used = True
330 break
331 if not masterip_used:
332 addrs_list['lo0'].append(datadump['masterip'] + "/32")
333
334 for iface_key in datadump['iface_keys']:
335 ifacedump = datadump[iface_key]
336 interface = ifacedump['interface']
337 # By default no special interface mapping
338 iface_map[interface] = interface
339
340 # Add interface IP to list
341 item = (ifacedump['ip'], ifacedump['desc'])
342 if addrs_list.has_key(interface):
343 addrs_list[interface].append(item)
344 else:
345 addrs_list[interface] = [item]
346
347 # Alias only needs IP assignment for now, this might change if we
348 # are going to use virtual accesspoints
349 if "alias" in iface_key:
350 continue
351
352 # XXX: Might want to deduct type directly from interface name
353 if ifacedump['type'] in ['11a', '11b', '11g', 'wireless']:
354 # Default to station (client) mode
355 ifacedump['wlanmode'] = "sta"
356 if ifacedump['mode'] in ['master', 'master-wds']:
357 ifacedump['wlanmode'] = "ap"
358 # Default to 802.11b mode
359 ifacedump['mode'] = '11b'
360 if ifacedump['type'] in ['11a', '11b' '11g']:
361 ifacedump['mode'] = ifacedump['type']
362
363 if not ifacedump.has_key('channel'):
364 if ifacedump['type'] == '11a':
365 ifacedump['channel'] = 36
366 else:
367 ifacedump['channel'] = 1
368
369 # Allow special hacks at the back like wds and stuff
370 if not ifacedump.has_key('extra'):
371 ifacedump['extra'] = 'regdomain ETSI country NL'
372
373 output += "wlans_%(interface)s='%(autogen_ifname)s'\n" % ifacedump
374 output += ("create_args_%(autogen_ifname)s='wlanmode %(wlanmode)s mode " +\
375 "%(mode)s ssid %(ssid)s %(extra)s channel %(channel)s'\n") % ifacedump
376
377 elif ifacedump['type'] in ['ethernet', 'eth']:
378 # No special config needed besides IP
379 pass
380 else:
381 assert False, "Unknown type " + ifacedump['type']
382
383 # Print IP address which needs to be assigned over here
384 output += "\n"
385 for iface,addrs in sorted(addrs_list.iteritems()):
386 for addr, comment in addrs:
387 ifacedump['iface'] = iface
388 output += "# %s || %s || %s\n" % (iface, addr, comment)
389 output += "ipv4_addrs_%s='%s'\n\n" % (iface_map[iface], " ".join([x[0] for x in addrs]))
390
391 return output
392
393
394
395def get_yaml(item):
396 """ Get configuration yaml for 'item'"""
397 gfile = os.path.join(NODE_DIR,item,'wleiden.yaml')
398
399 f = open(gfile, 'r')
400 datadump = yaml.load(f,Loader=Loader)
401 datadump['autogen_iface_keys'] = get_interface_keys(datadump)
402
403 wlan_count=0
404 for key in datadump['autogen_iface_keys']:
405 if datadump[key]['type'] in ['11a', '11b', '11g', 'wireless']:
406 datadump[key]['autogen_ifname'] = 'wlan%i' % wlan_count
407 wlan_count += 1
408 else:
409 datadump[key]['autogen_ifname'] = datadump[key]['interface']
410
411
412 dhcp_interfaces = [datadump[key]['autogen_ifname'] for key in datadump['autogen_iface_keys'] if datadump[key]['dhcp'] != 'no']
413 datadump['autogen_dhcp_interfaces'] = ' '.join(dhcp_interfaces)
414 datadump['autogen_item'] = item
415 datadump['autogen_fqdn'] = get_fqdn(datadump)
416 f.close()
417
418 return datadump
419
420def store_yaml(datadump, header=True):
421 """ Store configuration yaml for 'item'"""
422 item = datadump['autogen_item']
423 gfile = os.path.join(NODE_DIR,item,'wleiden.yaml')
424
425 f = open(gfile, 'w')
426 f.write(generate_wleiden_yaml(datadump, header))
427 f.close()
428
429
430
431def get_all_configs():
432 """ Get dict with key 'host' with all configs present """
433 configs = dict()
434 for host in get_hostlist():
435 datadump = get_yaml(host)
436 configs[host] = datadump
437 return configs
438
439
440def get_interface_keys(config):
441 """ Quick hack to get all interface keys, later stage convert this to a iterator """
442 return sorted([elem for elem in config.keys() if (elem.startswith('iface_') and not "lo0" in elem)])
443
444
445def get_used_ips(configs):
446 """ Return array of all IPs used in config files"""
447 ip_list = []
448 for config in configs:
449 ip_list.append(config['masterip'])
450 for iface_key in get_interface_keys(config):
451 l = config[iface_key]['ip']
452 addr, mask = l.split('/')
453 # Special case do not process
454 if valid_addr(addr):
455 ip_list.append(addr)
456 else:
457 logger.error("## IP '%s' in '%s' not valid" % (addr, config['nodename']))
458 return sorted(ip_list)
459
460
461
462def generate_resolv_conf(datadump):
463 """ Generate configuration file '/etc/resolv.conf' """
464 output = generate_header("#");
465 output += """\
466search wleiden.net
467# Try local (cache) first
468nameserver 127.0.0.1
469"""
470 if datadump['nodetype'] == 'Proxy':
471 output += """\
472nameserver 8.8.8.8 # Google Public NameServer
473nameserver 8.8.4.4 # Google Public NameServer
474"""
475 else:
476 output += """\
477# Proxies are recursive nameservers
478# needs to be in resolv.conf for dnsmasq as well
479""" % datadump
480 for proxy in get_proxylist():
481 proxy_ip = get_yaml(proxy)['masterip']
482 output += "nameserver %-15s # %s\n" % (proxy_ip, proxy)
483
484 return output
485
486def generate_motd(datadump):
487 """ Generate configuration file '/etc/motd' """
488 output = """\
489FreeBSD 9.0-RELEASE (kernel.wleiden) #0 r230587: Sun Jan 29 17:09:57 CET 2012
490
491 WWW: %(autogen_fqdn)s.wleiden.net - http://www.wirelessleiden.nl
492
493Interlinks:
494""" % datadump
495
496 # XXX: This is a hacky way to get the required data
497 for line in generate_rc_conf_local(datadump).split('\n'):
498 if '||' in line and not line[1:].split()[0] in ['lo0', 'ath0'] :
499 output += " - %s \n" % line[1:]
500 output += """\
501Attached bridges:
502"""
503 for iface_key in datadump['autogen_iface_keys']:
504 ifacedump = datadump[iface_key]
505 if ifacedump.has_key('ns_ip'):
506 output += " - %(interface)s || %(mode)s || %(ns_ip)s\n" % ifacedump
507
508 return output
509
510
511def format_yaml_value(value):
512 """ Get yaml value in right syntax for outputting """
513 if isinstance(value,str):
514 output = '"%s"' % value
515 else:
516 output = value
517 return output
518
519
520
521def format_wleiden_yaml(datadump):
522 """ Special formatting to ensure it is editable"""
523 output = "# Genesis config yaml style\n"
524 output += "# vim:ts=2:et:sw=2:ai\n"
525 output += "#\n"
526 iface_keys = [elem for elem in datadump.keys() if elem.startswith('iface_')]
527 for key in sorted(set(datadump.keys()) - set(iface_keys)):
528 output += "%-10s: %s\n" % (key, format_yaml_value(datadump[key]))
529
530 output += "\n\n"
531
532 key_order = [ 'comment', 'interface', 'ip', 'desc', 'sdesc', 'mode', 'type',
533 'extra_type', 'channel', 'ssid', 'dhcp' ]
534
535 for iface_key in sorted(iface_keys):
536 output += "%s:\n" % iface_key
537 for key in key_order + list(sorted(set(datadump[iface_key].keys()) - set(key_order))):
538 if datadump[iface_key].has_key(key):
539 output += " %-11s: %s\n" % (key, format_yaml_value(datadump[iface_key][key]))
540 output += "\n\n"
541
542 return output
543
544
545
546def generate_wleiden_yaml(datadump, header=True):
547 """ Generate (petty) version of wleiden.yaml"""
548 for key in datadump.keys():
549 if key.startswith('autogen_'):
550 del datadump[key]
551 # Interface autogen cleanups
552 elif type(datadump[key]) == dict:
553 for key2 in datadump[key].keys():
554 if key2.startswith('autogen_'):
555 del datadump[key][key2]
556
557 output = generate_header("#") if header else ''
558 output += format_wleiden_yaml(datadump)
559 return output
560
561
562def generate_yaml(datadump):
563 return generate_config(datadump['nodename'], "wleiden.yaml", datadump)
564
565
566
567def generate_config(node, config, datadump=None):
568 """ Print configuration file 'config' of 'node' """
569 output = ""
570 try:
571 # Load config file
572 if datadump == None:
573 datadump = get_yaml(node)
574
575 # Preformat certain needed variables for formatting and push those into special object
576 datadump_extra = copy.deepcopy(datadump)
577 if not datadump_extra.has_key('domain'):
578 datadump_extra['domain'] = 'wleiden.net'
579 datadump_extra['nodename_lower'] = datadump_extra['nodename'].lower()
580 datadump_extra['iface_keys'] = sorted([elem for elem in datadump.keys() if elem.startswith('iface_')])
581
582 if config == 'wleiden.yaml':
583 output += generate_wleiden_yaml(datadump)
584 elif config == 'authorized_keys':
585 f = open(os.path.join(NODE_DIR,"global_keys"), 'r')
586 output += f.read()
587 f.close()
588 elif config == 'dnsmasq.conf':
589 output += generate_dnsmasq_conf(datadump_extra)
590 elif config == 'rc.conf.local':
591 output += generate_rc_conf_local(datadump_extra)
592 elif config == 'resolv.conf':
593 output += generate_resolv_conf(datadump_extra)
594 elif config == 'motd':
595 output += generate_motd(datadump_extra)
596 else:
597 assert False, "Config not found!"
598 except IOError, e:
599 output += "[ERROR] Config file not found"
600 return output
601
602
603
604def process_cgi_request():
605 """ When calling from CGI """
606 # Update repository if requested
607 form = cgi.FieldStorage()
608 if form.getvalue("action") == "update":
609 print "Refresh: 5; url=."
610 print "Content-type:text/plain\r\n\r\n",
611 print "[INFO] Updating subverion, please wait..."
612 print subprocess.Popen(['svn', 'up', "%s/.." % NODE_DIR], stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0],
613 print "[INFO] All done, redirecting in 5 seconds"
614 sys.exit(0)
615
616
617 uri = os.environ['PATH_INFO'].strip('/').split('/')
618 output = ""
619 if not uri[0]:
620 if is_text_request():
621 output += "Content-type:text/plain\r\n\r\n"
622 output += '\n'.join(get_hostlist())
623 else:
624 output += "Content-type:text/html\r\n\r\n"
625 output += generate_title(get_hostlist())
626 elif len(uri) == 1:
627 output += "Content-type:text/plain\r\n\r\n"
628 output += generate_node(uri[0])
629 elif len(uri) == 2:
630 output += "Content-type:text/plain\r\n\r\n"
631 output += generate_config(uri[0], uri[1])
632 else:
633 assert False, "Invalid option"
634 print output
635
636def get_fqdn(datadump):
637 # Proxy naming convention is special
638 if datadump['nodetype'] == 'Proxy':
639 fqdn = datadump['nodename']
640 else:
641 # By default the full name is listed and also a shortname CNAME for easy use.
642 fqdn = datadump['nodetype'] + datadump['nodename']
643 return(fqdn)
644
645
646
647def make_dns(output_dir = 'dns'):
648 items = dict()
649
650 # hostname is key, IP is value
651 wleiden_zone = dict()
652 wleiden_cname = dict()
653
654 pool = dict()
655 for node in get_hostlist():
656 logger.info("Processing host %s", node)
657 datadump = get_yaml(node)
658
659 # Proxy naming convention is special
660 fqdn = get_fqdn(datadump)
661 if datadump['nodetype'] == 'CNode':
662 wleiden_cname[datadump['nodename']] = fqdn
663
664 wleiden_zone[fqdn] = datadump['masterip']
665
666 # Hacking to get proper DHCP IPs and hostnames
667 for iface_key in get_interface_keys(datadump):
668 iface_name = datadump[iface_key]['interface'].replace(':',"-alias-")
669 (ip, netmask) = datadump[iface_key]['ip'].split('/')
670 try:
671 (dhcp_start, dhcp_stop) = datadump[iface_key]['dhcp'].split('-')
672 datadump[iface_key]['subnet'] = netmask2subnet(netmask)
673 dhcp_part = ".".join(ip.split('.')[0:3])
674 if ip != datadump['masterip']:
675 wleiden_zone["dhcp-gateway-%s.%s" % (iface_name, fqdn)] = ip
676 for i in range(int(dhcp_start), int(dhcp_stop) + 1):
677 wleiden_zone["dhcp-%s-%s.%s" % (i, iface_name, fqdn)] = "%s.%s" % (dhcp_part, i)
678 except (AttributeError, ValueError):
679 # First push it into a pool, to indentify the counter-part later on
680 addr = parseaddr(ip)
681 netmask = int(netmask)
682 addr = addr & ~((1 << (32 - netmask)) - 1)
683 if pool.has_key(addr):
684 pool[addr] += [(iface_name, fqdn, ip)]
685 else:
686 pool[addr] = [(iface_name, fqdn, ip)]
687 continue
688
689
690 def pool_to_name(node, pool_members):
691 """Convert the joined name to a usable pool name"""
692
693 # Get rid of the own entry
694 pool_members = list(set(pool_members) - set([fqdn]))
695
696 target = oldname = ''
697 for node in sorted(pool_members):
698 (name, number) = re.match('^([A-Za-z]+)([0-9]*)$',node).group(1,2)
699 target += "-" + number if name == oldname else "-" + node if target else node
700 oldname = name
701
702 return target
703
704
705 # WL uses an /29 to configure an interface. IP's are ordered like this:
706 # MasterA (.1) -- DeviceA (.2) <<>> DeviceB (.3) --- SlaveB (.4)
707
708 sn = lambda x: re.sub(r'(?i)^cnode','',x)
709
710 # Automatic naming convention of interlinks namely 2 + remote.lower()
711 for (key,value) in pool.iteritems():
712 # Make sure they are sorted from low-ip to high-ip
713 value = sorted(value, key=lambda x: parseaddr(x[2]))
714
715 if len(value) == 1:
716 (iface_name, fqdn, ip) = value[0]
717 wleiden_zone["2unused-%s.%s" % (iface_name, fqdn)] = ip
718
719 # Device DNS names
720 if 'cnode' in fqdn.lower():
721 wleiden_zone["d-at-%s.%s" % (iface_name, fqdn)] = showaddr(parseaddr(ip) + 1)
722 wleiden_cname["d-at-%s.%s" % (iface_name,sn(fqdn))] = "d-at-%s.%s" % (iface_name, fqdn)
723
724 elif len(value) == 2:
725 (a_iface_name, a_fqdn, a_ip) = value[0]
726 (b_iface_name, b_fqdn, b_ip) = value[1]
727 wleiden_zone["2%s.%s" % (b_fqdn,a_fqdn)] = a_ip
728 wleiden_zone["2%s.%s" % (a_fqdn,b_fqdn)] = b_ip
729
730 # Device DNS names
731 if 'cnode' in a_fqdn.lower() and 'cnode' in b_fqdn.lower():
732 wleiden_zone["d-at-%s.%s" % (a_iface_name, a_fqdn)] = showaddr(parseaddr(a_ip) + 1)
733 wleiden_zone["d-at-%s.%s" % (b_iface_name, b_fqdn)] = showaddr(parseaddr(b_ip) - 1)
734 wleiden_cname["d-at-%s.%s" % (a_iface_name,sn(a_fqdn))] = "d-at-%s.%s" % (a_iface_name, a_fqdn)
735 wleiden_cname["d-at-%s.%s" % (b_iface_name,sn(b_fqdn))] = "d-at-%s.%s" % (b_iface_name, b_fqdn)
736 wleiden_cname["d2%s.%s" % (sn(b_fqdn),sn(a_fqdn))] = "d-at-%s.%s" % (a_iface_name, a_fqdn)
737 wleiden_cname["d2%s.%s" % (sn(a_fqdn),sn(b_fqdn))] = "d-at-%s.%s" % (b_iface_name, b_fqdn)
738
739 else:
740 pool_members = [k[1] for k in value]
741 for item in value:
742 (iface_name, fqdn, ip) = item
743 pool_name = "2pool-" + showaddr(key).replace('.','-') + "-" + pool_to_name(fqdn,pool_members)
744 wleiden_zone["%s.%s" % (pool_name, fqdn)] = ip
745
746 # Include static DNS entries
747 # XXX: Should they override the autogenerated results?
748 # XXX: Convert input to yaml more useable.
749 # Format:
750 ##; this is a comment
751 ## roomburgh=CNodeRoomburgh1
752 ## apkerk1.CNodeVosko=172.17.176.8 ;this as well
753 dns = yaml.load(open(os.path.join(NODE_DIR,'../dns/staticDNS.yaml'),'r'))
754
755 # Hack to allow special entries, for development
756 wleiden_raw = dns['raw']
757 del dns['raw']
758
759 for comment, block in dns.iteritems():
760 for k,v in block.iteritems():
761 if valid_addr(v):
762 wleiden_zone[k] = v
763 else:
764 wleiden_cname[k] = v
765
766 details = dict()
767 # 24 updates a day allowed
768 details['serial'] = time.strftime('%Y%m%d%H')
769
770 dns_header = '''
771$TTL 3h
772%(zone)s. SOA sunny.wleiden.net. beheer.lijst.wirelessleiden.nl. ( %(serial)s 1d 12h 1w 3h )
773 ; Serial, Refresh, Retry, Expire, Neg. cache TTL
774
775 NS sunny.wleiden.net.
776 \n'''
777
778
779 if not os.path.isdir('dns'):
780 os.makedirs('dns')
781 details['zone'] = 'wleiden.net'
782 f = open(os.path.join(output_dir,"db." + details['zone']), "w")
783 f.write(dns_header % details)
784
785 for host,ip in wleiden_zone.iteritems():
786 if valid_addr(ip):
787 f.write("%s.wleiden.net. IN A %s \n" % (host.lower(), ip))
788 for source,dest in wleiden_cname.iteritems():
789 f.write("%s.wleiden.net. IN CNAME %s.wleiden.net.\n" % (source.lower(), dest.lower()))
790 for source, dest in wleiden_raw.iteritems():
791 f.write("%s.wleiden.net. %s\n" % (source, dest))
792 f.close()
793
794 # Create whole bunch of specific sub arpa zones. To keep it compliant
795 for s in range(16,32):
796 details['zone'] = '%i.172.in-addr.arpa' % s
797 f = open(os.path.join(output_dir,"db." + details['zone']), "w")
798 f.write(dns_header % details)
799
800 #XXX: Not effient, fix to proper data structure and do checks at other
801 # stages
802 for host,ip in wleiden_zone.iteritems():
803 if valid_addr(ip):
804 if int(ip.split('.')[1]) == s:
805 rev_ip = '.'.join(reversed(ip.split('.')))
806 f.write("%s.in-addr.arpa. IN PTR %s.wleiden.net.\n" % (rev_ip.lower(), host.lower()))
807 f.close()
808
809
810def usage():
811 print """Usage: %s <standalone [port] |test [test arguments]|static|dns>
812Examples:
813\tdns [outputdir] = Generate BIND compliant zone files in dns.
814\tstandalone = Run configurator webserver [default port=8000]
815\twind-export = Generate SQL import scripts for WIND database
816\tfull-export = Generate yaml export script for heatmap.
817\tstatic = Generate all config files and store on disk
818\t with format ./static/%%NODE%%/%%FILE%%
819\ttest CNodeRick dnsmasq.conf = Receive output of CGI script
820\t for arguments CNodeRick/dnsmasq.conf
821\tlist <nodes|proxies> = List systems which marked up.
822"""
823 exit(0)
824
825
826def is_text_request():
827 return os.environ['HTTP_USER_AGENT'].split()[0] in ['curl', 'fetch', 'wget']
828
829def main():
830 """Hard working sub"""
831 # Allow easy hacking using the CLI
832 if not os.environ.has_key('PATH_INFO'):
833 if len(sys.argv) < 2:
834 usage()
835
836 if sys.argv[1] == "standalone":
837 import SocketServer
838 import CGIHTTPServer
839 # CGI does not go backward, little hack to get ourself in the right working directory.
840 os.chdir(os.path.dirname(__file__) + '/..')
841 try:
842 PORT = int(sys.argv[2])
843 except (IndexError,ValueError):
844 PORT = 8000
845
846 class MyCGIHTTPRequestHandler(CGIHTTPServer.CGIHTTPRequestHandler):
847 """ Serve this CGI from the root of the webserver """
848 def is_cgi(self):
849 if "favicon" in self.path:
850 return False
851
852 self.cgi_info = (__file__, self.path)
853 self.path = ''
854 return True
855 handler = MyCGIHTTPRequestHandler
856 SocketServer.TCPServer.allow_reuse_address = True
857 httpd = SocketServer.TCPServer(("", PORT), handler)
858 httpd.server_name = 'localhost'
859 httpd.server_port = PORT
860
861 logger.info("serving at port %s", PORT)
862 try:
863 httpd.serve_forever()
864 except KeyboardInterrupt:
865 httpd.shutdown()
866 logger.info("All done goodbye")
867 elif sys.argv[1] == "test":
868 os.environ['PATH_INFO'] = "/".join(sys.argv[2:])
869 os.environ['SCRIPT_NAME'] = __file__
870 process_cgi_request()
871 elif sys.argv[1] == "static":
872 items = dict()
873 for node in get_hostlist():
874 items['node'] = node
875 items['wdir'] = "./static/%(node)s" % items
876 if not os.path.isdir(items['wdir']):
877 os.makedirs(items['wdir'])
878 datadump = get_yaml(node)
879 for config in files:
880 items['config'] = config
881 logger.info("## Generating %(node)s %(config)s" % items)
882 f = open("%(wdir)s/%(config)s" % items, "w")
883 f.write(generate_config(node, config, datadump))
884 f.close()
885 elif sys.argv[1] == "wind-export":
886 items = dict()
887 for node in get_hostlist():
888 datadump = get_yaml(node)
889 sql = """INSERT IGNORE INTO nodes (name, name_ns, longitude, latitude)
890 VALUES ('%(nodename)s', '%(nodename)s', %(latitude)s, %(longitude)s);""" % datadump;
891 sql = """INSERT IGNORE INTO users_nodes (user_id, node_id, owner)
892 VALUES (
893 (SELECT id FROM users WHERE username = 'rvdzwet'),
894 (SELECT id FROM nodes WHERE name = '%(nodename)s'),
895 'Y');""" % datadump
896 #for config in files:
897 # items['config'] = config
898 # print "## 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 for node in get_hostlist():
903 datadump = get_yaml(node)
904 for iface_key in sorted([elem for elem in datadump.keys() if elem.startswith('iface_')]):
905 ifacedump = datadump[iface_key]
906 if ifacedump.has_key('mode') and ifacedump['mode'] == 'ap-wds':
907 ifacedump['nodename'] = datadump['nodename']
908 if not ifacedump.has_key('channel') or not ifacedump['channel']:
909 ifacedump['channel'] = 0
910 sql = """INSERT INTO links (node_id, type, ssid, protocol, channel, status)
911 VALUES ((SELECT id FROM nodes WHERE name = '%(nodename)s'), 'ap',
912 '%(ssid)s', 'IEEE 802.11b', %(channel)s, 'active');""" % ifacedump
913 elif sys.argv[1] == "full-export":
914 hosts = {}
915 for node in get_hostlist():
916 datadump = get_yaml(node)
917 hosts[datadump['nodename']] = datadump
918 print yaml.dump(hosts)
919
920 elif sys.argv[1] == "dns":
921 make_dns(sys.argv[2] if len(sys.argv) > 2 else 'dns')
922 elif sys.argv[1] == "cleanup":
923 # First generate all datadumps
924 datadumps = dict()
925 for host in get_hostlist():
926 logger.info("# Processing: %s", host)
927 datadump = get_yaml(host)
928 datadumps[get_fqdn(datadump)] = datadump
929
930 for key,datadump in datadumps.iteritems():
931 datadump['latitude'], datadump['longitude'] = rdnap.rd2etrs(datadump['rdnap_x'], datadump['rdnap_y'])
932 store_yaml(datadump, header=False)
933 elif sys.argv[1] == "list":
934 if sys.argv[2] == "nodes":
935 systems = get_nodelist()
936 elif sys.argv[2] == "proxies":
937 systems = get_proxylist()
938 else:
939 usage()
940 for system in systems:
941 datadump = get_yaml(system)
942 if datadump['status'] == "up":
943 print system
944 else:
945 usage()
946 else:
947 # Do not enable debugging for config requests as it highly clutters the output
948 if not is_text_request():
949 cgitb.enable()
950 process_cgi_request()
951
952
953if __name__ == "__main__":
954 main()
Note: See TracBrowser for help on using the repository browser.