source: genesis/tools/gformat.py@ 10391

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

Fix typo in hostgroup.

While here, fix the wrong key autogen_fqdn and introduce autogen_realname which does this the proper way.

Related-To: beheer#176

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