source: genesis/tools/gformat.py@ 9935

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

Extra comments is proven usefull when debugging for errors...

  • Property svn:executable set to *
  • Property svn:keywords set to Id
File size: 24.5 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 9808 2011-12-20 19:50:15Z 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", "LocalHost"), ("172.31.255.1/32","Proxy IP")] }
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 item = (ifacedump['ip'], ifacedump['desc'])
302 if addrs_list.has_key(interface):
303 addrs_list[interface].append(item)
304 else:
305 addrs_list[interface] = [item]
306
307 # Alias only needs IP assignment for now, this might change if we
308 # are going to use virtual accesspoints
309 if "alias" in iface_key:
310 continue
311
312 # XXX: Might want to deduct type directly from interface name
313 if ifacedump['type'] in ['11a', '11b', '11g', 'wireless']:
314 # Create wlanX interface
315 ifacedump['wlanif'] ="wlan%i" % wlan_count
316 iface_map[interface] = ifacedump['wlanif']
317 wlan_count += 1
318
319 # Default to station (client) mode
320 ifacedump['wlanmode'] = "sta"
321 if ifacedump['mode'] in ['master', 'master-wds']:
322 ifacedump['wlanmode'] = "ap"
323 # Default to 802.11b mode
324 ifacedump['mode'] = '11b'
325 if ifacedump['type'] in ['11a', '11b' '11g']:
326 ifacedump['mode'] = ifacedump['type']
327
328 if not ifacedump.has_key('channel'):
329 if ifacedump['type'] == '11a':
330 ifacedump['channel'] = 36
331 else:
332 ifacedump['channel'] = 1
333
334 # Allow special hacks at the back like wds and stuff
335 if not ifacedump.has_key('extra'):
336 ifacedump['extra'] = 'regdomain ETSI country NL'
337
338 output += "wlans_%(interface)s='%(wlanif)s'\n" % ifacedump
339 output += ("create_args_%(wlanif)s='wlanmode %(wlanmode)s mode " +\
340 "%(mode)s ssid %(ssid)s %(extra)s channel %(channel)s'\n") % ifacedump
341
342 elif ifacedump['type'] in ['ethernet', 'eth']:
343 # No special config needed besides IP
344 pass
345 else:
346 assert False, "Unknown type " + ifacedump['type']
347
348 # Print IP address which needs to be assigned over here
349 output += "\n"
350 for iface,addrs in sorted(addrs_list.iteritems()):
351 for addr,comment in addrs:
352 output += "# %s || %s || %s\n" % (iface, addr, comment)
353 output += "ipv4_addrs_%s='%s'\n\n" % (iface_map[iface], " ".join([x[0] for x in addrs]))
354
355 return output
356
357
358
359def get_yaml(item):
360 """ Get configuration yaml for 'item'"""
361 gfile = os.path.join(NODE_DIR,item,'wleiden.yaml')
362
363 f = open(gfile, 'r')
364 datadump = yaml.load(f,Loader=Loader)
365 f.close()
366
367 return datadump
368
369def store_yaml(datadump):
370 """ Store configuration yaml for 'item'"""
371 gfile = os.path.join(NODE_DIR,item,'wleiden.yaml')
372
373 f = open(gfile, 'w')
374 f.write(generate_wleiden_yaml(datadump))
375 f.close()
376
377
378
379def get_all_configs():
380 """ Get dict with key 'host' with all configs present """
381 configs = dict()
382 for host in get_hostlist():
383 datadump = get_yaml(host)
384 configs[host] = datadump
385 return configs
386
387
388def get_interface_keys(config):
389 """ Quick hack to get all interface keys, later stage convert this to a iterator """
390 return [elem for elem in config.keys() if (elem.startswith('iface_') and not "lo0" in elem)]
391
392
393def get_used_ips(configs):
394 """ Return array of all IPs used in config files"""
395 ip_list = []
396 for config in configs:
397 ip_list.append(config['masterip'])
398 for iface_key in get_interface_keys(config):
399 l = config[iface_key]['ip']
400 addr, mask = l.split('/')
401 # Special case do not process
402 if valid_addr(addr):
403 ip_list.append(addr)
404 else:
405 logger.error("## IP '%s' in '%s' not valid" % (addr, config['nodename']))
406 return sorted(ip_list)
407
408
409
410def write_yaml(item, datadump):
411 """ Write configuration yaml for 'item'"""
412 gfile = os.path.join(NODE_DIR,item,'wleiden.yaml')
413
414 f = open(gfile, 'w')
415 f.write(format_wleiden_yaml(datadump))
416 f.close()
417
418
419
420def generate_resolv_conf(datadump):
421 """ Generate configuration file '/etc/resolv.conf' """
422 output = generate_header("#");
423 output += """\
424search wleiden.net
425# Try local (cache) first
426nameserver 127.0.0.1
427
428# Proxies are recursive nameservers
429# needs to be in resolv.conf for dnsmasq as well
430""" % datadump
431
432 for proxy in get_proxylist():
433 proxy_ip = get_yaml(proxy)['masterip']
434 output += "nameserver %-15s # %s\n" % (proxy_ip, proxy)
435 return output
436
437
438
439def format_yaml_value(value):
440 """ Get yaml value in right syntax for outputting """
441 if isinstance(value,str):
442 output = "'%s'" % value
443 else:
444 output = value
445 return output
446
447
448
449def format_wleiden_yaml(datadump):
450 """ Special formatting to ensure it is editable"""
451 output = "# Genesis config yaml style\n"
452 output += "# vim:ts=2:et:sw=2:ai\n"
453 output += "#\n"
454 iface_keys = [elem for elem in datadump.keys() if elem.startswith('iface_')]
455 for key in sorted(set(datadump.keys()) - set(iface_keys)):
456 output += "%-10s: %s\n" % (key, format_yaml_value(datadump[key]))
457
458 output += "\n\n"
459
460 key_order = [ 'comment', 'interface', 'ip', 'desc', 'sdesc', 'mode', 'type',
461 'extra_type', 'channel', 'ssid', 'dhcp' ]
462
463 for iface_key in sorted(iface_keys):
464 output += "%s:\n" % iface_key
465 for key in key_order + list(sorted(set(datadump[iface_key].keys()) - set(key_order))):
466 if datadump[iface_key].has_key(key):
467 output += " %-11s: %s\n" % (key, format_yaml_value(datadump[iface_key][key]))
468 output += "\n\n"
469
470 return output
471
472
473
474def generate_wleiden_yaml(datadump):
475 """ Generate (petty) version of wleiden.yaml"""
476 output = generate_header("#")
477 output += format_wleiden_yaml(datadump)
478 return output
479
480
481def generate_yaml(datadump):
482 return generate_config(datadump['nodename'], "wleiden.yaml", datadump)
483
484
485
486def generate_config(node, config, datadump=None):
487 """ Print configuration file 'config' of 'node' """
488 output = ""
489 try:
490 # Load config file
491 if datadump == None:
492 datadump = get_yaml(node)
493
494 # Preformat certain needed variables for formatting and push those into special object
495 datadump_extra = copy.deepcopy(datadump)
496 if not datadump_extra.has_key('domain'):
497 datadump_extra['domain'] = 'wleiden.net'
498 datadump_extra['nodename_lower'] = datadump_extra['nodename'].lower()
499 datadump_extra['iface_keys'] = sorted([elem for elem in datadump.keys() if elem.startswith('iface_')])
500
501 if config == 'wleiden.yaml':
502 output += generate_wleiden_yaml(datadump)
503 elif config == 'authorized_keys':
504 f = open("global_keys", 'r')
505 output += f.read()
506 f.close()
507 elif config == 'dnsmasq.conf':
508 output += generate_dnsmasq_conf(datadump_extra)
509 elif config == 'rc.conf.local':
510 output += generate_rc_conf_local(datadump_extra)
511 elif config == 'resolv.conf':
512 output += generate_resolv_conf(datadump_extra)
513 else:
514 assert False, "Config not found!"
515 except IOError, e:
516 output += "[ERROR] Config file not found"
517 return output
518
519
520
521def process_cgi_request():
522 """ When calling from CGI """
523 # Update repository if requested
524 form = cgi.FieldStorage()
525 if form.getvalue("action") == "update":
526 print "Refresh: 5; url=."
527 print "Content-type:text/plain\r\n\r\n",
528 print "[INFO] Updating subverion, please wait..."
529 print subprocess.Popen(['svn', 'up', NODE_DIR], stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0],
530 print "[INFO] All done, redirecting in 5 seconds"
531 sys.exit(0)
532
533
534 uri = os.environ['PATH_INFO'].strip('/').split('/')
535 output = ""
536 if not uri[0]:
537 output += "Content-type:text/html\r\n\r\n"
538 output += generate_title(get_hostlist())
539 elif len(uri) == 1:
540 output += "Content-type:text/plain\r\n\r\n"
541 output += generate_node(uri[0])
542 elif len(uri) == 2:
543 output += "Content-type:text/plain\r\n\r\n"
544 output += generate_config(uri[0], uri[1])
545 else:
546 assert False, "Invalid option"
547 print output
548
549def get_fqdn(datadump):
550 # Proxy naming convention is special
551 if datadump['nodetype'] == 'Proxy':
552 fqdn = datadump['nodename']
553 else:
554 # By default the full name is listed and also a shortname CNAME for easy use.
555 fqdn = datadump['nodetype'] + datadump['nodename']
556 return(fqdn)
557
558
559
560def make_dns(output_dir = 'dns'):
561 items = dict()
562
563 # hostname is key, IP is value
564 wleiden_zone = dict()
565 wleiden_cname = dict()
566
567 pool = dict()
568 for node in get_hostlist():
569 logger.info("Processing host %s", node)
570 datadump = get_yaml(node)
571
572 # Proxy naming convention is special
573 fqdn = get_fqdn(datadump)
574 if datadump['nodetype'] == 'CNode':
575 wleiden_cname[datadump['nodename']] = fqdn
576
577 wleiden_zone[fqdn] = datadump['masterip']
578
579 # Hacking to get proper DHCP IPs and hostnames
580 for iface_key in get_interface_keys(datadump):
581 iface_name = datadump[iface_key]['interface'].replace(':',"-alias-")
582 (ip, netmask) = datadump[iface_key]['ip'].split('/')
583 try:
584 (dhcp_start, dhcp_stop) = datadump[iface_key]['dhcp'].split('-')
585 datadump[iface_key]['subnet'] = netmask2subnet(netmask)
586 dhcp_part = ".".join(ip.split('.')[0:3])
587 if ip != datadump['masterip']:
588 wleiden_zone["dhcp-gateway-%s.%s" % (iface_name, fqdn)] = ip
589 for i in range(int(dhcp_start), int(dhcp_stop) + 1):
590 wleiden_zone["dhcp-%s-%s.%s" % (i, iface_name, fqdn)] = "%s.%s" % (dhcp_part, i)
591 except (AttributeError, ValueError):
592 # First push it into a pool, to indentify the counter-part later on
593 addr = parseaddr(ip)
594 netmask = int(netmask)
595 addr = addr & ~((1 << (32 - netmask)) - 1)
596 if pool.has_key(addr):
597 pool[addr] += [(iface_name, fqdn, ip)]
598 else:
599 pool[addr] = [(iface_name, fqdn, ip)]
600 continue
601
602
603 def pool_to_name(node, pool_members):
604 """Convert the joined name to a usable pool name"""
605
606 # Get rid of the own entry
607 pool_members = list(set(pool_members) - set([fqdn]))
608
609 target = oldname = ''
610 for node in sorted(pool_members):
611 (name, number) = re.match('^([A-Za-z]+)([0-9]*)$',node).group(1,2)
612 target += "-" + number if name == oldname else "-" + node if target else node
613 oldname = name
614
615 return target
616
617
618 # Automatic naming convention of interlinks namely 2 + remote.lower()
619 for (key,value) in pool.iteritems():
620 if len(value) == 1:
621 (iface_name, fqdn, ip) = value[0]
622 wleiden_zone["2unused-%s.%s" % (iface_name, fqdn)] = ip
623 elif len(value) == 2:
624 (a_iface_name, a_fqdn, a_ip) = value[0]
625 (b_iface_name, b_fqdn, b_ip) = value[1]
626 wleiden_zone["2%s.%s" % (b_fqdn,a_fqdn)] = a_ip
627 wleiden_zone["2%s.%s" % (a_fqdn,b_fqdn)] = b_ip
628 else:
629 pool_members = [k[1] for k in value]
630 for item in value:
631 (iface_name, fqdn, ip) = item
632 pool_name = "2pool-" + showaddr(key).replace('.','-') + "-" + pool_to_name(fqdn,pool_members)
633 wleiden_zone["%s.%s" % (pool_name, fqdn)] = ip
634
635 # Include static DNS entries
636 # XXX: Should they override the autogenerated results?
637 # XXX: Convert input to yaml more useable.
638 # Format:
639 ##; this is a comment
640 ## roomburgh=CNodeRoomburgh1
641 ## apkerk1.CNodeVosko=172.17.176.8 ;this as well
642 dns = yaml.load(open(os.path.join(NODE_DIR,'../dns/staticDNS.yaml'),'r'))
643 for comment, block in dns.iteritems():
644 for k,v in block.iteritems():
645 if valid_addr(v):
646 wleiden_zone[k] = v
647 else:
648 wleiden_cname[k] = v
649
650 details = dict()
651 # 24 updates a day allowed
652 details['serial'] = time.strftime('%Y%m%d%H')
653
654 dns_header = '''
655$TTL 3h
656%(zone)s. SOA sunny.wleiden.net. beheer.lijst.wirelessleiden.nl. ( %(serial)s 1d 12h 1w 3h )
657 ; Serial, Refresh, Retry, Expire, Neg. cache TTL
658
659 NS sunny.wleiden.net.
660 \n'''
661
662
663 if not os.path.isdir('dns'):
664 os.makedirs('dns')
665 details['zone'] = 'wleiden.net'
666 f = open(os.path.join(output_dir,"db." + details['zone']), "w")
667 f.write(dns_header % details)
668
669 for host,ip in wleiden_zone.iteritems():
670 if valid_addr(ip):
671 f.write("%s.wleiden.net. IN A %s \n" % (host.lower(), ip))
672 for source,dest in wleiden_cname.iteritems():
673 f.write("%s.wleiden.net. IN CNAME %s.wleiden.net.\n" % (source.lower(), dest.lower()))
674 f.close()
675
676 # Create whole bunch of specific sub arpa zones. To keep it compliant
677 for s in range(16,32):
678 details['zone'] = '%i.172.in-addr.arpa' % s
679 f = open(os.path.join(output_dir,"db." + details['zone']), "w")
680 f.write(dns_header % details)
681
682 #XXX: Not effient, fix to proper data structure and do checks at other
683 # stages
684 for host,ip in wleiden_zone.iteritems():
685 if valid_addr(ip):
686 if int(ip.split('.')[1]) == s:
687 rev_ip = '.'.join(reversed(ip.split('.')))
688 f.write("%s.in-addr.arpa. IN PTR %s.wleiden.net.\n" % (rev_ip.lower(), host.lower()))
689 f.close()
690
691
692def usage():
693 print """Usage: %s <standalone [port] |test [test arguments]|static|dns>
694Examples:
695\tdns [outputdir] = Generate BIND compliant zone files in dns.
696\tstandalone = Run configurator webserver [default port=8000]
697\twind-export = Generate SQL import scripts for WIND database
698\tfull-export = Generate yaml export script for heatmap.
699\tstatic = Generate all config files and store on disk
700\t with format ./static/%%NODE%%/%%FILE%%
701\ttest CNodeRick dnsmasq.conf = Receive output of CGI script
702\t for arguments CNodeRick/dnsmasq.conf
703"""
704 exit(0)
705
706
707
708def main():
709 """Hard working sub"""
710 # Allow easy hacking using the CLI
711 if not os.environ.has_key('PATH_INFO'):
712 if len(sys.argv) < 2:
713 usage()
714
715 if sys.argv[1] == "standalone":
716 import SocketServer
717 import CGIHTTPServer
718 # CGI does not go backward, little hack to get ourself in the right working directory.
719 os.chdir(os.path.dirname(__file__) + '/..')
720 try:
721 PORT = int(sys.argv[2])
722 except (IndexError,ValueError):
723 PORT = 8000
724
725 class MyCGIHTTPRequestHandler(CGIHTTPServer.CGIHTTPRequestHandler):
726 """ Serve this CGI from the root of the webserver """
727 def is_cgi(self):
728 if "favicon" in self.path:
729 return False
730
731 self.cgi_info = (__file__, self.path)
732 self.path = ''
733 return True
734 handler = MyCGIHTTPRequestHandler
735 SocketServer.TCPServer.allow_reuse_address = True
736 httpd = SocketServer.TCPServer(("", PORT), handler)
737 httpd.server_name = 'localhost'
738 httpd.server_port = PORT
739
740 logger.info("serving at port %s", PORT)
741 try:
742 httpd.serve_forever()
743 except KeyboardInterrupt:
744 httpd.shutdown()
745 logger.info("All done goodbye")
746 elif sys.argv[1] == "test":
747 os.environ['PATH_INFO'] = "/".join(sys.argv[2:])
748 os.environ['SCRIPT_NAME'] = __file__
749 process_cgi_request()
750 elif sys.argv[1] == "static":
751 items = dict()
752 for node in get_hostlist():
753 items['node'] = node
754 items['wdir'] = "./static/%(node)s" % items
755 if not os.path.isdir(items['wdir']):
756 os.makedirs(items['wdir'])
757 datadump = get_yaml(node)
758 for config in files:
759 items['config'] = config
760 logger.info("## Generating %(node)s %(config)s" % items)
761 f = open("%(wdir)s/%(config)s" % items, "w")
762 f.write(generate_config(node, config, datadump))
763 f.close()
764 elif sys.argv[1] == "wind-export":
765 items = dict()
766 for node in get_hostlist():
767 datadump = get_yaml(node)
768 sql = """INSERT IGNORE INTO nodes (name, name_ns, longitude, latitude)
769 VALUES ('%(nodename)s', '%(nodename)s', %(latitude)s, %(longitude)s);""" % datadump;
770 sql = """INSERT IGNORE INTO users_nodes (user_id, node_id, owner)
771 VALUES (
772 (SELECT id FROM users WHERE username = 'rvdzwet'),
773 (SELECT id FROM nodes WHERE name = '%(nodename)s'),
774 'Y');""" % datadump
775 #for config in files:
776 # items['config'] = config
777 # print "## Generating %(node)s %(config)s" % items
778 # f = open("%(wdir)s/%(config)s" % items, "w")
779 # f.write(generate_config(node, config, datadump))
780 # f.close()
781 for node in get_hostlist():
782 datadump = get_yaml(node)
783 for iface_key in sorted([elem for elem in datadump.keys() if elem.startswith('iface_')]):
784 ifacedump = datadump[iface_key]
785 if ifacedump.has_key('mode') and ifacedump['mode'] == 'ap-wds':
786 ifacedump['nodename'] = datadump['nodename']
787 if not ifacedump.has_key('channel') or not ifacedump['channel']:
788 ifacedump['channel'] = 0
789 sql = """INSERT INTO links (node_id, type, ssid, protocol, channel, status)
790 VALUES ((SELECT id FROM nodes WHERE name = '%(nodename)s'), 'ap',
791 '%(ssid)s', 'IEEE 802.11b', %(channel)s, 'active');""" % ifacedump
792 elif sys.argv[1] == "full-export":
793 hosts = {}
794 for node in get_hostlist():
795 datadump = get_yaml(node)
796 hosts[datadump['nodename']] = datadump
797 print yaml.dump(hosts)
798
799 elif sys.argv[1] == "dns":
800 make_dns(sys.argv[2] if len(sys.argv) > 2 else 'dns')
801 elif sys.argv[1] == "cleanup":
802 # First generate all datadumps
803 datadumps = dict()
804 for host in get_hostlist():
805 logger.info("# Processing: %s", host)
806 datadump = get_yaml(host)
807 datadumps[get_fqdn(datadump)] = datadump
808
809 datadump['latitude'], datadump['longitude'] = rdnap.rd2etrs(datadump['rdnap_x'], datadump['rdnap_y'])
810 write_yaml(host, datadump)
811 else:
812 usage()
813 else:
814 cgitb.enable()
815 process_cgi_request()
816
817
818if __name__ == "__main__":
819 main()
Note: See TracBrowser for help on using the repository browser.