source: genesis/tools/gformat.py@ 10059

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

Makes the configuration production ready.

Related-To: ticket:117

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