source: genesis/tools/gformat.py@ 10067

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

Do not edit headers on the config files in indead a whee bit confusing.

Reported-By: huub

  • Property svn:executable set to *
  • Property svn:keywords set to Id
File size: 28.4 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 10067 2012-03-09 20:10:02Z 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, header=True):
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, header))
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, header=True):
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 output = generate_header("#") if header else ''
533 output += format_wleiden_yaml(datadump)
534 return output
535
536
537def generate_yaml(datadump):
538 return generate_config(datadump['nodename'], "wleiden.yaml", datadump)
539
540
541
542def generate_config(node, config, datadump=None):
543 """ Print configuration file 'config' of 'node' """
544 output = ""
545 try:
546 # Load config file
547 if datadump == None:
548 datadump = get_yaml(node)
549
550 # Preformat certain needed variables for formatting and push those into special object
551 datadump_extra = copy.deepcopy(datadump)
552 if not datadump_extra.has_key('domain'):
553 datadump_extra['domain'] = 'wleiden.net'
554 datadump_extra['nodename_lower'] = datadump_extra['nodename'].lower()
555 datadump_extra['iface_keys'] = sorted([elem for elem in datadump.keys() if elem.startswith('iface_')])
556
557 if config == 'wleiden.yaml':
558 output += generate_wleiden_yaml(datadump)
559 elif config == 'authorized_keys':
560 f = open(os.path.join(NODE_DIR,"global_keys"), 'r')
561 output += f.read()
562 f.close()
563 elif config == 'dnsmasq.conf':
564 output += generate_dnsmasq_conf(datadump_extra)
565 elif config == 'rc.conf.local':
566 output += generate_rc_conf_local(datadump_extra)
567 elif config == 'resolv.conf':
568 output += generate_resolv_conf(datadump_extra)
569 else:
570 assert False, "Config not found!"
571 except IOError, e:
572 output += "[ERROR] Config file not found"
573 return output
574
575
576
577def process_cgi_request():
578 """ When calling from CGI """
579 # Update repository if requested
580 form = cgi.FieldStorage()
581 if form.getvalue("action") == "update":
582 print "Refresh: 5; url=."
583 print "Content-type:text/plain\r\n\r\n",
584 print "[INFO] Updating subverion, please wait..."
585 print subprocess.Popen(['svn', 'up', NODE_DIR], stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0],
586 print "[INFO] All done, redirecting in 5 seconds"
587 sys.exit(0)
588
589
590 uri = os.environ['PATH_INFO'].strip('/').split('/')
591 output = ""
592 if not uri[0]:
593 if os.environ['HTTP_USER_AGENT'].startswith('fetch '):
594 output += "Content-type:text/plain\r\n\r\n"
595 output += '\n'.join(get_hostlist())
596 else:
597 output += "Content-type:text/html\r\n\r\n"
598 output += generate_title(get_hostlist())
599 elif len(uri) == 1:
600 output += "Content-type:text/plain\r\n\r\n"
601 output += generate_node(uri[0])
602 elif len(uri) == 2:
603 output += "Content-type:text/plain\r\n\r\n"
604 output += generate_config(uri[0], uri[1])
605 else:
606 assert False, "Invalid option"
607 print output
608
609def get_fqdn(datadump):
610 # Proxy naming convention is special
611 if datadump['nodetype'] == 'Proxy':
612 fqdn = datadump['nodename']
613 else:
614 # By default the full name is listed and also a shortname CNAME for easy use.
615 fqdn = datadump['nodetype'] + datadump['nodename']
616 return(fqdn)
617
618
619
620def make_dns(output_dir = 'dns'):
621 items = dict()
622
623 # hostname is key, IP is value
624 wleiden_zone = dict()
625 wleiden_cname = dict()
626
627 pool = dict()
628 for node in get_hostlist():
629 logger.info("Processing host %s", node)
630 datadump = get_yaml(node)
631
632 # Proxy naming convention is special
633 fqdn = get_fqdn(datadump)
634 if datadump['nodetype'] == 'CNode':
635 wleiden_cname[datadump['nodename']] = fqdn
636
637 wleiden_zone[fqdn] = datadump['masterip']
638
639 # Hacking to get proper DHCP IPs and hostnames
640 for iface_key in get_interface_keys(datadump):
641 iface_name = datadump[iface_key]['interface'].replace(':',"-alias-")
642 (ip, netmask) = datadump[iface_key]['ip'].split('/')
643 try:
644 (dhcp_start, dhcp_stop) = datadump[iface_key]['dhcp'].split('-')
645 datadump[iface_key]['subnet'] = netmask2subnet(netmask)
646 dhcp_part = ".".join(ip.split('.')[0:3])
647 if ip != datadump['masterip']:
648 wleiden_zone["dhcp-gateway-%s.%s" % (iface_name, fqdn)] = ip
649 for i in range(int(dhcp_start), int(dhcp_stop) + 1):
650 wleiden_zone["dhcp-%s-%s.%s" % (i, iface_name, fqdn)] = "%s.%s" % (dhcp_part, i)
651 except (AttributeError, ValueError):
652 # First push it into a pool, to indentify the counter-part later on
653 addr = parseaddr(ip)
654 netmask = int(netmask)
655 addr = addr & ~((1 << (32 - netmask)) - 1)
656 if pool.has_key(addr):
657 pool[addr] += [(iface_name, fqdn, ip)]
658 else:
659 pool[addr] = [(iface_name, fqdn, ip)]
660 continue
661
662
663 def pool_to_name(node, pool_members):
664 """Convert the joined name to a usable pool name"""
665
666 # Get rid of the own entry
667 pool_members = list(set(pool_members) - set([fqdn]))
668
669 target = oldname = ''
670 for node in sorted(pool_members):
671 (name, number) = re.match('^([A-Za-z]+)([0-9]*)$',node).group(1,2)
672 target += "-" + number if name == oldname else "-" + node if target else node
673 oldname = name
674
675 return target
676
677
678 # WL uses an /29 to configure an interface. IP's are ordered like this:
679 # MasterA (.1) -- DeviceA (.2) <<>> DeviceB (.3) --- SlaveB (.4)
680
681 sn = lambda x: re.sub(r'(?i)^cnode','',x)
682
683 # Automatic naming convention of interlinks namely 2 + remote.lower()
684 for (key,value) in pool.iteritems():
685 # Make sure they are sorted from low-ip to high-ip
686 value = sorted(value, key=lambda x: parseaddr(x[2]))
687
688 if len(value) == 1:
689 (iface_name, fqdn, ip) = value[0]
690 wleiden_zone["2unused-%s.%s" % (iface_name, fqdn)] = ip
691
692 # Device DNS names
693 if 'cnode' in fqdn.lower():
694 wleiden_zone["d-at-%s.%s" % (iface_name, fqdn)] = showaddr(parseaddr(ip) + 1)
695 wleiden_cname["d-at-%s.%s" % (iface_name,sn(fqdn))] = "d-at-%s.%s" % (iface_name, fqdn)
696
697 elif len(value) == 2:
698 (a_iface_name, a_fqdn, a_ip) = value[0]
699 (b_iface_name, b_fqdn, b_ip) = value[1]
700 wleiden_zone["2%s.%s" % (b_fqdn,a_fqdn)] = a_ip
701 wleiden_zone["2%s.%s" % (a_fqdn,b_fqdn)] = b_ip
702
703 # Device DNS names
704 if 'cnode' in a_fqdn.lower() and 'cnode' in b_fqdn.lower():
705 wleiden_zone["d-at-%s.%s" % (a_iface_name, a_fqdn)] = showaddr(parseaddr(a_ip) + 1)
706 wleiden_zone["d-at-%s.%s" % (b_iface_name, b_fqdn)] = showaddr(parseaddr(b_ip) - 1)
707 wleiden_cname["d-at-%s.%s" % (a_iface_name,sn(a_fqdn))] = "d-at-%s.%s" % (a_iface_name, a_fqdn)
708 wleiden_cname["d-at-%s.%s" % (b_iface_name,sn(b_fqdn))] = "d-at-%s.%s" % (b_iface_name, b_fqdn)
709 wleiden_cname["d2%s.%s" % (sn(b_fqdn),sn(a_fqdn))] = "d-at-%s.%s" % (a_iface_name, a_fqdn)
710 wleiden_cname["d2%s.%s" % (sn(a_fqdn),sn(b_fqdn))] = "d-at-%s.%s" % (b_iface_name, b_fqdn)
711
712 else:
713 pool_members = [k[1] for k in value]
714 for item in value:
715 (iface_name, fqdn, ip) = item
716 pool_name = "2pool-" + showaddr(key).replace('.','-') + "-" + pool_to_name(fqdn,pool_members)
717 wleiden_zone["%s.%s" % (pool_name, fqdn)] = ip
718
719 # Include static DNS entries
720 # XXX: Should they override the autogenerated results?
721 # XXX: Convert input to yaml more useable.
722 # Format:
723 ##; this is a comment
724 ## roomburgh=CNodeRoomburgh1
725 ## apkerk1.CNodeVosko=172.17.176.8 ;this as well
726 dns = yaml.load(open(os.path.join(NODE_DIR,'../dns/staticDNS.yaml'),'r'))
727
728 # Hack to allow special entries, for development
729 wleiden_raw = dns['raw']
730 del dns['raw']
731
732 for comment, block in dns.iteritems():
733 for k,v in block.iteritems():
734 if valid_addr(v):
735 wleiden_zone[k] = v
736 else:
737 wleiden_cname[k] = v
738
739 details = dict()
740 # 24 updates a day allowed
741 details['serial'] = time.strftime('%Y%m%d%H')
742
743 dns_header = '''
744$TTL 3h
745%(zone)s. SOA sunny.wleiden.net. beheer.lijst.wirelessleiden.nl. ( %(serial)s 1d 12h 1w 3h )
746 ; Serial, Refresh, Retry, Expire, Neg. cache TTL
747
748 NS sunny.wleiden.net.
749 \n'''
750
751
752 if not os.path.isdir('dns'):
753 os.makedirs('dns')
754 details['zone'] = 'wleiden.net'
755 f = open(os.path.join(output_dir,"db." + details['zone']), "w")
756 f.write(dns_header % details)
757
758 for host,ip in wleiden_zone.iteritems():
759 if valid_addr(ip):
760 f.write("%s.wleiden.net. IN A %s \n" % (host.lower(), ip))
761 for source,dest in wleiden_cname.iteritems():
762 f.write("%s.wleiden.net. IN CNAME %s.wleiden.net.\n" % (source.lower(), dest.lower()))
763 for source, dest in wleiden_raw.iteritems():
764 f.write("%s.wleiden.net. %s\n" % (source, dest))
765 f.close()
766
767 # Create whole bunch of specific sub arpa zones. To keep it compliant
768 for s in range(16,32):
769 details['zone'] = '%i.172.in-addr.arpa' % s
770 f = open(os.path.join(output_dir,"db." + details['zone']), "w")
771 f.write(dns_header % details)
772
773 #XXX: Not effient, fix to proper data structure and do checks at other
774 # stages
775 for host,ip in wleiden_zone.iteritems():
776 if valid_addr(ip):
777 if int(ip.split('.')[1]) == s:
778 rev_ip = '.'.join(reversed(ip.split('.')))
779 f.write("%s.in-addr.arpa. IN PTR %s.wleiden.net.\n" % (rev_ip.lower(), host.lower()))
780 f.close()
781
782
783def usage():
784 print """Usage: %s <standalone [port] |test [test arguments]|static|dns>
785Examples:
786\tdns [outputdir] = Generate BIND compliant zone files in dns.
787\tstandalone = Run configurator webserver [default port=8000]
788\twind-export = Generate SQL import scripts for WIND database
789\tfull-export = Generate yaml export script for heatmap.
790\tstatic = Generate all config files and store on disk
791\t with format ./static/%%NODE%%/%%FILE%%
792\ttest CNodeRick dnsmasq.conf = Receive output of CGI script
793\t for arguments CNodeRick/dnsmasq.conf
794\tlist <nodes|proxies> = List systems which marked up.
795"""
796 exit(0)
797
798
799
800def main():
801 """Hard working sub"""
802 # Allow easy hacking using the CLI
803 if not os.environ.has_key('PATH_INFO'):
804 if len(sys.argv) < 2:
805 usage()
806
807 if sys.argv[1] == "standalone":
808 import SocketServer
809 import CGIHTTPServer
810 # CGI does not go backward, little hack to get ourself in the right working directory.
811 os.chdir(os.path.dirname(__file__) + '/..')
812 try:
813 PORT = int(sys.argv[2])
814 except (IndexError,ValueError):
815 PORT = 8000
816
817 class MyCGIHTTPRequestHandler(CGIHTTPServer.CGIHTTPRequestHandler):
818 """ Serve this CGI from the root of the webserver """
819 def is_cgi(self):
820 if "favicon" in self.path:
821 return False
822
823 self.cgi_info = (__file__, self.path)
824 self.path = ''
825 return True
826 handler = MyCGIHTTPRequestHandler
827 SocketServer.TCPServer.allow_reuse_address = True
828 httpd = SocketServer.TCPServer(("", PORT), handler)
829 httpd.server_name = 'localhost'
830 httpd.server_port = PORT
831
832 logger.info("serving at port %s", PORT)
833 try:
834 httpd.serve_forever()
835 except KeyboardInterrupt:
836 httpd.shutdown()
837 logger.info("All done goodbye")
838 elif sys.argv[1] == "test":
839 os.environ['PATH_INFO'] = "/".join(sys.argv[2:])
840 os.environ['SCRIPT_NAME'] = __file__
841 process_cgi_request()
842 elif sys.argv[1] == "static":
843 items = dict()
844 for node in get_hostlist():
845 items['node'] = node
846 items['wdir'] = "./static/%(node)s" % items
847 if not os.path.isdir(items['wdir']):
848 os.makedirs(items['wdir'])
849 datadump = get_yaml(node)
850 for config in files:
851 items['config'] = config
852 logger.info("## Generating %(node)s %(config)s" % items)
853 f = open("%(wdir)s/%(config)s" % items, "w")
854 f.write(generate_config(node, config, datadump))
855 f.close()
856 elif sys.argv[1] == "wind-export":
857 items = dict()
858 for node in get_hostlist():
859 datadump = get_yaml(node)
860 sql = """INSERT IGNORE INTO nodes (name, name_ns, longitude, latitude)
861 VALUES ('%(nodename)s', '%(nodename)s', %(latitude)s, %(longitude)s);""" % datadump;
862 sql = """INSERT IGNORE INTO users_nodes (user_id, node_id, owner)
863 VALUES (
864 (SELECT id FROM users WHERE username = 'rvdzwet'),
865 (SELECT id FROM nodes WHERE name = '%(nodename)s'),
866 'Y');""" % datadump
867 #for config in files:
868 # items['config'] = config
869 # print "## Generating %(node)s %(config)s" % items
870 # f = open("%(wdir)s/%(config)s" % items, "w")
871 # f.write(generate_config(node, config, datadump))
872 # f.close()
873 for node in get_hostlist():
874 datadump = get_yaml(node)
875 for iface_key in sorted([elem for elem in datadump.keys() if elem.startswith('iface_')]):
876 ifacedump = datadump[iface_key]
877 if ifacedump.has_key('mode') and ifacedump['mode'] == 'ap-wds':
878 ifacedump['nodename'] = datadump['nodename']
879 if not ifacedump.has_key('channel') or not ifacedump['channel']:
880 ifacedump['channel'] = 0
881 sql = """INSERT INTO links (node_id, type, ssid, protocol, channel, status)
882 VALUES ((SELECT id FROM nodes WHERE name = '%(nodename)s'), 'ap',
883 '%(ssid)s', 'IEEE 802.11b', %(channel)s, 'active');""" % ifacedump
884 elif sys.argv[1] == "full-export":
885 hosts = {}
886 for node in get_hostlist():
887 datadump = get_yaml(node)
888 hosts[datadump['nodename']] = datadump
889 print yaml.dump(hosts)
890
891 elif sys.argv[1] == "dns":
892 make_dns(sys.argv[2] if len(sys.argv) > 2 else 'dns')
893 elif sys.argv[1] == "cleanup":
894 # First generate all datadumps
895 datadumps = dict()
896 for host in get_hostlist():
897 logger.info("# Processing: %s", host)
898 datadump = get_yaml(host)
899 datadumps[get_fqdn(datadump)] = datadump
900
901 for key,datadump in datadumps.iteritems():
902 datadump['latitude'], datadump['longitude'] = rdnap.rd2etrs(datadump['rdnap_x'], datadump['rdnap_y'])
903 store_yaml(datadump, header=False)
904 elif sys.argv[1] == "list":
905 if sys.argv[2] == "nodes":
906 systems = get_nodelist()
907 elif sys.argv[2] == "proxies":
908 systems = get_proxylist()
909 else:
910 usage()
911 for system in systems:
912 datadump = get_yaml(system)
913 if datadump['status'] == "up":
914 print system
915 else:
916 usage()
917 else:
918 cgitb.enable()
919 process_cgi_request()
920
921
922if __name__ == "__main__":
923 main()
Note: See TracBrowser for help on using the repository browser.