source: genesis/tools/gformat.py@ 10281

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

Make the default node page a bit more usefull for daily usage.

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