source: genesis/tools/gformat.py@ 10057

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

Include proxy configuration in gformat generation

Related-To: ticket:117

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