source: genesis/tools/gformat.py@ 10188

Last change on this file since 10188 was 10188, checked in by richardvm, 13 years ago

interal route is not used when lvrouted is enabled

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