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
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# Rick van der Zwet <info@rickvanderzwet.nl>
6
7# Hack to make the script directory is also threated as a module search path.
8import sys
9import os
10import re
11sys.path.append(os.path.dirname(__file__))
12
13import cgi
14import cgitb
15import copy
16import glob
17import socket
18import string
19import subprocess
20import time
21import rdnap
22from pprint import pprint
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)
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
36import logging
37logging.basicConfig(format='# %(levelname)s: %(message)s' )
38logger = logging.getLogger()
39logger.setLevel(logging.DEBUG)
40
41
42if os.environ.has_key('CONFIGROOT'):
43 NODE_DIR = os.environ['CONFIGROOT']
44else:
45 NODE_DIR = os.path.abspath(os.path.dirname(__file__)) + '/../nodes'
46__version__ = '$Id: gformat.py 9697 2011-10-06 09:44:06Z rick $'
47
48
49files = [
50 'authorized_keys',
51 'dnsmasq.conf',
52 'rc.conf.local',
53 'resolv.conf',
54 'wleiden.yaml'
55 ]
56
57# Global variables uses
58OK = 10
59DOWN = 20
60UNKNOWN = 90
61
62
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
73def valid_addr(addr):
74 """ Show which address is valid in which are not """
75 return str(addr).startswith('172.')
76
77
78def get_nodelist():
79 """ Get all available nodes - sorted """
80 os.chdir(NODE_DIR)
81 nodelist = sorted(glob.glob("CNode*"))
82 return nodelist
83
84def get_hostlist():
85 """ Combined hosts and proxy list"""
86 return get_nodelist() + get_proxylist()
87
88def angle_between_points(lat1,lat2,long1,long2):
89 """
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
97
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"
110 elif degrees < (90 - p):
111 return "no"
112 elif degrees < (90 + p):
113 return "o"
114 elif degrees < (180 - p):
115 return "zo"
116 elif degrees < (180 + p):
117 return "z"
118 elif degrees < (270 - p):
119 return "zw"
120 elif degrees < (270 + p):
121 return "w"
122 elif degrees < (360 - p):
123 return "nw"
124 else:
125 return "n"
126
127
128def generate_title(nodelist):
129 """ Main overview page """
130 items = {'root' : "." }
131 output = """
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>
144 <form type="GET" action="%(root)s">
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
151
152 for node in nodelist:
153 items['node'] = node
154 output += '<tr><td><a href="%(root)s/%(node)s">%(node)s</a></td>' % items
155 for config in files:
156 items['config'] = config
157 output += '<td><a href="%(root)s/%(node)s/%(config)s">%(config)s</a></td>' % items
158 output += "</tr>"
159 output += """
160 </table>
161 <hr />
162 <em>%s</em>
163 </center>
164 </body>
165</html>
166 """ % __version__
167
168 return output
169
170
171
172def generate_node(node):
173 """ Print overview of all files available for node """
174 return "\n".join(files)
175
176
177
178def generate_header(ctag="#"):
179 return """\
180%(ctag)s
181%(ctag)s DO NOT EDIT - Automatically generated by 'gformat'
182%(ctag)s Generated at %(date)s by %(host)s
183%(ctag)s
184""" % { 'ctag' : ctag, 'date' : time.ctime(), 'host' : socket.gethostname() }
185
186
187
188def parseaddr(s):
189 """ Process IPv4 CIDR notation addr to a (binary) number """
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
196
197
198def showaddr(a):
199 """ Display IPv4 addr in (dotted) CIDR notation """
200 return "%d.%d.%d.%d" % ((a >> 24) & 0xff, (a >> 16) & 0xff, (a >> 8) & 0xff, a & 0xff)
201
202
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
211
212
213
214
215def netmask2subnet(netmask):
216 """ Given a 'netmask' return corresponding CIDR """
217 return showaddr(0xffffffff & (0xffffffff << (32 - int(netmask))))
218
219
220
221def generate_dnsmasq_conf(datadump):
222 """ Generate configuration file '/usr/local/etc/dnsmasq.conf' """
223 output = generate_header()
224 output += """\
225# DHCP server options
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']:
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]
240
241 try:
242 (dhcp_start, dhcp_stop) = datadump[iface_key]['dhcp'].split('-')
243 (ip, netmask) = datadump[iface_key]['ip'].split('/')
244 datadump[iface_key]['subnet'] = netmask2subnet(netmask)
245 except (AttributeError, ValueError):
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]
253
254 return output
255
256
257
258def generate_rc_conf_local(datadump):
259 """ Generate configuration file '/etc/rc.conf.local' """
260 output = generate_header("#");
261 output += """\
262hostname='%(nodetype)s%(nodename)s.%(domain)s'
263location='%(location)s'
264""" % datadump
265
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"
276
277 output += '\n'
278 # lo0 configuration:
279 # - 172.32.255.1/32 is the proxy.wleiden.net deflector
280 # - masterip is special as it needs to be assigned to at
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"] }
283 iface_map = {'lo0' : 'lo0'}
284
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
290 if not masterip_used:
291 addrs_list['lo0'].append(datadump['masterip'] + "/32")
292
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
314 ifacedump['wlanif'] ="wlan%i" % wlan_count
315 iface_map[interface] = ifacedump['wlanif']
316 wlan_count += 1
317
318 # Default to station (client) mode
319 ifacedump['wlanmode'] = "sta"
320 if ifacedump['mode'] in ['master', 'master-wds']:
321 ifacedump['wlanmode'] = "ap"
322 # Default to 802.11b mode
323 ifacedump['mode'] = '11b'
324 if ifacedump['type'] in ['11a', '11b' '11g']:
325 ifacedump['mode'] = ifacedump['type']
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 " +\
339 "%(mode)s ssid %(ssid)s %(extra)s channel %(channel)s'\n") % ifacedump
340
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
347 # Print IP address which needs to be assigned over here
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
354
355
356def get_yaml(item):
357 """ Get configuration yaml for 'item'"""
358 gfile = os.path.join(NODE_DIR,item,'wleiden.yaml')
359
360 f = open(gfile, 'r')
361 datadump = yaml.load(f,Loader=Loader)
362 f.close()
363
364 return datadump
365
366def store_yaml(datadump):
367 """ Store configuration yaml for 'item'"""
368 gfile = os.path.join(NODE_DIR,item,'wleiden.yaml')
369
370 f = open(gfile, 'w')
371 f.write(generate_wleiden_yaml(datadump))
372 f.close()
373
374
375
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
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)]
388
389
390def get_used_ips(configs):
391 """ Return array of all IPs used in config files"""
392 ip_list = []
393 for config in configs:
394 ip_list.append(config['masterip'])
395 for iface_key in get_interface_keys(config):
396 l = config[iface_key]['ip']
397 addr, mask = l.split('/')
398 # Special case do not process
399 if valid_addr(addr):
400 ip_list.append(addr)
401 else:
402 print "## IP '%s' in '%s' not valid" % (addr, config['nodename'])
403 return sorted(ip_list)
404
405
406
407def write_yaml(item, datadump):
408 """ Write configuration yaml for 'item'"""
409 gfile = os.path.join(NODE_DIR,item,'wleiden.yaml')
410
411 f = open(gfile, 'w')
412 f.write(format_wleiden_yaml(datadump))
413 f.close()
414
415
416
417def generate_resolv_conf(datadump):
418 """ Generate configuration file '/etc/resolv.conf' """
419 output = generate_header("#");
420 output += """\
421search wleiden.net
422# Try local (cache) first
423nameserver 127.0.0.1
424
425# Proxies are recursive nameservers
426# needs to be in resolv.conf for dnsmasq as well
427""" % datadump
428
429 for proxy in get_proxylist():
430 proxy_ip = get_yaml(proxy)['masterip']
431 output += "nameserver %-15s # %s\n" % (proxy_ip, proxy)
432 return output
433
434
435
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
442 return output
443
444
445
446def format_wleiden_yaml(datadump):
447 """ Special formatting to ensure it is editable"""
448 output = "# Genesis config yaml style\n"
449 output += "# vim:ts=2:et:sw=2:ai\n"
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)):
453 output += "%-10s: %s\n" % (key, format_yaml_value(datadump[key]))
454
455 output += "\n\n"
456
457 key_order = [ 'comment', 'interface', 'ip', 'desc', 'sdesc', 'mode', 'type',
458 'extra_type', 'channel', 'ssid', 'dhcp' ]
459
460 for iface_key in sorted(iface_keys):
461 output += "%s:\n" % iface_key
462 for key in key_order + list(sorted(set(datadump[iface_key].keys()) - set(key_order))):
463 if datadump[iface_key].has_key(key):
464 output += " %-11s: %s\n" % (key, format_yaml_value(datadump[iface_key][key]))
465 output += "\n\n"
466
467 return output
468
469
470
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
478def generate_yaml(datadump):
479 return generate_config(datadump['nodename'], "wleiden.yaml", datadump)
480
481
482
483def generate_config(node, config, datadump=None):
484 """ Print configuration file 'config' of 'node' """
485 output = ""
486 try:
487 # Load config file
488 if datadump == None:
489 datadump = get_yaml(node)
490
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
498 if config == 'wleiden.yaml':
499 output += generate_wleiden_yaml(datadump)
500 elif config == 'authorized_keys':
501 f = open("global_keys", 'r')
502 output += f.read()
503 f.close()
504 elif config == 'dnsmasq.conf':
505 output += generate_dnsmasq_conf(datadump_extra)
506 elif config == 'rc.conf.local':
507 output += generate_rc_conf_local(datadump_extra)
508 elif config == 'resolv.conf':
509 output += generate_resolv_conf(datadump_extra)
510 else:
511 assert False, "Config not found!"
512 except IOError, e:
513 output += "[ERROR] Config file not found"
514 return output
515
516
517
518def process_cgi_request():
519 """ When calling from CGI """
520 # Update repository if requested
521 form = cgi.FieldStorage()
522 if form.getvalue("action") == "update":
523 print "Refresh: 5; url=."
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)
529
530
531 uri = os.environ['PATH_INFO'].strip('/').split('/')
532 output = ""
533 if not uri[0]:
534 output += "Content-type:text/html\r\n\r\n"
535 output += generate_title(get_hostlist())
536 elif len(uri) == 1:
537 output += "Content-type:text/plain\r\n\r\n"
538 output += generate_node(uri[0])
539 elif len(uri) == 2:
540 output += "Content-type:text/plain\r\n\r\n"
541 output += generate_config(uri[0], uri[1])
542 else:
543 assert False, "Invalid option"
544 print output
545
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)
554
555
556
557def make_dns(output_dir = 'dns'):
558 items = dict()
559
560 # hostname is key, IP is value
561 wleiden_zone = dict()
562 wleiden_cname = dict()
563
564 pool = dict()
565 for node in get_hostlist():
566 logger.info("Processing host %s", node)
567 datadump = get_yaml(node)
568
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
576 # Hacking to get proper DHCP IPs and hostnames
577 for iface_key in get_interface_keys(datadump):
578 iface_name = datadump[iface_key]['interface'].replace(':',"-alias-")
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)
593 if pool.has_key(addr):
594 pool[addr] += [(iface_name, fqdn, ip)]
595 else:
596 pool[addr] = [(iface_name, fqdn, ip)]
597 continue
598
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
615 # Automatic naming convention of interlinks namely 2 + remote.lower()
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:
628 (iface_name, fqdn, ip) = item
629 pool_name = "2pool-" + showaddr(key).replace('.','-') + "-" + pool_to_name(fqdn,pool_members)
630 wleiden_zone["%s.%s" % (pool_name, fqdn)] = ip
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
639 dns = yaml.load(open(os.path.join(NODE_DIR,'../dns/staticDNS.yaml'),'r'))
640 for comment, block in dns.iteritems():
641 for k,v in block.iteritems():
642 if valid_addr(v):
643 wleiden_zone[k] = v
644 else:
645 wleiden_cname[k] = v
646
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
659
660 if not os.path.isdir('dns'):
661 os.makedirs('dns')
662 details['zone'] = 'wleiden.net'
663 f = open(os.path.join(output_dir,"db." + details['zone']), "w")
664 f.write(dns_header % details)
665
666 for host,ip in wleiden_zone.iteritems():
667 if valid_addr(ip):
668 f.write("%s.wleiden.net. IN A %s \n" % (host.lower(), ip))
669 for source,dest in wleiden_cname.iteritems():
670 f.write("%s.wleiden.net. IN CNAME %s.wleiden.net.\n" % (source.lower(), dest.lower()))
671 f.close()
672
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
676 f = open(os.path.join(output_dir,"db." + details['zone']), "w")
677 f.write(dns_header % details)
678
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('.')))
685 f.write("%s.in-addr.arpa. IN PTR %s.wleiden.net.\n" % (rev_ip.lower(), host.lower()))
686 f.close()
687
688
689def usage():
690 print """Usage: %s <standalone [port] |test [test arguments]|static|dns>
691Examples:
692\tdns [outputdir] = Generate BIND compliant zone files in dns.
693\tstandalone = Run configurator webserver [default port=8000]
694\twind-export = Generate SQL import scripts for WIND database
695\tfull-export = Generate yaml export script for heatmap.
696\tstatic = Generate all config files and store on disk
697\t with format ./static/%%NODE%%/%%FILE%%
698\ttest CNodeRick dnsmasq.conf = Receive output of CGI script
699\t for arguments CNodeRick/dnsmasq.conf
700"""
701 exit(0)
702
703
704
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()
711
712 if sys.argv[1] == "standalone":
713 import SocketServer
714 import CGIHTTPServer
715 # CGI does not go backward, little hack to get ourself in the right working directory.
716 os.chdir(os.path.dirname(__file__) + '/..')
717 try:
718 PORT = int(sys.argv[2])
719 except (IndexError,ValueError):
720 PORT = 8000
721
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
727
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
735
736 print "serving at port", PORT
737 try:
738 httpd.serve_forever()
739 except KeyboardInterrupt:
740 httpd.shutdown()
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()
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'])
752 datadump = get_yaml(node)
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")
757 f.write(generate_config(node, config, datadump))
758 f.close()
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
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
797 elif sys.argv[1] == "dns":
798 make_dns(sys.argv[2] if len(sys.argv) > 2 else 'dns')
799 elif sys.argv[1] == "cleanup":
800 # First generate all datadumps
801 datadumps = dict()
802 for host in get_hostlist():
803 print "# Processing: ", host
804 datadump = get_yaml(host)
805 datadumps[get_fqdn(datadump)] = datadump
806
807 datadump['latitude'], datadump['longitude'] = rdnap.rd2etrs(datadump['rdnap_x'], datadump['rdnap_y'])
808 write_yaml(host, datadump)
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.