source: genesis/tools/gformat.py@ 10264

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

Support generating an external zone file using an awefull hack.

Related-To: beheer#136

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