source: genesis/tools/gformat.py@ 9697

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

Show which host is causing the trouble...

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