source: genesis/tools/gformat.py@ 10191

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

seperate hybrid from proxy of node

  • Property svn:executable set to *
  • Property svn:keywords set to Id
File size: 31.9 KB
RevLine 
[8242]1#!/usr/bin/env python
2#
3# vim:ts=2:et:sw=2:ai
4# Wireless Leiden configuration generator, based on yaml files'
[9957]5#
6# XXX: This should be rewritten to make use of the ipaddr.py library.
7#
[10058]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#
[8242]15# Rick van der Zwet <info@rickvanderzwet.nl>
[9957]16#
[8622]17
18# Hack to make the script directory is also threated as a module search path.
19import sys
20import os
[9286]21import re
[8622]22sys.path.append(os.path.dirname(__file__))
23
[8242]24import cgi
[8267]25import cgitb
26import copy
[8242]27import glob
28import socket
29import string
30import subprocess
31import time
[8622]32import rdnap
[8584]33from pprint import pprint
[8575]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)
[8588]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
[10110]47from jinja2 import Template
48
[9697]49import logging
50logging.basicConfig(format='# %(levelname)s: %(message)s' )
51logger = logging.getLogger()
52logger.setLevel(logging.DEBUG)
[8242]53
[9283]54
[8948]55if os.environ.has_key('CONFIGROOT'):
56 NODE_DIR = os.environ['CONFIGROOT']
57else:
[9283]58 NODE_DIR = os.path.abspath(os.path.dirname(__file__)) + '/../nodes'
[8242]59__version__ = '$Id: gformat.py 10190 2012-03-17 12:15:14Z richardvm $'
60
[8267]61
[9283]62files = [
[8242]63 'authorized_keys',
64 'dnsmasq.conf',
65 'rc.conf.local',
66 'resolv.conf',
[10069]67 'motd',
[10054]68 'wleiden.yaml',
[8242]69 ]
70
[8319]71# Global variables uses
[8323]72OK = 10
73DOWN = 20
74UNKNOWN = 90
[8257]75
76
[8267]77def get_proxylist():
78 """Get all available proxies proxyX sorting based on X number"""
[10041]79 proxylist = sorted([os.path.basename(x) for x in glob.glob("%s/proxy*" % NODE_DIR)],
[8267]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
[8321]86def valid_addr(addr):
87 """ Show which address is valid in which are not """
88 return str(addr).startswith('172.')
89
90
[8267]91def get_nodelist():
92 """ Get all available nodes - sorted """
[10041]93 nodelist = sorted([os.path.basename(x) for x in glob.glob("%s/CNode*" % NODE_DIR)])
[8267]94 return nodelist
95
[8296]96def get_hostlist():
97 """ Combined hosts and proxy list"""
98 return get_nodelist() + get_proxylist()
[8267]99
[8588]100def angle_between_points(lat1,lat2,long1,long2):
[9283]101 """
[8588]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
[8267]109
[8588]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"
[9283]122 elif degrees < (90 - p):
[8588]123 return "no"
[9283]124 elif degrees < (90 + p):
[8588]125 return "o"
[9283]126 elif degrees < (180 - p):
[8588]127 return "zo"
[9283]128 elif degrees < (180 + p):
[8588]129 return "z"
[9283]130 elif degrees < (270 - p):
[8588]131 return "zw"
[9283]132 elif degrees < (270 + p):
[8588]133 return "w"
[9283]134 elif degrees < (360 - p):
[8588]135 return "nw"
136 else:
137 return "n"
138
139
[8267]140def generate_title(nodelist):
[8257]141 """ Main overview page """
[9283]142 items = {'root' : "." }
[8267]143 output = """
[8257]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>
[8259]156 <form type="GET" action="%(root)s">
[8257]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
[8242]163
[8296]164 for node in nodelist:
[8257]165 items['node'] = node
[8267]166 output += '<tr><td><a href="%(root)s/%(node)s">%(node)s</a></td>' % items
[8257]167 for config in files:
168 items['config'] = config
[8267]169 output += '<td><a href="%(root)s/%(node)s/%(config)s">%(config)s</a></td>' % items
170 output += "</tr>"
171 output += """
[8257]172 </table>
173 <hr />
174 <em>%s</em>
175 </center>
176 </body>
177</html>
178 """ % __version__
[8242]179
[8267]180 return output
[8257]181
182
[8267]183
184def generate_node(node):
[8257]185 """ Print overview of all files available for node """
[8267]186 return "\n".join(files)
[8242]187
[8257]188
189
[8242]190def generate_header(ctag="#"):
191 return """\
[9283]192%(ctag)s
[8242]193%(ctag)s DO NOT EDIT - Automatically generated by 'gformat'
194%(ctag)s Generated at %(date)s by %(host)s
[9283]195%(ctag)s
[8242]196""" % { 'ctag' : ctag, 'date' : time.ctime(), 'host' : socket.gethostname() }
197
[8257]198
199
[8242]200def parseaddr(s):
[8257]201 """ Process IPv4 CIDR notation addr to a (binary) number """
[8242]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
[8257]208
209
[8242]210def showaddr(a):
[8257]211 """ Display IPv4 addr in (dotted) CIDR notation """
[8242]212 return "%d.%d.%d.%d" % ((a >> 24) & 0xff, (a >> 16) & 0xff, (a >> 8) & 0xff, a & 0xff)
213
[8257]214
[8584]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
[8257]223
[8584]224
225
[9283]226
[8242]227def netmask2subnet(netmask):
[8257]228 """ Given a 'netmask' return corresponding CIDR """
[8242]229 return showaddr(0xffffffff & (0xffffffff << (32 - int(netmask))))
230
[8257]231
232
[8242]233def generate_dnsmasq_conf(datadump):
[8257]234 """ Generate configuration file '/usr/local/etc/dnsmasq.conf' """
[8242]235 output = generate_header()
236 output += """\
[9283]237# DHCP server options
[8242]238dhcp-authoritative
239dhcp-fqdn
240domain=dhcp.%(nodename_lower)s.%(domain)s
241domain-needed
242expand-hosts
[10120]243log-async=100
[8242]244
245# Low memory footprint
246cache-size=10000
247 \n""" % datadump
248
249 for iface_key in datadump['iface_keys']:
[8262]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]
[8242]253
254 try:
[8257]255 (dhcp_start, dhcp_stop) = datadump[iface_key]['dhcp'].split('-')
[8242]256 (ip, netmask) = datadump[iface_key]['ip'].split('/')
257 datadump[iface_key]['subnet'] = netmask2subnet(netmask)
[8262]258 except (AttributeError, ValueError):
[8242]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]
[9283]266
[8242]267 return output
268
[8257]269
270
[8242]271def generate_rc_conf_local(datadump):
[8257]272 """ Generate configuration file '/etc/rc.conf.local' """
[10112]273 datadump['autogen_ileiden_enable'] = 'yes' if datadump['ileiden'] else 'no'
[10110]274
[10112]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
[8242]283 output = generate_header("#");
[10110]284 output += Template("""\
285hostname='{{ autogen_fqdn }}.{{ domain }}'
286location='{{ location }}'
287nodetype="{{ nodetype }}"
[9283]288
[10110]289{% if tproxy -%}
[8242]290tproxy_enable='YES'
[10110]291tproxy_range='{{ tproxy }}'
292{% else -%}
293tproxy_enable='NO'
294{% endif -%}
[9283]295
[10190]296{% if nodetype == "Proxy" %}
[10054]297#
298# PROXY Configuration
299#
[10188]300{% if internalroute -%}
[10054]301static_routes="wleiden"
[10110]302route_wleiden="-net 172.16.0.0/12 {{ internalroute }}"
[10188]303{% endif -%}
304
[10110]305{% if gateway -%}
306defaultrouter="{{ gateway }}"
307{% else -%}
308#defaultrouter="NOTSET"
309{% endif -%}
[10053]310
[10110]311internalif="{{ internalif }}"
[10054]312
313# PROXY iLeiden Configuration
[10112]314lvrouted_enable="{{ autogen_ileiden_enable }}"
315lvrouted_flags="-u -s s00p3rs3kr3t -m 28"
316ileiden_enable="{{ autogen_ileiden_enable }}"
317gateway_enable="{{ autogen_ileiden_enable }}"
318firewall_enable="{{ autogen_ileiden_enable }}"
[10054]319firewall_script="/etc/ipfw.sh"
[10112]320firewall_nat_enable="{{ autogen_ileiden_enable }}"
[10110]321{% endif -%}
[10054]322
[10110]323{% if nodetype == "CNode" %}
[10112]324#
[10054]325# NODE iLeiden Configuration
[10112]326#
327# iLeiden Proxies {{ autogen_ileiden_proxies_names }}
328lvrouted_flags="-u -s s00p3rs3kr3t -m 28 -z {{ autogen_ileiden_proxies }}"
329
[10054]330captive_portal_whitelist=""
[10110]331captive_portal_interfaces="{{ autogen_dhcp_interfaces }}"
332{% endif %}
[10054]333
[10183]334{% if nodetype == "Hybrid" %}
335#
336# Hybrid Node
337#
[10190]338{% if internalroute -%}
339static_routes="wleiden"
340route_wleiden="-net 172.16.0.0/12 {{ internalroute }}"
341{% endif -%}
342
343{% if gateway -%}
344defaultrouter="{{ gateway }}"
345{% else -%}
346#defaultrouter="NOTSET"
347{% endif -%}
348
349internalif="{{ internalif }}"
350{% if vpnif -%}
351 vpnif="{{ vpnif }}"\n
352{% endif -%}
353
354lvrouted_enable="{{ autogen_ileiden_enable }}"
[10183]355lvrouted_flags="-u -s s00p3rs3kr3t -m 28"
356
[10190]357gateway_enable="{{ autogen_ileiden_enable }}"
358
359ileiden_enable="{{ autogen_ileiden_enable }}"
360firewall_enable="{{ autogen_ileiden_enable }}"
361firewall_script="/etc/ipfw.sh"
362
[10183]363captive_portal_whitelist=""
364captive_portal_interfaces="{{ autogen_dhcp_interfaces }}"
365{% endif %}
366
[10110]367""").render(datadump)
368
[8242]369 # lo0 configuration:
370 # - 172.32.255.1/32 is the proxy.wleiden.net deflector
[9283]371 # - masterip is special as it needs to be assigned to at
[8242]372 # least one interface, so if not used assign to lo0
[9808]373 addrs_list = { 'lo0' : [("127.0.0.1/8", "LocalHost"), ("172.31.255.1/32","Proxy IP")] }
[9283]374 iface_map = {'lo0' : 'lo0'}
[8242]375
[8297]376 masterip_used = False
377 for iface_key in datadump['iface_keys']:
378 if datadump[iface_key]['ip'].startswith(datadump['masterip']):
379 masterip_used = True
380 break
[9283]381 if not masterip_used:
[10108]382 addrs_list['lo0'].append((datadump['masterip'] + "/32", 'Master IP Not used in interface'))
[8297]383
[8242]384 for iface_key in datadump['iface_keys']:
385 ifacedump = datadump[iface_key]
[10162]386 ifname = ifacedump['autogen_ifname']
[8242]387
388 # Add interface IP to list
[9808]389 item = (ifacedump['ip'], ifacedump['desc'])
[10162]390 if addrs_list.has_key(ifname):
391 addrs_list[ifname].append(item)
[8242]392 else:
[10162]393 addrs_list[ifname] = [item]
[8242]394
395 # Alias only needs IP assignment for now, this might change if we
396 # are going to use virtual accesspoints
397 if "alias" in iface_key:
398 continue
399
400 # XXX: Might want to deduct type directly from interface name
401 if ifacedump['type'] in ['11a', '11b', '11g', 'wireless']:
402 # Default to station (client) mode
403 ifacedump['wlanmode'] = "sta"
[10166]404 if ifacedump['mode'] in ['master', 'master-wds', 'ap', 'ap-wds']:
[8242]405 ifacedump['wlanmode'] = "ap"
406 # Default to 802.11b mode
407 ifacedump['mode'] = '11b'
408 if ifacedump['type'] in ['11a', '11b' '11g']:
[9283]409 ifacedump['mode'] = ifacedump['type']
[8242]410
411 if not ifacedump.has_key('channel'):
412 if ifacedump['type'] == '11a':
413 ifacedump['channel'] = 36
414 else:
415 ifacedump['channel'] = 1
416
417 # Allow special hacks at the back like wds and stuff
418 if not ifacedump.has_key('extra'):
419 ifacedump['extra'] = 'regdomain ETSI country NL'
420
[10054]421 output += "wlans_%(interface)s='%(autogen_ifname)s'\n" % ifacedump
422 output += ("create_args_%(autogen_ifname)s='wlanmode %(wlanmode)s mode " +\
[8274]423 "%(mode)s ssid %(ssid)s %(extra)s channel %(channel)s'\n") % ifacedump
[9283]424
[8242]425 elif ifacedump['type'] in ['ethernet', 'eth']:
426 # No special config needed besides IP
427 pass
428 else:
429 assert False, "Unknown type " + ifacedump['type']
430
[9283]431 # Print IP address which needs to be assigned over here
[8242]432 output += "\n"
433 for iface,addrs in sorted(addrs_list.iteritems()):
[10079]434 for addr, comment in sorted(addrs,key=lambda x: parseaddr(x[0].split('/')[0])):
[9808]435 output += "# %s || %s || %s\n" % (iface, addr, comment)
[10162]436 output += "ipv4_addrs_%s='%s'\n\n" % (iface, " ".join([x[0] for x in addrs]))
[8242]437
438 return output
439
[8257]440
441
[8242]442def get_yaml(item):
[8257]443 """ Get configuration yaml for 'item'"""
[9284]444 gfile = os.path.join(NODE_DIR,item,'wleiden.yaml')
[8242]445
446 f = open(gfile, 'r')
[8588]447 datadump = yaml.load(f,Loader=Loader)
[10052]448 datadump['autogen_iface_keys'] = get_interface_keys(datadump)
[10054]449
450 wlan_count=0
451 for key in datadump['autogen_iface_keys']:
452 if datadump[key]['type'] in ['11a', '11b', '11g', 'wireless']:
453 datadump[key]['autogen_ifname'] = 'wlan%i' % wlan_count
454 wlan_count += 1
455 else:
[10162]456 datadump[key]['autogen_ifname'] = datadump[key]['interface'].split(':')[0]
[10054]457
458
459 dhcp_interfaces = [datadump[key]['autogen_ifname'] for key in datadump['autogen_iface_keys'] if datadump[key]['dhcp'] != 'no']
460 datadump['autogen_dhcp_interfaces'] = ' '.join(dhcp_interfaces)
[10053]461 datadump['autogen_item'] = item
[10054]462 datadump['autogen_fqdn'] = get_fqdn(datadump)
[8242]463 f.close()
464
465 return datadump
466
[10074]467def store_yaml(datadump, header=False):
[8588]468 """ Store configuration yaml for 'item'"""
[10053]469 item = datadump['autogen_item']
[9284]470 gfile = os.path.join(NODE_DIR,item,'wleiden.yaml')
[8257]471
[8588]472 f = open(gfile, 'w')
[10067]473 f.write(generate_wleiden_yaml(datadump, header))
[8588]474 f.close()
[8257]475
[8588]476
477
[8317]478def get_all_configs():
479 """ Get dict with key 'host' with all configs present """
480 configs = dict()
481 for host in get_hostlist():
482 datadump = get_yaml(host)
483 configs[host] = datadump
484 return configs
485
486
[8319]487def get_interface_keys(config):
488 """ Quick hack to get all interface keys, later stage convert this to a iterator """
[10054]489 return sorted([elem for elem in config.keys() if (elem.startswith('iface_') and not "lo0" in elem)])
[8317]490
[8319]491
[8317]492def get_used_ips(configs):
493 """ Return array of all IPs used in config files"""
494 ip_list = []
[8319]495 for config in configs:
[8317]496 ip_list.append(config['masterip'])
[8319]497 for iface_key in get_interface_keys(config):
[8317]498 l = config[iface_key]['ip']
499 addr, mask = l.split('/')
500 # Special case do not process
[8332]501 if valid_addr(addr):
502 ip_list.append(addr)
503 else:
[9728]504 logger.error("## IP '%s' in '%s' not valid" % (addr, config['nodename']))
[8317]505 return sorted(ip_list)
506
507
508
[8242]509def generate_resolv_conf(datadump):
[8257]510 """ Generate configuration file '/etc/resolv.conf' """
[8242]511 output = generate_header("#");
512 output += """\
513search wleiden.net
514# Try local (cache) first
515nameserver 127.0.0.1
[10053]516"""
517 if datadump['nodetype'] == 'Proxy':
518 output += """\
519nameserver 8.8.8.8 # Google Public NameServer
520nameserver 8.8.4.4 # Google Public NameServer
521"""
522 else:
523 output += """\
[9283]524# Proxies are recursive nameservers
[8242]525# needs to be in resolv.conf for dnsmasq as well
526""" % datadump
[10053]527 for proxy in get_proxylist():
528 proxy_ip = get_yaml(proxy)['masterip']
529 output += "nameserver %-15s # %s\n" % (proxy_ip, proxy)
[9283]530
[8242]531 return output
532
[10069]533def generate_motd(datadump):
534 """ Generate configuration file '/etc/motd' """
535 output = """\
536FreeBSD 9.0-RELEASE (kernel.wleiden) #0 r230587: Sun Jan 29 17:09:57 CET 2012
[8242]537
[10069]538 WWW: %(autogen_fqdn)s.wleiden.net - http://www.wirelessleiden.nl
[10113]539 Loc: %(location)s
[8257]540
[10069]541Interlinks:
542""" % datadump
543
544 # XXX: This is a hacky way to get the required data
545 for line in generate_rc_conf_local(datadump).split('\n'):
546 if '||' in line and not line[1:].split()[0] in ['lo0', 'ath0'] :
547 output += " - %s \n" % line[1:]
548 output += """\
549Attached bridges:
550"""
551 for iface_key in datadump['autogen_iface_keys']:
552 ifacedump = datadump[iface_key]
553 if ifacedump.has_key('ns_ip'):
554 output += " - %(interface)s || %(mode)s || %(ns_ip)s\n" % ifacedump
555
556 return output
557
558
[8267]559def format_yaml_value(value):
560 """ Get yaml value in right syntax for outputting """
561 if isinstance(value,str):
[10049]562 output = '"%s"' % value
[8267]563 else:
564 output = value
[9283]565 return output
[8267]566
567
568
569def format_wleiden_yaml(datadump):
[8242]570 """ Special formatting to ensure it is editable"""
[9283]571 output = "# Genesis config yaml style\n"
[8262]572 output += "# vim:ts=2:et:sw=2:ai\n"
[8242]573 output += "#\n"
574 iface_keys = [elem for elem in datadump.keys() if elem.startswith('iface_')]
575 for key in sorted(set(datadump.keys()) - set(iface_keys)):
[8267]576 output += "%-10s: %s\n" % (key, format_yaml_value(datadump[key]))
[9283]577
[8242]578 output += "\n\n"
[9283]579
[8272]580 key_order = [ 'comment', 'interface', 'ip', 'desc', 'sdesc', 'mode', 'type',
581 'extra_type', 'channel', 'ssid', 'dhcp' ]
582
[8242]583 for iface_key in sorted(iface_keys):
584 output += "%s:\n" % iface_key
[8272]585 for key in key_order + list(sorted(set(datadump[iface_key].keys()) - set(key_order))):
586 if datadump[iface_key].has_key(key):
[9283]587 output += " %-11s: %s\n" % (key, format_yaml_value(datadump[iface_key][key]))
[8242]588 output += "\n\n"
589
590 return output
591
592
[8257]593
[10067]594def generate_wleiden_yaml(datadump, header=True):
[8267]595 """ Generate (petty) version of wleiden.yaml"""
[10053]596 for key in datadump.keys():
597 if key.startswith('autogen_'):
598 del datadump[key]
[10054]599 # Interface autogen cleanups
600 elif type(datadump[key]) == dict:
601 for key2 in datadump[key].keys():
602 if key2.startswith('autogen_'):
603 del datadump[key][key2]
604
[10067]605 output = generate_header("#") if header else ''
[8267]606 output += format_wleiden_yaml(datadump)
607 return output
608
609
[8588]610def generate_yaml(datadump):
611 return generate_config(datadump['nodename'], "wleiden.yaml", datadump)
[8267]612
[8588]613
[9283]614
[8298]615def generate_config(node, config, datadump=None):
[8257]616 """ Print configuration file 'config' of 'node' """
[8267]617 output = ""
[8242]618 try:
619 # Load config file
[8298]620 if datadump == None:
621 datadump = get_yaml(node)
[9283]622
[8267]623 # Preformat certain needed variables for formatting and push those into special object
624 datadump_extra = copy.deepcopy(datadump)
625 if not datadump_extra.has_key('domain'):
626 datadump_extra['domain'] = 'wleiden.net'
627 datadump_extra['nodename_lower'] = datadump_extra['nodename'].lower()
628 datadump_extra['iface_keys'] = sorted([elem for elem in datadump.keys() if elem.startswith('iface_')])
629
[8242]630 if config == 'wleiden.yaml':
[8267]631 output += generate_wleiden_yaml(datadump)
632 elif config == 'authorized_keys':
[10051]633 f = open(os.path.join(NODE_DIR,"global_keys"), 'r')
[8267]634 output += f.read()
[8242]635 f.close()
636 elif config == 'dnsmasq.conf':
[8267]637 output += generate_dnsmasq_conf(datadump_extra)
[8242]638 elif config == 'rc.conf.local':
[8267]639 output += generate_rc_conf_local(datadump_extra)
[8242]640 elif config == 'resolv.conf':
[8267]641 output += generate_resolv_conf(datadump_extra)
[10069]642 elif config == 'motd':
643 output += generate_motd(datadump_extra)
[8242]644 else:
[9283]645 assert False, "Config not found!"
[8242]646 except IOError, e:
[8267]647 output += "[ERROR] Config file not found"
648 return output
[8242]649
650
[8257]651
[8258]652def process_cgi_request():
653 """ When calling from CGI """
654 # Update repository if requested
655 form = cgi.FieldStorage()
656 if form.getvalue("action") == "update":
[8259]657 print "Refresh: 5; url=."
[8258]658 print "Content-type:text/plain\r\n\r\n",
659 print "[INFO] Updating subverion, please wait..."
[10143]660 print subprocess.Popen(['svn', 'cleanup', "%s/.." % NODE_DIR], stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0],
[10071]661 print subprocess.Popen(['svn', 'up', "%s/.." % NODE_DIR], stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0],
[8258]662 print "[INFO] All done, redirecting in 5 seconds"
663 sys.exit(0)
[9283]664
665
[8258]666 uri = os.environ['PATH_INFO'].strip('/').split('/')
[8267]667 output = ""
[8258]668 if not uri[0]:
[10070]669 if is_text_request():
[10060]670 output += "Content-type:text/plain\r\n\r\n"
671 output += '\n'.join(get_hostlist())
672 else:
673 output += "Content-type:text/html\r\n\r\n"
674 output += generate_title(get_hostlist())
[8258]675 elif len(uri) == 1:
[8267]676 output += "Content-type:text/plain\r\n\r\n"
677 output += generate_node(uri[0])
[8258]678 elif len(uri) == 2:
[8267]679 output += "Content-type:text/plain\r\n\r\n"
680 output += generate_config(uri[0], uri[1])
[8258]681 else:
682 assert False, "Invalid option"
[8267]683 print output
[8242]684
[8588]685def get_fqdn(datadump):
686 # Proxy naming convention is special
687 if datadump['nodetype'] == 'Proxy':
688 fqdn = datadump['nodename']
689 else:
690 # By default the full name is listed and also a shortname CNAME for easy use.
691 fqdn = datadump['nodetype'] + datadump['nodename']
692 return(fqdn)
[8259]693
[9283]694
695
[9284]696def make_dns(output_dir = 'dns'):
[8588]697 items = dict()
[8598]698
[8588]699 # hostname is key, IP is value
700 wleiden_zone = dict()
701 wleiden_cname = dict()
[8598]702
[8588]703 pool = dict()
704 for node in get_hostlist():
[9697]705 logger.info("Processing host %s", node)
[8588]706 datadump = get_yaml(node)
[9283]707
[8588]708 # Proxy naming convention is special
709 fqdn = get_fqdn(datadump)
710 if datadump['nodetype'] == 'CNode':
711 wleiden_cname[datadump['nodename']] = fqdn
712
713 wleiden_zone[fqdn] = datadump['masterip']
714
[8598]715 # Hacking to get proper DHCP IPs and hostnames
[8588]716 for iface_key in get_interface_keys(datadump):
[8598]717 iface_name = datadump[iface_key]['interface'].replace(':',"-alias-")
[8588]718 (ip, netmask) = datadump[iface_key]['ip'].split('/')
719 try:
720 (dhcp_start, dhcp_stop) = datadump[iface_key]['dhcp'].split('-')
721 datadump[iface_key]['subnet'] = netmask2subnet(netmask)
722 dhcp_part = ".".join(ip.split('.')[0:3])
723 if ip != datadump['masterip']:
724 wleiden_zone["dhcp-gateway-%s.%s" % (iface_name, fqdn)] = ip
725 for i in range(int(dhcp_start), int(dhcp_stop) + 1):
726 wleiden_zone["dhcp-%s-%s.%s" % (i, iface_name, fqdn)] = "%s.%s" % (dhcp_part, i)
727 except (AttributeError, ValueError):
728 # First push it into a pool, to indentify the counter-part later on
729 addr = parseaddr(ip)
730 netmask = int(netmask)
731 addr = addr & ~((1 << (32 - netmask)) - 1)
[9283]732 if pool.has_key(addr):
[8588]733 pool[addr] += [(iface_name, fqdn, ip)]
[9283]734 else:
[8588]735 pool[addr] = [(iface_name, fqdn, ip)]
736 continue
737
[9286]738
739 def pool_to_name(node, pool_members):
740 """Convert the joined name to a usable pool name"""
741
742 # Get rid of the own entry
743 pool_members = list(set(pool_members) - set([fqdn]))
744
745 target = oldname = ''
746 for node in sorted(pool_members):
747 (name, number) = re.match('^([A-Za-z]+)([0-9]*)$',node).group(1,2)
748 target += "-" + number if name == oldname else "-" + node if target else node
749 oldname = name
750
751 return target
752
753
[9957]754 # WL uses an /29 to configure an interface. IP's are ordered like this:
[9958]755 # MasterA (.1) -- DeviceA (.2) <<>> DeviceB (.3) --- SlaveB (.4)
[9957]756
757 sn = lambda x: re.sub(r'(?i)^cnode','',x)
758
[8598]759 # Automatic naming convention of interlinks namely 2 + remote.lower()
[8588]760 for (key,value) in pool.iteritems():
[9958]761 # Make sure they are sorted from low-ip to high-ip
762 value = sorted(value, key=lambda x: parseaddr(x[2]))
763
[8588]764 if len(value) == 1:
765 (iface_name, fqdn, ip) = value[0]
766 wleiden_zone["2unused-%s.%s" % (iface_name, fqdn)] = ip
[9957]767
768 # Device DNS names
769 if 'cnode' in fqdn.lower():
770 wleiden_zone["d-at-%s.%s" % (iface_name, fqdn)] = showaddr(parseaddr(ip) + 1)
771 wleiden_cname["d-at-%s.%s" % (iface_name,sn(fqdn))] = "d-at-%s.%s" % (iface_name, fqdn)
772
[8588]773 elif len(value) == 2:
774 (a_iface_name, a_fqdn, a_ip) = value[0]
775 (b_iface_name, b_fqdn, b_ip) = value[1]
776 wleiden_zone["2%s.%s" % (b_fqdn,a_fqdn)] = a_ip
777 wleiden_zone["2%s.%s" % (a_fqdn,b_fqdn)] = b_ip
[9957]778
779 # Device DNS names
780 if 'cnode' in a_fqdn.lower() and 'cnode' in b_fqdn.lower():
781 wleiden_zone["d-at-%s.%s" % (a_iface_name, a_fqdn)] = showaddr(parseaddr(a_ip) + 1)
[9958]782 wleiden_zone["d-at-%s.%s" % (b_iface_name, b_fqdn)] = showaddr(parseaddr(b_ip) - 1)
[9957]783 wleiden_cname["d-at-%s.%s" % (a_iface_name,sn(a_fqdn))] = "d-at-%s.%s" % (a_iface_name, a_fqdn)
784 wleiden_cname["d-at-%s.%s" % (b_iface_name,sn(b_fqdn))] = "d-at-%s.%s" % (b_iface_name, b_fqdn)
785 wleiden_cname["d2%s.%s" % (sn(b_fqdn),sn(a_fqdn))] = "d-at-%s.%s" % (a_iface_name, a_fqdn)
786 wleiden_cname["d2%s.%s" % (sn(a_fqdn),sn(b_fqdn))] = "d-at-%s.%s" % (b_iface_name, b_fqdn)
787
[8588]788 else:
789 pool_members = [k[1] for k in value]
790 for item in value:
[9283]791 (iface_name, fqdn, ip) = item
[9286]792 pool_name = "2pool-" + showaddr(key).replace('.','-') + "-" + pool_to_name(fqdn,pool_members)
[8588]793 wleiden_zone["%s.%s" % (pool_name, fqdn)] = ip
[8598]794
795 # Include static DNS entries
796 # XXX: Should they override the autogenerated results?
797 # XXX: Convert input to yaml more useable.
798 # Format:
799 ##; this is a comment
800 ## roomburgh=CNodeRoomburgh1
801 ## apkerk1.CNodeVosko=172.17.176.8 ;this as well
[9284]802 dns = yaml.load(open(os.path.join(NODE_DIR,'../dns/staticDNS.yaml'),'r'))
[9938]803
804 # Hack to allow special entries, for development
805 wleiden_raw = dns['raw']
806 del dns['raw']
807
[8622]808 for comment, block in dns.iteritems():
809 for k,v in block.iteritems():
[8598]810 if valid_addr(v):
811 wleiden_zone[k] = v
812 else:
813 wleiden_cname[k] = v
[9283]814
[8598]815 details = dict()
816 # 24 updates a day allowed
817 details['serial'] = time.strftime('%Y%m%d%H')
818
819 dns_header = '''
820$TTL 3h
821%(zone)s. SOA sunny.wleiden.net. beheer.lijst.wirelessleiden.nl. ( %(serial)s 1d 12h 1w 3h )
822 ; Serial, Refresh, Retry, Expire, Neg. cache TTL
823
824 NS sunny.wleiden.net.
825 \n'''
826
[9283]827
[8598]828 if not os.path.isdir('dns'):
829 os.makedirs('dns')
830 details['zone'] = 'wleiden.net'
[9284]831 f = open(os.path.join(output_dir,"db." + details['zone']), "w")
[8598]832 f.write(dns_header % details)
833
[8588]834 for host,ip in wleiden_zone.iteritems():
[8598]835 if valid_addr(ip):
[9283]836 f.write("%s.wleiden.net. IN A %s \n" % (host.lower(), ip))
[8588]837 for source,dest in wleiden_cname.iteritems():
[8636]838 f.write("%s.wleiden.net. IN CNAME %s.wleiden.net.\n" % (source.lower(), dest.lower()))
[9938]839 for source, dest in wleiden_raw.iteritems():
840 f.write("%s.wleiden.net. %s\n" % (source, dest))
[8588]841 f.close()
[9283]842
[8598]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
[9284]846 f = open(os.path.join(output_dir,"db." + details['zone']), "w")
[8598]847 f.write(dns_header % details)
[8588]848
[8598]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('.')))
[9283]855 f.write("%s.in-addr.arpa. IN PTR %s.wleiden.net.\n" % (rev_ip.lower(), host.lower()))
[8598]856 f.close()
[8588]857
[8598]858
[8259]859def usage():
[8598]860 print """Usage: %s <standalone [port] |test [test arguments]|static|dns>
[8259]861Examples:
[9284]862\tdns [outputdir] = Generate BIND compliant zone files in dns.
[8259]863\tstandalone = Run configurator webserver [default port=8000]
[9589]864\twind-export = Generate SQL import scripts for WIND database
865\tfull-export = Generate yaml export script for heatmap.
[8296]866\tstatic = Generate all config files and store on disk
867\t with format ./static/%%NODE%%/%%FILE%%
[9283]868\ttest CNodeRick dnsmasq.conf = Receive output of CGI script
[8259]869\t for arguments CNodeRick/dnsmasq.conf
[9971]870\tlist <nodes|proxies> = List systems which marked up.
[8259]871"""
872 exit(0)
873
874
[10070]875def is_text_request():
[10107]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
[8259]881
[8267]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()
[9283]888
[8267]889 if sys.argv[1] == "standalone":
890 import SocketServer
891 import CGIHTTPServer
[10105]892 # Hop to the right working directory.
893 os.chdir(os.path.dirname(__file__))
[8267]894 try:
895 PORT = int(sys.argv[2])
896 except (IndexError,ValueError):
897 PORT = 8000
[9283]898
[8267]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
[9283]904
[8267]905 self.cgi_info = (__file__, self.path)
906 self.path = ''
907 return True
908 handler = MyCGIHTTPRequestHandler
[9807]909 SocketServer.TCPServer.allow_reuse_address = True
[8267]910 httpd = SocketServer.TCPServer(("", PORT), handler)
911 httpd.server_name = 'localhost'
912 httpd.server_port = PORT
[9283]913
[9728]914 logger.info("serving at port %s", PORT)
[8860]915 try:
916 httpd.serve_forever()
917 except KeyboardInterrupt:
918 httpd.shutdown()
[9728]919 logger.info("All done goodbye")
[8267]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()
[10107]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
[8296]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'])
[8298]943 datadump = get_yaml(node)
[8296]944 for config in files:
945 items['config'] = config
[9728]946 logger.info("## Generating %(node)s %(config)s" % items)
[8296]947 f = open("%(wdir)s/%(config)s" % items, "w")
[8298]948 f.write(generate_config(node, config, datadump))
[8296]949 f.close()
[9514]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
[9589]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
[8584]985 elif sys.argv[1] == "dns":
[9285]986 make_dns(sys.argv[2] if len(sys.argv) > 2 else 'dns')
[9283]987 elif sys.argv[1] == "cleanup":
[8588]988 # First generate all datadumps
989 datadumps = dict()
990 for host in get_hostlist():
[9728]991 logger.info("# Processing: %s", host)
[8588]992 datadump = get_yaml(host)
993 datadumps[get_fqdn(datadump)] = datadump
[9283]994
[10156]995 for host,datadump in datadumps.iteritems():
[8622]996 datadump['latitude'], datadump['longitude'] = rdnap.rd2etrs(datadump['rdnap_x'], datadump['rdnap_y'])
[10156]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:]
[10162]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'
[10074]1008 store_yaml(datadump)
[9971]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
[9283]1020 else:
1021 usage()
1022 else:
[10070]1023 # Do not enable debugging for config requests as it highly clutters the output
1024 if not is_text_request():
1025 cgitb.enable()
[9283]1026 process_cgi_request()
1027
1028
1029if __name__ == "__main__":
1030 main()
Note: See TracBrowser for help on using the repository browser.