source: genesis/tools/gformat.py@ 10051

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

Gave getrange.py use gformat instead of parsing the wleiden.conf files.

Related-To: ticket:117

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