source: genesis/tools/gformat.py@ 10731

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

'Gewone' Hybrid nodes hebben ook lvrouted vlaggetjes nodes.

Fixes: nodefactory#155

  • Property svn:executable set to *
  • Property svn:keywords set to Id
File size: 47.4 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
[10729]33import math
[10378]34import make_network_kml
[8584]35from pprint import pprint
[10281]36from collections import defaultdict
[8575]37try:
38 import yaml
39except ImportError, e:
40 print e
41 print "[ERROR] Please install the python-yaml or devel/py-yaml package"
42 exit(1)
[8588]43
44try:
45 from yaml import CLoader as Loader
46 from yaml import CDumper as Dumper
47except ImportError:
48 from yaml import Loader, Dumper
49
[10584]50from jinja2 import Environment, Template
51def yesorno(value):
52 return "YES" if bool(value) else "NO"
53env = Environment()
54env.filters['yesorno'] = yesorno
55def render_template(datadump, template):
56 result = env.from_string(template).render(datadump)
57 # Make it look pretty to the naked eye, as jinja templates are not so
58 # friendly when it comes to whitespace formatting
59 ## Remove extra whitespace at end of line lstrip() style.
60 result = re.sub(r'\n[\ ]+','\n', result)
61 ## Include only a single newline between an definition and a comment
62 result = re.sub(r'(["\'])\n+([a-z]|\n#\n)',r'\1\n\2', result)
63 ## Remove extra newlines after single comment
64 result = re.sub(r'(#\n)\n+([a-z])',r'\1\2', result)
65 return result
[10110]66
[9697]67import logging
68logging.basicConfig(format='# %(levelname)s: %(message)s' )
69logger = logging.getLogger()
70logger.setLevel(logging.DEBUG)
[8242]71
[9283]72
[8948]73if os.environ.has_key('CONFIGROOT'):
74 NODE_DIR = os.environ['CONFIGROOT']
75else:
[9283]76 NODE_DIR = os.path.abspath(os.path.dirname(__file__)) + '/../nodes'
[8242]77__version__ = '$Id: gformat.py 10731 2012-05-08 22:19:13Z rick $'
78
[8267]79
[9283]80files = [
[8242]81 'authorized_keys',
82 'dnsmasq.conf',
[10410]83 'dhcpd.conf',
[8242]84 'rc.conf.local',
85 'resolv.conf',
[10069]86 'motd',
[10654]87 'ntp.conf',
[10705]88 'pf.hybrid.conf.local',
[10054]89 'wleiden.yaml',
[8242]90 ]
91
[8319]92# Global variables uses
[8323]93OK = 10
94DOWN = 20
95UNKNOWN = 90
[8257]96
[10391]97def get_yaml(item):
98 """ Get configuration yaml for 'item'"""
99 gfile = os.path.join(NODE_DIR,item,'wleiden.yaml')
[8257]100
[10461]101 # Use some boring defaults
[10702]102 datadump = {}
[10391]103 f = open(gfile, 'r')
[10461]104 datadump.update(yaml.load(f,Loader=Loader))
[10702]105 if datadump['nodetype'] == 'Hybrid':
106 defaults = { 'service_proxy_normal' : False, 'service_proxy_ileiden' : False, 'service_accesspoint' : True }
107 for (key,value) in defaults.iteritems():
108 if not datadump.has_key(key):
109 datadump[key] = value
[10391]110 f.close()
111
112 # Preformat certain needed variables for formatting and push those into special object
113 datadump['autogen_iface_keys'] = get_interface_keys(datadump)
114
115 wlan_count=0
116 for key in datadump['autogen_iface_keys']:
117 if datadump[key]['type'] in ['11a', '11b', '11g', 'wireless']:
118 datadump[key]['autogen_ifname'] = 'wlan%i' % wlan_count
119 wlan_count += 1
120 else:
121 datadump[key]['autogen_ifname'] = datadump[key]['interface'].split(':')[0]
122
[10459]123 dhcp_interfaces = [datadump[key]['autogen_ifname'] for key in datadump['autogen_iface_keys'] if datadump[key]['dhcp']]
124 datadump['autogen_dhcp_interfaces'] = ','.join(dhcp_interfaces)
[10391]125 datadump['autogen_item'] = item
126
127 datadump['autogen_realname'] = get_realname(datadump)
128 datadump['autogen_domain'] = datadump['domain'] if datadump.has_key('domain') else 'wleiden.net.'
129 datadump['autogen_fqdn'] = datadump['autogen_realname'] + '.' + datadump['autogen_domain']
130 return datadump
131
132
133def store_yaml(datadump, header=False):
134 """ Store configuration yaml for 'item'"""
135 item = datadump['autogen_item']
136 gfile = os.path.join(NODE_DIR,item,'wleiden.yaml')
137
138 f = open(gfile, 'w')
139 f.write(generate_wleiden_yaml(datadump, header))
140 f.close()
141
142
[10729]143def network(ip):
144 addr, mask = ip.split('/')
145 # Not parsing of these folks please
146 addr = parseaddr(addr)
147 mask = int(mask)
148 network = addr & ~((1 << (32 - mask)) - 1)
149 return network
150
[10391]151
[10729]152
153def make_relations(datadumps=None):
[10270]154 """ Process _ALL_ yaml files to get connection relations """
[10729]155 errors = []
[10281]156 poel = defaultdict(list)
[10729]157
158 if not datadumps:
159 for host in get_hostlist():
160 datadumps[host] = get_yaml(host)
161
162 for host, datadump in datadumps.iteritems():
[10270]163 try:
164 for iface_key in datadump['autogen_iface_keys']:
[10729]165 net_addr = network(datadump[iface_key]['ip'])
166 poel[net_addr] += [(host,datadump[iface_key])]
[10270]167 except (KeyError, ValueError), e:
[10729]168 errors.append("[FOUT] in '%s' interface '%s' (%s)" % (host,iface_key, e))
[10270]169 continue
170 return (poel, errors)
171
172
[8267]173
[8321]174def valid_addr(addr):
175 """ Show which address is valid in which are not """
176 return str(addr).startswith('172.')
177
[10692]178def get_system_list(prefix):
179 return sorted([os.path.basename(os.path.dirname(x)) for x in glob.glob("%s/%s*/wleiden.yaml" % (NODE_DIR, prefix))])
[8321]180
[10692]181get_hybridlist = lambda: get_system_list("Hybrid")
182get_nodelist = lambda: get_system_list("CNode")
183get_proxylist = lambda: get_system_list("Proxy")
[8267]184
[8296]185def get_hostlist():
186 """ Combined hosts and proxy list"""
[10192]187 return get_nodelist() + get_proxylist() + get_hybridlist()
[8267]188
[8588]189def angle_between_points(lat1,lat2,long1,long2):
[9283]190 """
[8588]191 Return Angle in radians between two GPS coordinates
192 See: http://stackoverflow.com/questions/3809179/angle-between-2-gps-coordinates
193 """
194 dy = lat2 - lat1
[10729]195 dx = math.cos(lat1)*(long2 - long1)
[8588]196 angle = math.atan2(dy,dx)
197 return angle
[8267]198
[10729]199
200
[8588]201def angle_to_cd(angle):
202 """ Return Dutch Cardinal Direction estimation in 'one digit' of radian angle """
203
204 # For easy conversion get positive degree
205 degrees = math.degrees(angle)
[10729]206 abs_degrees = 360 + degrees if degrees < 0 else degrees
[8588]207
208 # Numbers can be confusing calculate from the 4 main directions
209 p = 22.5
[10729]210 if abs_degrees < p:
211 cd = "n"
212 elif abs_degrees < (90 - p):
213 cd = "no"
214 elif abs_degrees < (90 + p):
215 cd = "o"
216 elif abs_degrees < (180 - p):
217 cd = "zo"
218 elif abs_degrees < (180 + p):
219 cd = "z"
220 elif abs_degrees < (270 - p):
221 cd = "zw"
222 elif abs_degrees < (270 + p):
223 cd = "w"
224 elif abs_degrees < (360 - p):
225 cd = "nw"
[8588]226 else:
[10729]227 cd = "n"
228 return cd
[8588]229
230
[10729]231
232def cd_between_hosts(hostA, hostB, datadumps):
233 # Using RDNAP coordinates
234 dx = float(int(datadumps[hostA]['rdnap_x']) - int(datadumps[hostB]['rdnap_x'])) * -1
235 dy = float(int(datadumps[hostA]['rdnap_y']) - int(datadumps[hostB]['rdnap_y'])) * -1
236 return angle_to_cd(math.atan2(dx,dy))
237
238 # GPS coordinates seems to fail somehow
239 #latA = float(datadumps[hostA]['latitude'])
240 #latB = float(datadumps[hostB]['latitude'])
241 #lonA = float(datadumps[hostA]['longitude'])
242 #lonB = float(datadumps[hostB]['longitude'])
243 #return angle_to_cd(angle_between_points(latA, latB, lonA, lonB))
244
245
[8267]246def generate_title(nodelist):
[8257]247 """ Main overview page """
[9283]248 items = {'root' : "." }
[10682]249 def fl(spaces, line):
250 return (' ' * spaces) + line + '\n'
251
[8267]252 output = """
[8257]253<html>
254 <head>
255 <title>Wireless leiden Configurator - GFormat</title>
256 <style type="text/css">
257 th {background-color: #999999}
258 tr:nth-child(odd) {background-color: #cccccc}
259 tr:nth-child(even) {background-color: #ffffff}
260 th, td {padding: 0.1em 1em}
261 </style>
262 </head>
263 <body>
264 <center>
[8259]265 <form type="GET" action="%(root)s">
[8257]266 <input type="hidden" name="action" value="update">
267 <input type="submit" value="Update Configuration Database (SVN)">
268 </form>
269 <table>
[10682]270 <caption><h3>Wireless Leiden Configurator</h3></caption>
[8257]271 """ % items
[8242]272
[8296]273 for node in nodelist:
[8257]274 items['node'] = node
[10682]275 output += fl(5, '<tr>') + fl(7,'<td><a href="%(root)s/%(node)s">%(node)s</a></td>' % items)
[8257]276 for config in files:
277 items['config'] = config
[10682]278 output += fl(7,'<td><a href="%(root)s/%(node)s/%(config)s">%(config)s</a></td>' % items)
279 output += fl(5, "</tr>")
[8267]280 output += """
[8257]281 </table>
282 <hr />
283 <em>%s</em>
284 </center>
285 </body>
286</html>
287 """ % __version__
[8242]288
[8267]289 return output
[8257]290
291
[8267]292
293def generate_node(node):
[8257]294 """ Print overview of all files available for node """
[8267]295 return "\n".join(files)
[8242]296
[10270]297def generate_node_overview(host):
298 """ Print overview of all files available for node """
299 datadump = get_yaml(host)
300 params = { 'host' : host }
301 output = "<em><a href='..'>Back to overview</a></em><hr />"
302 output += "<h2>Available files:</h2><ul>"
303 for cf in files:
304 params['cf'] = cf
305 output += '<li><a href="%(host)s/%(cf)s">%(cf)s</a></li>\n' % params
306 output += "</ul>"
[8257]307
[10270]308 # Generate and connection listing
309 output += "<h2>Connected To:</h2><ul>"
[10281]310 (poel, errors) = make_relations()
311 for network, hosts in poel.iteritems():
312 if host in [x[0] for x in hosts]:
313 if len(hosts) == 1:
314 # Single not connected interface
315 continue
316 for remote,ifacedump in hosts:
317 if remote == host:
318 # This side of the interface
319 continue
320 params = { 'remote': remote, 'remote_ip' : ifacedump['ip'] }
321 output += '<li><a href="%(remote)s">%(remote)s</a> -- %(remote_ip)s</li>\n' % params
[10270]322 output += "</ul>"
[10281]323 output += "<h2>MOTD details:</h2><pre>" + generate_motd(datadump) + "</pre>"
[8257]324
[10270]325 output += "<hr /><em><a href='..'>Back to overview</a></em>"
326 return output
327
328
[8242]329def generate_header(ctag="#"):
330 return """\
[9283]331%(ctag)s
[8242]332%(ctag)s DO NOT EDIT - Automatically generated by 'gformat'
333%(ctag)s Generated at %(date)s by %(host)s
[9283]334%(ctag)s
[8242]335""" % { 'ctag' : ctag, 'date' : time.ctime(), 'host' : socket.gethostname() }
336
[8257]337
338
[8242]339def parseaddr(s):
[8257]340 """ Process IPv4 CIDR notation addr to a (binary) number """
[8242]341 f = s.split('.')
342 return (long(f[0]) << 24L) + \
343 (long(f[1]) << 16L) + \
344 (long(f[2]) << 8L) + \
345 long(f[3])
346
[8257]347
348
[8242]349def showaddr(a):
[8257]350 """ Display IPv4 addr in (dotted) CIDR notation """
[8242]351 return "%d.%d.%d.%d" % ((a >> 24) & 0xff, (a >> 16) & 0xff, (a >> 8) & 0xff, a & 0xff)
352
[8257]353
[8584]354def is_member(ip, mask, canidate):
355 """ Return True if canidate is part of ip/mask block"""
[10729]356 ip_addr = parseaddr(ip)
357 ip_canidate = parseaddr(canidate)
[8584]358 mask = int(mask)
359 ip_addr = ip_addr & ~((1 << (32 - mask)) - 1)
360 ip_canidate = ip_canidate & ~((1 << (32 - mask)) - 1)
361 return ip_addr == ip_canidate
[8257]362
[8584]363
364
[10410]365def cidr2netmask(netmask):
[8257]366 """ Given a 'netmask' return corresponding CIDR """
[8242]367 return showaddr(0xffffffff & (0xffffffff << (32 - int(netmask))))
368
[10410]369def get_network(addr, mask):
370 return showaddr(parseaddr(addr) & ~((1 << (32 - int(mask))) - 1))
[8257]371
372
[10410]373def generate_dhcpd_conf(datadump):
374 """ Generate config file '/usr/local/etc/dhcpd.conf """
375 output = generate_header()
376 output += Template("""\
377# option definitions common to all supported networks...
378option domain-name "dhcp.{{ autogen_fqdn }}";
379
380default-lease-time 600;
381max-lease-time 7200;
382
383# Use this to enble / disable dynamic dns updates globally.
384#ddns-update-style none;
385
386# If this DHCP server is the official DHCP server for the local
387# network, the authoritative directive should be uncommented.
388authoritative;
389
390# Use this to send dhcp log messages to a different log file (you also
391# have to hack syslog.conf to complete the redirection).
392log-facility local7;
393
394#
395# Interface definitions
396#
397\n""").render(datadump)
398
399 for iface_key in datadump['autogen_iface_keys']:
400 if not datadump[iface_key].has_key('comment'):
[10455]401 datadump[iface_key]['comment'] = None
[10410]402 output += "## %(interface)s - %(desc)s - %(comment)s\n" % datadump[iface_key]
403
404 (addr, mask) = datadump[iface_key]['ip'].split('/')
405 datadump[iface_key]['addr'] = addr
406 datadump[iface_key]['netmask'] = cidr2netmask(mask)
407 datadump[iface_key]['subnet'] = get_network(addr, mask)
408 try:
409 (dhcp_start, dhcp_stop) = datadump[iface_key]['dhcp'].split('-')
410 except (AttributeError, ValueError):
411 output += "subnet %(subnet)s netmask %(netmask)s {\n ### not autoritive\n}\n\n" % datadump[iface_key]
412 continue
413
414 dhcp_part = ".".join(addr.split('.')[0:3])
415 datadump[iface_key]['dhcp_start'] = dhcp_part + "." + dhcp_start
416 datadump[iface_key]['dhcp_stop'] = dhcp_part + "." + dhcp_stop
417 output += """\
418subnet %(subnet)s netmask %(netmask)s {
419 range %(dhcp_start)s %(dhcp_stop)s;
420 option routers %(addr)s;
421 option domain-name-servers %(addr)s;
422}
423\n""" % datadump[iface_key]
424
425 return output
426
427
428
[8242]429def generate_dnsmasq_conf(datadump):
[8257]430 """ Generate configuration file '/usr/local/etc/dnsmasq.conf' """
[8242]431 output = generate_header()
[10368]432 output += Template("""\
[9283]433# DHCP server options
[8242]434dhcp-authoritative
435dhcp-fqdn
[10391]436domain=dhcp.{{ autogen_fqdn }}
[8242]437domain-needed
438expand-hosts
[10120]439log-async=100
[8242]440
441# Low memory footprint
442cache-size=10000
443
[10368]444\n""").render(datadump)
445
[10281]446 for iface_key in datadump['autogen_iface_keys']:
[8262]447 if not datadump[iface_key].has_key('comment'):
[10455]448 datadump[iface_key]['comment'] = None
[8262]449 output += "## %(interface)s - %(desc)s - %(comment)s\n" % datadump[iface_key]
[8242]450
451 try:
[8257]452 (dhcp_start, dhcp_stop) = datadump[iface_key]['dhcp'].split('-')
[10410]453 (ip, cidr) = datadump[iface_key]['ip'].split('/')
454 datadump[iface_key]['netmask'] = cidr2netmask(cidr)
[8262]455 except (AttributeError, ValueError):
[8242]456 output += "# not autoritive\n\n"
457 continue
458
459 dhcp_part = ".".join(ip.split('.')[0:3])
460 datadump[iface_key]['dhcp_start'] = dhcp_part + "." + dhcp_start
461 datadump[iface_key]['dhcp_stop'] = dhcp_part + "." + dhcp_stop
[10410]462 output += "dhcp-range=%(interface)s,%(dhcp_start)s,%(dhcp_stop)s,%(netmask)s,24h\n\n" % datadump[iface_key]
[9283]463
[8242]464 return output
465
[8257]466
467
[8242]468def generate_rc_conf_local(datadump):
[8257]469 """ Generate configuration file '/etc/rc.conf.local' """
[10455]470 if not datadump.has_key('ileiden'):
471 datadump['autogen_ileiden_enable'] = False
472 else:
473 datadump['autogen_ileiden_enable'] = datadump['ileiden']
[10110]474
[10547]475 datadump['autogen_ileiden_enable'] = switchFormat(datadump['autogen_ileiden_enable'])
476
[10112]477 ileiden_proxies = []
[10367]478 normal_proxies = []
[10112]479 for proxy in get_proxylist():
480 proxydump = get_yaml(proxy)
481 if proxydump['ileiden']:
482 ileiden_proxies.append(proxydump)
[10367]483 else:
484 normal_proxies.append(proxydump)
[10461]485 for host in get_hybridlist():
486 hostdump = get_yaml(host)
[10584]487 if hostdump['service_proxy_ileiden']:
[10461]488 ileiden_proxies.append(hostdump)
[10584]489 if hostdump['service_proxy_normal']:
[10461]490 normal_proxies.append(hostdump)
491
[10585]492 datadump['autogen_ileiden_proxies'] = ileiden_proxies
493 datadump['autogen_normal_proxies'] = normal_proxies
494 datadump['autogen_ileiden_proxies_ips'] = ','.join([x['masterip'] for x in ileiden_proxies])
[10112]495 datadump['autogen_ileiden_proxies_names'] = ','.join([x['autogen_item'] for x in ileiden_proxies])
[10585]496 datadump['autogen_normal_proxies_ips'] = ','.join([x['masterip'] for x in normal_proxies])
[10367]497 datadump['autogen_normal_proxies_names'] = ','.join([x['autogen_item'] for x in normal_proxies])
[10112]498
[8242]499 output = generate_header("#");
[10584]500 output += render_template(datadump, """\
[10391]501hostname='{{ autogen_fqdn }}'
[10110]502location='{{ location }}'
503nodetype="{{ nodetype }}"
[9283]504
[10459]505#
506# Configured listings
507#
508captive_portal_whitelist=""
509{% if nodetype == "Proxy" %}
[10054]510#
[10459]511# Proxy Configuration
[10054]512#
[10110]513{% if gateway -%}
514defaultrouter="{{ gateway }}"
515{% else -%}
516#defaultrouter="NOTSET"
517{% endif -%}
518internalif="{{ internalif }}"
[10112]519ileiden_enable="{{ autogen_ileiden_enable }}"
520gateway_enable="{{ autogen_ileiden_enable }}"
[10238]521pf_enable="yes"
[10302]522pf_rules="/etc/pf.conf"
[10455]523{% if autogen_ileiden_enable -%}
[10234]524pf_flags="-D ext_if={{ externalif }} -D int_if={{ internalif }} -D publicnat={80,443}"
[10238]525lvrouted_enable="{{ autogen_ileiden_enable }}"
526lvrouted_flags="-u -s s00p3rs3kr3t -m 28"
527{% else -%}
528pf_flags="-D ext_if={{ externalif }} -D int_if={{ internalif }} -D publicnat={0}"
[10310]529{% endif -%}
[10238]530{% if internalroute -%}
531static_routes="wleiden"
532route_wleiden="-net 172.16.0.0/12 {{ internalroute }}"
[10110]533{% endif -%}
[10054]534
[10584]535{% elif nodetype == "Hybrid" %}
536 #
537 # Hybrid Configuration
538 #
[10599]539 list_ileiden_proxies="
[10585]540 {% for item in autogen_ileiden_proxies -%}
541 {{ "%-16s"|format(item.masterip) }} # {{ item.autogen_realname }}
542 {% endfor -%}
[10599]543 "
544 list_normal_proxies="
[10585]545 {% for item in autogen_normal_proxies -%}
546 {{ "%-16s"|format(item.masterip) }} # {{ item.autogen_realname }}
547 {% endfor -%}
[10599]548 "
[10585]549
[10584]550 captive_portal_interfaces="{{ autogen_dhcp_interfaces|default('none', true) }}"
551 externalif="{{ externalif|default('vr0', true) }}"
552 masterip="{{ masterip }}"
553
554 # Defined services
555 service_proxy_ileiden="{{ service_proxy_ileiden|yesorno }}"
556 service_proxy_normal="{{ service_proxy_normal|yesorno }}"
557 service_accesspoint="{{ service_accesspoint|yesorno }}"
558 #
[10459]559
[10587]560 {% if service_proxy_ileiden %}
[10584]561 pf_rules="/etc/pf.hybrid.conf"
562 pf_flags="-D ext_if=$externalif -D ext_if_net=$externalif:network -D masterip=$masterip"
[10587]563 pf_flags="$pf_flags -D publicnat=80,443"
564 {% elif service_proxy_normal %}
[10649]565 pf_rules="/etc/pf.hybrid.conf"
[10587]566 pf_flags="-D ext_if=$externalif -D ext_if_net=$externalif:network -D masterip=$masterip"
[10649]567 pf_flags="$pf_flags -D publicnat=0"
[10599]568 lvrouted_flags="$lvrouted_flags -z `make_list "$list_ileiden_proxies" ","`"
[10649]569 named_setfib="1"
570 tinyproxy_setfib="1"
571 dnsmasq_setfib="1"
[10698]572 sshd_setfib="1"
[10584]573 {% else %}
574 pf_rules="/etc/pf.node.conf"
[10587]575 pf_flags=""
[10731]576 lvrouted_flags="$lvrouted_flags -z `make_list "$list_ileiden_proxies" ","`"
[10584]577 {% endif %}
[10459]578
[10584]579 {% if service_proxy_normal %}
580 tinyproxy_enable="yes"
581 {% else %}
582 pen_wrapper_enable="yes"
583 {% endif %}
[10460]584
[10584]585 {% if service_accesspoint %}
586 pf_flags="$pf_flags -D captive_portal_interfaces=$captive_portal_interfaces"
587 {% endif %}
[10459]588
[10584]589 {% if board == "ALIX2" %}
590 #
591 # ''Fat'' configuration, board has 256MB RAM
592 #
593 dnsmasq_enable="NO"
594 named_enable="YES"
595 dhcpd_enable="YES"
596 {% endif -%}
[10459]597
[10584]598 {% if service_proxy_ileiden and gateway %}
599 defaultrouter="{{ gateway }}"
600 {% endif %}
601{% elif nodetype == "CNode" %}
[10459]602#
[10054]603# NODE iLeiden Configuration
[10112]604#
[10585]605
606# iLeiden Proxies {{ autogen_ileiden_proxies_names }}
607list_ileiden_proxies="{{ autogen_ileiden_proxies_ips }}"
608# normal Proxies {{ autogen_normal_proxies_names }}
609list_normal_proxies="{{ autogen_normal_proxies_ips }}"
610
[10564]611captive_portal_interfaces="{{ autogen_dhcp_interfaces }}"
[10367]612
613lvrouted_flags="-u -s s00p3rs3kr3t -m 28 -z $list_ileiden_proxies"
[10110]614{% endif %}
615
[10584]616#
617# Interface definitions
618#\n
619""")
620
[8242]621 # lo0 configuration:
622 # - 172.32.255.1/32 is the proxy.wleiden.net deflector
[9283]623 # - masterip is special as it needs to be assigned to at
[8242]624 # least one interface, so if not used assign to lo0
[9808]625 addrs_list = { 'lo0' : [("127.0.0.1/8", "LocalHost"), ("172.31.255.1/32","Proxy IP")] }
[9283]626 iface_map = {'lo0' : 'lo0'}
[10366]627 dhclient_if = {'lo0' : False}
[8242]628
[8297]629 masterip_used = False
[10281]630 for iface_key in datadump['autogen_iface_keys']:
[8297]631 if datadump[iface_key]['ip'].startswith(datadump['masterip']):
632 masterip_used = True
633 break
[9283]634 if not masterip_used:
[10108]635 addrs_list['lo0'].append((datadump['masterip'] + "/32", 'Master IP Not used in interface'))
[8297]636
[10281]637 for iface_key in datadump['autogen_iface_keys']:
[8242]638 ifacedump = datadump[iface_key]
[10162]639 ifname = ifacedump['autogen_ifname']
[8242]640
[10366]641 # Flag dhclient is possible
642 dhclient_if[ifname] = ifacedump.has_key('dhcpclient') and ifacedump['dhcpclient']
[10318]643
[8242]644 # Add interface IP to list
[9808]645 item = (ifacedump['ip'], ifacedump['desc'])
[10162]646 if addrs_list.has_key(ifname):
647 addrs_list[ifname].append(item)
[8242]648 else:
[10162]649 addrs_list[ifname] = [item]
[8242]650
651 # Alias only needs IP assignment for now, this might change if we
652 # are going to use virtual accesspoints
653 if "alias" in iface_key:
654 continue
655
656 # XXX: Might want to deduct type directly from interface name
657 if ifacedump['type'] in ['11a', '11b', '11g', 'wireless']:
658 # Default to station (client) mode
659 ifacedump['wlanmode'] = "sta"
[10166]660 if ifacedump['mode'] in ['master', 'master-wds', 'ap', 'ap-wds']:
[8242]661 ifacedump['wlanmode'] = "ap"
662 # Default to 802.11b mode
663 ifacedump['mode'] = '11b'
664 if ifacedump['type'] in ['11a', '11b' '11g']:
[9283]665 ifacedump['mode'] = ifacedump['type']
[8242]666
667 if not ifacedump.has_key('channel'):
668 if ifacedump['type'] == '11a':
669 ifacedump['channel'] = 36
670 else:
671 ifacedump['channel'] = 1
672
673 # Allow special hacks at the back like wds and stuff
674 if not ifacedump.has_key('extra'):
675 ifacedump['extra'] = 'regdomain ETSI country NL'
676
[10054]677 output += "wlans_%(interface)s='%(autogen_ifname)s'\n" % ifacedump
678 output += ("create_args_%(autogen_ifname)s='wlanmode %(wlanmode)s mode " +\
[8274]679 "%(mode)s ssid %(ssid)s %(extra)s channel %(channel)s'\n") % ifacedump
[9283]680
[8242]681 elif ifacedump['type'] in ['ethernet', 'eth']:
682 # No special config needed besides IP
683 pass
684 else:
685 assert False, "Unknown type " + ifacedump['type']
686
[9283]687 # Print IP address which needs to be assigned over here
[8242]688 output += "\n"
689 for iface,addrs in sorted(addrs_list.iteritems()):
[10079]690 for addr, comment in sorted(addrs,key=lambda x: parseaddr(x[0].split('/')[0])):
[9808]691 output += "# %s || %s || %s\n" % (iface, addr, comment)
[8242]692
[10366]693 # Write DHCLIENT entry
694 if dhclient_if[iface]:
695 output += "ifconfig_%s='SYNCDHCP'\n\n" % (iface)
696 else:
697 output += "ipv4_addrs_%s='%s'\n\n" % (iface, " ".join([x[0] for x in addrs]))
698
[8242]699 return output
700
[8257]701
702
[8242]703
[8317]704def get_all_configs():
705 """ Get dict with key 'host' with all configs present """
706 configs = dict()
707 for host in get_hostlist():
708 datadump = get_yaml(host)
709 configs[host] = datadump
710 return configs
711
712
[8319]713def get_interface_keys(config):
714 """ Quick hack to get all interface keys, later stage convert this to a iterator """
[10054]715 return sorted([elem for elem in config.keys() if (elem.startswith('iface_') and not "lo0" in elem)])
[8317]716
[8319]717
[8317]718def get_used_ips(configs):
719 """ Return array of all IPs used in config files"""
720 ip_list = []
[8319]721 for config in configs:
[8317]722 ip_list.append(config['masterip'])
[8319]723 for iface_key in get_interface_keys(config):
[8317]724 l = config[iface_key]['ip']
725 addr, mask = l.split('/')
726 # Special case do not process
[8332]727 if valid_addr(addr):
728 ip_list.append(addr)
729 else:
[9728]730 logger.error("## IP '%s' in '%s' not valid" % (addr, config['nodename']))
[8317]731 return sorted(ip_list)
732
733
734
[8242]735def generate_resolv_conf(datadump):
[8257]736 """ Generate configuration file '/etc/resolv.conf' """
[10468]737 # XXX: This should properly going to be an datastructure soon
738 datadump['autogen_header'] = generate_header("#")
739 datadump['autogen_edge_nameservers'] = ''
740 for host in get_proxylist():
741 hostdump = get_yaml(host)
742 datadump['autogen_edge_nameservers'] += "nameserver %(masterip)-15s # %(autogen_realname)s\n" % hostdump
743 for host in get_hybridlist():
744 hostdump = get_yaml(host)
[10584]745 if hostdump['service_proxy_ileiden'] or hostdump['service_proxy_normal']:
[10468]746 datadump['autogen_edge_nameservers'] += "nameserver %(masterip)-15s # %(autogen_realname)s\n" % hostdump
747
748 return Template("""\
749{{ autogen_header }}
[8242]750search wleiden.net
[10468]751
752# Try local (cache) first
[10209]753nameserver 127.0.0.1
[10468]754
[10584]755{% if service_proxy_normal or service_proxy_ileiden or nodetype == 'Proxy' -%}
[10053]756nameserver 8.8.8.8 # Google Public NameServer
757nameserver 8.8.4.4 # Google Public NameServer
[10468]758{% else -%}
[10646]759# START DYNAMIC LIST - updated by /tools/nameserver-shuffle
[10468]760{{ autogen_edge_nameservers }}
761{% endif -%}
762""").render(datadump)
[10209]763
[9283]764
[8242]765
[10654]766def generate_ntp_conf(datadump):
767 """ Generate configuration file '/etc/ntp.conf' """
768 # XXX: This should properly going to be an datastructure soon
769
770 datadump['autogen_header'] = generate_header("#")
771 datadump['autogen_ntp_servers'] = ''
772 for host in get_proxylist():
773 hostdump = get_yaml(host)
774 datadump['autogen_ntp_servers'] += "server %(masterip)-15s iburst maxpoll 9 # %(autogen_realname)s\n" % hostdump
775 for host in get_hybridlist():
776 hostdump = get_yaml(host)
777 if hostdump['service_proxy_ileiden'] or hostdump['service_proxy_normal']:
778 datadump['autogen_ntp_servers'] += "server %(masterip)-15s iburst maxpoll 9 # %(autogen_realname)s\n" % hostdump
779
780 return Template("""\
781{{ autogen_header }}
782
783{% if service_proxy_normal or service_proxy_ileiden or nodetype == 'Proxy' -%}
784# Machine hooked to internet.
785server 0.nl.pool.ntp.org iburst maxpoll 9
786server 1.nl.pool.ntp.org iburst maxpoll 9
787server 2.nl.pool.ntp.org iburst maxpoll 9
788server 3.nl.pool.ntp.org iburst maxpoll 9
789{% else -%}
790# Local Wireless Leiden NTP Servers.
791server 0.pool.ntp.wleiden.net iburst maxpoll 9
792server 1.pool.ntp.wleiden.net iburst maxpoll 9
793server 2.pool.ntp.wleiden.net iburst maxpoll 9
794server 3.pool.ntp.wleiden.net iburst maxpoll 9
795
796# All the configured NTP servers
797{{ autogen_ntp_servers }}
798{% endif %}
799
800# If a server loses sync with all upstream servers, NTP clients
801# no longer follow that server. The local clock can be configured
802# to provide a time source when this happens, but it should usually
803# be configured on just one server on a network. For more details see
804# http://support.ntp.org/bin/view/Support/UndisciplinedLocalClock
805# The use of Orphan Mode may be preferable.
806#
807server 127.127.1.0
808fudge 127.127.1.0 stratum 10
809""").render(datadump)
810
811
[10705]812def generate_pf_hybrid_conf_local(datadump):
813 """ Generate configuration file '/etc/pf.hybrid.conf.local' """
814 datadump['autogen_header'] = generate_header("#")
815 return Template("""\
816{{ autogen_header }}
[10654]817
[10705]818# Redirect some internal facing services outside (7)
[10714]819# INFO: {{ rdr_rules|count }} rdr_rules (outside to internal redirect rules) defined.
[10715]820{% for protocol, src_port,dest_ip,dest_port in rdr_rules -%}
821rdr on $ext_if inet proto {{ protocol }} from any to $ext_if port {{ src_port }} tag SRV -> {{ dest_ip }} port {{ dest_port }}
[10714]822{% endfor -%}
[10705]823""").render(datadump)
824
[10069]825def generate_motd(datadump):
826 """ Generate configuration file '/etc/motd' """
[10568]827 output = Template("""\
[10627]828FreeBSD run ``service motd onestart'' to make me look normal
[8242]829
[10568]830 WWW: {{ autogen_fqdn }} - http://www.wirelessleiden.nl
831 Loc: {{ location }}
[8257]832
[10568]833Services:
834{% if board == "ALIX2" -%}
[10665]835 - Core Node ({{ board }})
[10568]836{% else -%}
[10665]837 - Hulp Node ({{ board }})
[10568]838{% endif -%}
[10584]839{% if service_proxy_normal -%}
[10568]840 - Normal Proxy
841{% endif -%}
[10584]842{% if service_proxy_ileiden -%}
[10568]843 - iLeiden Proxy
844{% endif %}
[10626]845Interlinks:\n
[10568]846""").render(datadump)
[10069]847
848 # XXX: This is a hacky way to get the required data
849 for line in generate_rc_conf_local(datadump).split('\n'):
850 if '||' in line and not line[1:].split()[0] in ['lo0', 'ath0'] :
851 output += " - %s \n" % line[1:]
852 output += """\
853Attached bridges:
854"""
855 for iface_key in datadump['autogen_iface_keys']:
856 ifacedump = datadump[iface_key]
857 if ifacedump.has_key('ns_ip'):
858 output += " - %(interface)s || %(mode)s || %(ns_ip)s\n" % ifacedump
859
860 return output
861
862
[8267]863def format_yaml_value(value):
864 """ Get yaml value in right syntax for outputting """
865 if isinstance(value,str):
[10049]866 output = '"%s"' % value
[8267]867 else:
868 output = value
[9283]869 return output
[8267]870
871
872
873def format_wleiden_yaml(datadump):
[8242]874 """ Special formatting to ensure it is editable"""
[9283]875 output = "# Genesis config yaml style\n"
[8262]876 output += "# vim:ts=2:et:sw=2:ai\n"
[8242]877 output += "#\n"
878 iface_keys = [elem for elem in datadump.keys() if elem.startswith('iface_')]
879 for key in sorted(set(datadump.keys()) - set(iface_keys)):
[10714]880 if key == 'rdr_rules':
881 output += '%-10s:\n' % 'rdr_rules'
882 for rdr_rule in datadump[key]:
883 output += '- %s\n' % rdr_rule
884 else:
885 output += "%-10s: %s\n" % (key, format_yaml_value(datadump[key]))
[9283]886
[8242]887 output += "\n\n"
[9283]888
[8272]889 key_order = [ 'comment', 'interface', 'ip', 'desc', 'sdesc', 'mode', 'type',
890 'extra_type', 'channel', 'ssid', 'dhcp' ]
891
[8242]892 for iface_key in sorted(iface_keys):
893 output += "%s:\n" % iface_key
[8272]894 for key in key_order + list(sorted(set(datadump[iface_key].keys()) - set(key_order))):
895 if datadump[iface_key].has_key(key):
[9283]896 output += " %-11s: %s\n" % (key, format_yaml_value(datadump[iface_key][key]))
[8242]897 output += "\n\n"
898
899 return output
900
901
[8257]902
[10067]903def generate_wleiden_yaml(datadump, header=True):
[8267]904 """ Generate (petty) version of wleiden.yaml"""
[10053]905 for key in datadump.keys():
906 if key.startswith('autogen_'):
907 del datadump[key]
[10054]908 # Interface autogen cleanups
909 elif type(datadump[key]) == dict:
910 for key2 in datadump[key].keys():
911 if key2.startswith('autogen_'):
912 del datadump[key][key2]
913
[10067]914 output = generate_header("#") if header else ''
[8267]915 output += format_wleiden_yaml(datadump)
916 return output
917
918
[8588]919def generate_yaml(datadump):
920 return generate_config(datadump['nodename'], "wleiden.yaml", datadump)
[8267]921
[8588]922
[9283]923
[8298]924def generate_config(node, config, datadump=None):
[8257]925 """ Print configuration file 'config' of 'node' """
[8267]926 output = ""
[8242]927 try:
928 # Load config file
[8298]929 if datadump == None:
930 datadump = get_yaml(node)
[9283]931
[8242]932 if config == 'wleiden.yaml':
[8267]933 output += generate_wleiden_yaml(datadump)
934 elif config == 'authorized_keys':
[10051]935 f = open(os.path.join(NODE_DIR,"global_keys"), 'r')
[8267]936 output += f.read()
[8242]937 f.close()
938 elif config == 'dnsmasq.conf':
[10281]939 output += generate_dnsmasq_conf(datadump)
[10410]940 elif config == 'dhcpd.conf':
941 output += generate_dhcpd_conf(datadump)
[8242]942 elif config == 'rc.conf.local':
[10281]943 output += generate_rc_conf_local(datadump)
[8242]944 elif config == 'resolv.conf':
[10281]945 output += generate_resolv_conf(datadump)
[10654]946 elif config == 'ntp.conf':
947 output += generate_ntp_conf(datadump)
[10069]948 elif config == 'motd':
[10281]949 output += generate_motd(datadump)
[10705]950 elif config == 'pf.hybrid.conf.local':
951 output += generate_pf_hybrid_conf_local(datadump)
[8242]952 else:
[9283]953 assert False, "Config not found!"
[8242]954 except IOError, e:
[8267]955 output += "[ERROR] Config file not found"
956 return output
[8242]957
958
[8257]959
[8258]960def process_cgi_request():
961 """ When calling from CGI """
962 # Update repository if requested
963 form = cgi.FieldStorage()
964 if form.getvalue("action") == "update":
[8259]965 print "Refresh: 5; url=."
[8258]966 print "Content-type:text/plain\r\n\r\n",
967 print "[INFO] Updating subverion, please wait..."
[10143]968 print subprocess.Popen(['svn', 'cleanup', "%s/.." % NODE_DIR], stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0],
[10071]969 print subprocess.Popen(['svn', 'up', "%s/.." % NODE_DIR], stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0],
[8258]970 print "[INFO] All done, redirecting in 5 seconds"
971 sys.exit(0)
[9283]972
973
[10270]974 base_uri = os.environ['PATH_INFO']
975 uri = base_uri.strip('/').split('/')
976
[10681]977 output = "Template Holder"
978 content_type='text/plain'
[10378]979 if base_uri.endswith('/create/network.kml'):
[10681]980 content_type='application/vnd.google-earth.kml+xml'
981 output = make_network_kml.make_graph()
[10378]982 elif not uri[0]:
[10070]983 if is_text_request():
[10681]984 content_type = 'text/plain'
985 output = '\n'.join(get_hostlist())
[10060]986 else:
[10681]987 content_type = 'text/html'
988 output = generate_title(get_hostlist())
[8258]989 elif len(uri) == 1:
[10270]990 if is_text_request():
[10681]991 content_type = 'text/plain'
992 output = generate_node(uri[0])
[10270]993 else:
[10681]994 content_type = 'text/html'
995 output = generate_node_overview(uri[0])
[8258]996 elif len(uri) == 2:
[10681]997 content_type = 'text/plain'
998 output = generate_config(uri[0], uri[1])
[8258]999 else:
1000 assert False, "Invalid option"
[10681]1001
1002 print "Content-Type: %s" % content_type
1003 print "Content-Length: %s" % len(output)
1004 print ""
[8267]1005 print output
[8242]1006
[10391]1007def get_realname(datadump):
[10365]1008 # Proxy naming convention is special, as the proxy name is also included in
1009 # the nodename, when it comes to the numbered proxies.
[8588]1010 if datadump['nodetype'] == 'Proxy':
[10391]1011 realname = datadump['nodetype'] + datadump['nodename'].replace('proxy','')
[8588]1012 else:
1013 # By default the full name is listed and also a shortname CNAME for easy use.
[10391]1014 realname = datadump['nodetype'] + datadump['nodename']
1015 return(realname)
[8259]1016
[9283]1017
1018
[10264]1019def make_dns(output_dir = 'dns', external = False):
[8588]1020 items = dict()
[8598]1021
[8588]1022 # hostname is key, IP is value
[10642]1023 wleiden_zone = defaultdict(list)
[8588]1024 wleiden_cname = dict()
[8598]1025
[8588]1026 pool = dict()
1027 for node in get_hostlist():
1028 datadump = get_yaml(node)
[9283]1029
[8588]1030 # Proxy naming convention is special
[10391]1031 fqdn = datadump['autogen_realname']
[10461]1032 if datadump['nodetype'] in ['CNode', 'Hybrid']:
[8588]1033 wleiden_cname[datadump['nodename']] = fqdn
[10730]1034
1035 if datadump.has_key('rdr_host'):
1036 remote_target = datadump['rdr_host']
1037 elif datadump.has_key('remote_access') and datadump['remote_access']:
1038 remote_target = datadump['remote_access'].split(':')[0]
1039 else:
1040 remote_target = None
[8588]1041
[10730]1042 if remote_target:
1043 try:
1044 parseaddr(remote_target)
1045 wleiden_zone[datadump['nodename'] + '.gw'].append((remote_target, False))
1046 except (IndexError, ValueError):
1047 wleiden_cname[datadump['nodename'] + '.gw'] = remote_target + '.'
1048
1049
[10655]1050 wleiden_zone[fqdn].append((datadump['masterip'], True))
[8588]1051
[8598]1052 # Hacking to get proper DHCP IPs and hostnames
[8588]1053 for iface_key in get_interface_keys(datadump):
[8598]1054 iface_name = datadump[iface_key]['interface'].replace(':',"-alias-")
[10410]1055 (ip, cidr) = datadump[iface_key]['ip'].split('/')
[8588]1056 try:
1057 (dhcp_start, dhcp_stop) = datadump[iface_key]['dhcp'].split('-')
[10410]1058 datadump[iface_key]['netmask'] = cidr2netmask(cidr)
[8588]1059 dhcp_part = ".".join(ip.split('.')[0:3])
1060 if ip != datadump['masterip']:
[10655]1061 wleiden_zone["dhcp-gateway-%s.%s" % (iface_name, fqdn)].append((ip, False))
[8588]1062 for i in range(int(dhcp_start), int(dhcp_stop) + 1):
[10655]1063 wleiden_zone["dhcp-%s-%s.%s" % (i, iface_name, fqdn)].append(("%s.%s" % (dhcp_part, i), True))
[8588]1064 except (AttributeError, ValueError):
1065 # First push it into a pool, to indentify the counter-part later on
1066 addr = parseaddr(ip)
[10461]1067 cidr = int(cidr)
1068 addr = addr & ~((1 << (32 - cidr)) - 1)
[9283]1069 if pool.has_key(addr):
[8588]1070 pool[addr] += [(iface_name, fqdn, ip)]
[9283]1071 else:
[8588]1072 pool[addr] = [(iface_name, fqdn, ip)]
1073 continue
1074
[9286]1075
[10656]1076 def pool_to_name(fqdn, pool_members):
[9286]1077 """Convert the joined name to a usable pool name"""
1078
[10656]1079 def isplit(item):
1080 (prefix, name, number) = re.match('^(cnode|hybrid|proxy)([a-z]+)([0-9]*)$',item.lower()).group(1,2,3)
1081 return (prefix, name, number)
1082
1083 my_name = isplit(fqdn.split('.')[0])[1]
[9286]1084
[10656]1085 short_names = defaultdict(list)
[9286]1086 for node in sorted(pool_members):
[10656]1087 (prefix, name, number) = isplit(node)
1088 short_names[name].append((prefix,number))
[9286]1089
[10656]1090 return '-'.join(sorted(short_names.keys()))
[9286]1091
1092
[9957]1093 # WL uses an /29 to configure an interface. IP's are ordered like this:
[9958]1094 # MasterA (.1) -- DeviceA (.2) <<>> DeviceB (.3) --- SlaveB (.4)
[9957]1095
1096 sn = lambda x: re.sub(r'(?i)^cnode','',x)
1097
[8598]1098 # Automatic naming convention of interlinks namely 2 + remote.lower()
[8588]1099 for (key,value) in pool.iteritems():
[9958]1100 # Make sure they are sorted from low-ip to high-ip
1101 value = sorted(value, key=lambda x: parseaddr(x[2]))
1102
[8588]1103 if len(value) == 1:
1104 (iface_name, fqdn, ip) = value[0]
[10655]1105 wleiden_zone["2unused-%s.%s" % (iface_name, fqdn)].append((ip, True))
[9957]1106
1107 # Device DNS names
1108 if 'cnode' in fqdn.lower():
[10655]1109 wleiden_zone["d-at-%s.%s" % (iface_name, fqdn)].append((showaddr(parseaddr(ip) + 1), False))
1110 wleiden_cname["d-at-%s.%s" % (iface_name,sn(fqdn))] = "d-at-%s.%s" % ((iface_name, fqdn))
[9957]1111
[8588]1112 elif len(value) == 2:
1113 (a_iface_name, a_fqdn, a_ip) = value[0]
1114 (b_iface_name, b_fqdn, b_ip) = value[1]
[10655]1115 wleiden_zone["2%s.%s" % (b_fqdn,a_fqdn)].append((a_ip, True))
1116 wleiden_zone["2%s.%s" % (a_fqdn,b_fqdn)].append((b_ip, True))
[9957]1117
1118 # Device DNS names
1119 if 'cnode' in a_fqdn.lower() and 'cnode' in b_fqdn.lower():
[10655]1120 wleiden_zone["d-at-%s.%s" % (a_iface_name, a_fqdn)].append((showaddr(parseaddr(a_ip) + 1), False))
1121 wleiden_zone["d-at-%s.%s" % (b_iface_name, b_fqdn)].append((showaddr(parseaddr(b_ip) - 1), False))
[9957]1122 wleiden_cname["d-at-%s.%s" % (a_iface_name,sn(a_fqdn))] = "d-at-%s.%s" % (a_iface_name, a_fqdn)
1123 wleiden_cname["d-at-%s.%s" % (b_iface_name,sn(b_fqdn))] = "d-at-%s.%s" % (b_iface_name, b_fqdn)
1124 wleiden_cname["d2%s.%s" % (sn(b_fqdn),sn(a_fqdn))] = "d-at-%s.%s" % (a_iface_name, a_fqdn)
1125 wleiden_cname["d2%s.%s" % (sn(a_fqdn),sn(b_fqdn))] = "d-at-%s.%s" % (b_iface_name, b_fqdn)
1126
[8588]1127 else:
1128 pool_members = [k[1] for k in value]
1129 for item in value:
[9283]1130 (iface_name, fqdn, ip) = item
[10656]1131 pool_name = "2pool-" + pool_to_name(fqdn,pool_members)
[10655]1132 wleiden_zone["%s.%s" % (pool_name, fqdn)].append((ip, True))
[8598]1133
1134 # Include static DNS entries
1135 # XXX: Should they override the autogenerated results?
1136 # XXX: Convert input to yaml more useable.
1137 # Format:
1138 ##; this is a comment
1139 ## roomburgh=CNodeRoomburgh1
1140 ## apkerk1.CNodeVosko=172.17.176.8 ;this as well
[10642]1141 dns_list = yaml.load(open(os.path.join(NODE_DIR,'../dns/staticDNS.yaml'),'r'))
[9938]1142
1143 # Hack to allow special entries, for development
[10642]1144 wleiden_raw = {}
[9938]1145
[10642]1146 for line in dns_list:
[10660]1147 reverse = False
[10642]1148 k, items = line.items()[0]
[10660]1149 if type(items) == dict:
1150 if items.has_key('reverse'):
1151 reverse = items['reverse']
1152 items = items['a']
1153 else:
1154 items = items['cname']
1155 items = [items] if type(items) != list else items
[10642]1156 for item in items:
1157 if item.startswith('IN '):
1158 wleiden_raw[k] = item
1159 elif valid_addr(item):
[10660]1160 wleiden_zone[k].append((item, reverse))
[8598]1161 else:
[10642]1162 wleiden_cname[k] = item
[9283]1163
[8598]1164 details = dict()
1165 # 24 updates a day allowed
1166 details['serial'] = time.strftime('%Y%m%d%H')
1167
[10264]1168 if external:
1169 dns_masters = ['siteview.wirelessleiden.nl', 'ns1.vanderzwet.net']
1170 else:
1171 dns_masters = ['sunny.wleiden.net']
1172
1173 details['master'] = dns_masters[0]
1174 details['ns_servers'] = '\n'.join(['\tNS\t%s.' % x for x in dns_masters])
1175
[8598]1176 dns_header = '''
1177$TTL 3h
[10659]1178%(zone)s. SOA %(master)s. beheer.lijst.wirelessleiden.nl. ( %(serial)s 1d 12h 1w 60s )
[8598]1179 ; Serial, Refresh, Retry, Expire, Neg. cache TTL
1180
[10264]1181%(ns_servers)s
[8598]1182 \n'''
1183
[9283]1184
[10264]1185 if not os.path.isdir(output_dir):
1186 os.makedirs(output_dir)
[8598]1187 details['zone'] = 'wleiden.net'
[9284]1188 f = open(os.path.join(output_dir,"db." + details['zone']), "w")
[8598]1189 f.write(dns_header % details)
1190
[10655]1191 for host,items in wleiden_zone.iteritems():
1192 for ip,reverse in items:
[10730]1193 if ip not in ['0.0.0.0']:
[10642]1194 f.write("%s.wleiden.net. IN A %s \n" % (host.lower(), ip))
[8588]1195 for source,dest in wleiden_cname.iteritems():
[10730]1196 dest = dest if dest.endswith('.') else dest + ".wleiden.net."
1197 f.write("%s.wleiden.net. IN CNAME %s\n" % (source.lower(), dest.lower()))
[9938]1198 for source, dest in wleiden_raw.iteritems():
1199 f.write("%s.wleiden.net. %s\n" % (source, dest))
[8588]1200 f.close()
[9283]1201
[8598]1202 # Create whole bunch of specific sub arpa zones. To keep it compliant
1203 for s in range(16,32):
1204 details['zone'] = '%i.172.in-addr.arpa' % s
[9284]1205 f = open(os.path.join(output_dir,"db." + details['zone']), "w")
[8598]1206 f.write(dns_header % details)
[8588]1207
[8598]1208 #XXX: Not effient, fix to proper data structure and do checks at other
1209 # stages
[10655]1210 for host,items in wleiden_zone.iteritems():
1211 for ip,reverse in items:
1212 if not reverse:
1213 continue
[10642]1214 if valid_addr(ip):
[10655]1215 if valid_addr(ip):
1216 if int(ip.split('.')[1]) == s:
1217 rev_ip = '.'.join(reversed(ip.split('.')))
1218 f.write("%s.in-addr.arpa. IN PTR %s.wleiden.net.\n" % (rev_ip.lower(), host.lower()))
[8598]1219 f.close()
[8588]1220
[8598]1221
[8259]1222def usage():
[10567]1223 print """Usage: %(prog)s <argument>
1224Argument:
1225\tstandalone [port] = Run configurator webserver [8000]
1226\tdns [outputdir] = Generate BIND compliant zone files in dns [./dns]
[9589]1227\tfull-export = Generate yaml export script for heatmap.
[10567]1228\tstatic [outputdir] = Generate all config files and store on disk
1229\t with format ./<outputdir>/%%NODE%%/%%FILE%% [./static]
1230\ttest <node> <file> = Receive output of CGI script.
1231\tlist <status> <items> = List systems which have certain status
[10563]1232
[10567]1233Arguments:
1234\t<node> = NodeName (example: HybridRick)
1235\t<file> = %(files)s
1236\t<status> = all|up|down|planned
1237\t<items> = systems|nodes|proxies
1238
[10563]1239NOTE FOR DEVELOPERS; you can test your changes like this:
1240 BEFORE any changes in this code:
1241 $ ./gformat.py static /tmp/pre
1242 AFTER the changes:
1243 $ ./gformat.py static /tmp/post
1244 VIEW differences and VERIFY all are OK:
[10564]1245 $ diff -urI 'Generated' -r /tmp/pre /tmp/post
[10567]1246""" % { 'prog' : sys.argv[0], 'files' : '|'.join(files) }
[8259]1247 exit(0)
1248
1249
[10070]1250def is_text_request():
[10107]1251 """ Find out whether we are calling from the CLI or any text based CLI utility """
1252 try:
1253 return os.environ['HTTP_USER_AGENT'].split()[0] in ['curl', 'fetch', 'wget']
1254 except KeyError:
1255 return True
[8259]1256
[10547]1257def switchFormat(setting):
1258 if setting:
1259 return "YES"
1260 else:
1261 return "NO"
1262
[8267]1263def main():
1264 """Hard working sub"""
1265 # Allow easy hacking using the CLI
1266 if not os.environ.has_key('PATH_INFO'):
1267 if len(sys.argv) < 2:
1268 usage()
[9283]1269
[8267]1270 if sys.argv[1] == "standalone":
1271 import SocketServer
1272 import CGIHTTPServer
[10105]1273 # Hop to the right working directory.
1274 os.chdir(os.path.dirname(__file__))
[8267]1275 try:
1276 PORT = int(sys.argv[2])
1277 except (IndexError,ValueError):
1278 PORT = 8000
[9283]1279
[8267]1280 class MyCGIHTTPRequestHandler(CGIHTTPServer.CGIHTTPRequestHandler):
1281 """ Serve this CGI from the root of the webserver """
1282 def is_cgi(self):
1283 if "favicon" in self.path:
1284 return False
[9283]1285
[10364]1286 self.cgi_info = (os.path.basename(__file__), self.path)
[8267]1287 self.path = ''
1288 return True
1289 handler = MyCGIHTTPRequestHandler
[9807]1290 SocketServer.TCPServer.allow_reuse_address = True
[8267]1291 httpd = SocketServer.TCPServer(("", PORT), handler)
1292 httpd.server_name = 'localhost'
1293 httpd.server_port = PORT
[9283]1294
[9728]1295 logger.info("serving at port %s", PORT)
[8860]1296 try:
1297 httpd.serve_forever()
1298 except KeyboardInterrupt:
1299 httpd.shutdown()
[9728]1300 logger.info("All done goodbye")
[8267]1301 elif sys.argv[1] == "test":
1302 os.environ['PATH_INFO'] = "/".join(sys.argv[2:])
1303 os.environ['SCRIPT_NAME'] = __file__
1304 process_cgi_request()
[8296]1305 elif sys.argv[1] == "static":
1306 items = dict()
[10563]1307 items['output_dir'] = sys.argv[2] if len(sys.argv) > 2 else "./static"
[8296]1308 for node in get_hostlist():
1309 items['node'] = node
[10563]1310 items['wdir'] = "%(output_dir)s/%(node)s" % items
[8296]1311 if not os.path.isdir(items['wdir']):
1312 os.makedirs(items['wdir'])
[8298]1313 datadump = get_yaml(node)
[8296]1314 for config in files:
1315 items['config'] = config
[9728]1316 logger.info("## Generating %(node)s %(config)s" % items)
[8296]1317 f = open("%(wdir)s/%(config)s" % items, "w")
[8298]1318 f.write(generate_config(node, config, datadump))
[8296]1319 f.close()
[9514]1320 elif sys.argv[1] == "wind-export":
1321 items = dict()
1322 for node in get_hostlist():
1323 datadump = get_yaml(node)
1324 sql = """INSERT IGNORE INTO nodes (name, name_ns, longitude, latitude)
1325 VALUES ('%(nodename)s', '%(nodename)s', %(latitude)s, %(longitude)s);""" % datadump;
1326 sql = """INSERT IGNORE INTO users_nodes (user_id, node_id, owner)
1327 VALUES (
1328 (SELECT id FROM users WHERE username = 'rvdzwet'),
1329 (SELECT id FROM nodes WHERE name = '%(nodename)s'),
1330 'Y');""" % datadump
1331 #for config in files:
1332 # items['config'] = config
1333 # print "## Generating %(node)s %(config)s" % items
1334 # f = open("%(wdir)s/%(config)s" % items, "w")
1335 # f.write(generate_config(node, config, datadump))
1336 # f.close()
1337 for node in get_hostlist():
1338 datadump = get_yaml(node)
1339 for iface_key in sorted([elem for elem in datadump.keys() if elem.startswith('iface_')]):
1340 ifacedump = datadump[iface_key]
1341 if ifacedump.has_key('mode') and ifacedump['mode'] == 'ap-wds':
1342 ifacedump['nodename'] = datadump['nodename']
1343 if not ifacedump.has_key('channel') or not ifacedump['channel']:
1344 ifacedump['channel'] = 0
1345 sql = """INSERT INTO links (node_id, type, ssid, protocol, channel, status)
1346 VALUES ((SELECT id FROM nodes WHERE name = '%(nodename)s'), 'ap',
1347 '%(ssid)s', 'IEEE 802.11b', %(channel)s, 'active');""" % ifacedump
[9589]1348 elif sys.argv[1] == "full-export":
1349 hosts = {}
1350 for node in get_hostlist():
1351 datadump = get_yaml(node)
1352 hosts[datadump['nodename']] = datadump
1353 print yaml.dump(hosts)
1354
[8584]1355 elif sys.argv[1] == "dns":
[10264]1356 make_dns(sys.argv[2] if len(sys.argv) > 2 else 'dns', 'external' in sys.argv)
[9283]1357 elif sys.argv[1] == "cleanup":
[8588]1358 # First generate all datadumps
1359 datadumps = dict()
[10729]1360 ssid_to_node = dict()
[8588]1361 for host in get_hostlist():
[9728]1362 logger.info("# Processing: %s", host)
[10436]1363 # Set some boring default values
1364 datadump = { 'board' : 'UNKNOWN' }
1365 datadump.update(get_yaml(host))
[10391]1366 datadumps[datadump['autogen_realname']] = datadump
[9283]1367
[10729]1368 (poel, errors) = make_relations(datadumps)
1369 print "\n".join(["# WARNING: %s" % x for x in errors])
[10455]1370
[10156]1371 for host,datadump in datadumps.iteritems():
[10455]1372 # Convert all yes and no to boolean values
1373 def fix_boolean(dump):
1374 for key in dump.keys():
1375 if type(dump[key]) == dict:
1376 dump[key] = fix_boolean(dump[key])
[10459]1377 elif str(dump[key]).lower() in ["yes", "true"]:
[10455]1378 dump[key] = True
[10459]1379 elif str(dump[key]).lower() in ["no", "false"]:
[10455]1380 # Compass richting no (Noord Oost) is valid input
[10459]1381 if key != "compass": dump[key] = False
[10455]1382 return dump
1383 datadump = fix_boolean(datadump)
1384
[10400]1385 if datadump['rdnap_x'] and datadump['rdnap_y']:
1386 datadump['latitude'], datadump['longitude'] = rdnap.rd2etrs(datadump['rdnap_x'], datadump['rdnap_y'])
1387 elif datadump['latitude'] and datadump['longitude']:
1388 datadump['rdnap_x'], datadump['rdnap_y'] = rdnap.etrs2rd(datadump['latitude'], datadump['longitude'])
1389
[10319]1390 if datadump['nodename'].startswith('Proxy'):
1391 datadump['nodename'] = datadump['nodename'].lower()
1392
[10156]1393 for iface_key in datadump['autogen_iface_keys']:
[10703]1394 # All our normal wireless cards are normal APs now
1395 if datadump[iface_key]['type'] in ['11a', '11b', '11g', 'wireless']:
1396 datadump[iface_key]['mode'] = 'ap'
[10156]1397 # Wireless Leiden SSID have an consistent lowercase/uppercase
1398 if datadump[iface_key].has_key('ssid'):
1399 ssid = datadump[iface_key]['ssid']
1400 prefix = 'ap-WirelessLeiden-'
1401 if ssid.lower().startswith(prefix.lower()):
1402 datadump[iface_key]['ssid'] = prefix + ssid[len(prefix)].upper() + ssid[len(prefix) + 1:]
[10162]1403 if datadump[iface_key].has_key('ns_ip') and not datadump[iface_key].has_key('mode'):
1404 datadump[iface_key]['mode'] = 'autogen-FIXME'
1405 if not datadump[iface_key].has_key('desc'):
1406 datadump[iface_key]['desc'] = 'autogen-FIXME'
[10729]1407 # Set the compass value based on the angle between the poels
1408 if datadump[iface_key].has_key('ns_ip'):
1409 my_pool = poel[network(datadump[iface_key]['ip'])]
1410 remote_hosts = list(set([x[0] for x in my_pool]) - set([host]))
1411 if remote_hosts:
1412 compass_target = remote_hosts[0]
1413 datadump[iface_key]['compass'] = cd_between_hosts(host, compass_target, datadumps)
1414
[10074]1415 store_yaml(datadump)
[9971]1416 elif sys.argv[1] == "list":
[10611]1417 use_fqdn = False
[10567]1418 if len(sys.argv) < 4 or not sys.argv[2] in ["up", "down", "planned", "all"]:
1419 usage()
1420 if sys.argv[3] == "nodes":
[9971]1421 systems = get_nodelist()
[10567]1422 elif sys.argv[3] == "proxies":
[9971]1423 systems = get_proxylist()
[10567]1424 elif sys.argv[3] == "systems":
[10270]1425 systems = get_hostlist()
[9971]1426 else:
1427 usage()
[10611]1428 if len(sys.argv) > 4:
1429 if sys.argv[4] == "fqdn":
1430 use_fqdn = True
1431 else:
1432 usage()
1433
[9971]1434 for system in systems:
1435 datadump = get_yaml(system)
[10611]1436
1437 output = datadump['autogen_fqdn'] if use_fqdn else system
[10567]1438 if sys.argv[2] == "all":
[10611]1439 print output
[10567]1440 elif datadump['status'] == sys.argv[2]:
[10611]1441 print output
[10378]1442 elif sys.argv[1] == "create":
1443 if sys.argv[2] == "network.kml":
1444 print make_network_kml.make_graph()
1445 else:
1446 usage()
[9283]1447 usage()
1448 else:
[10070]1449 # Do not enable debugging for config requests as it highly clutters the output
1450 if not is_text_request():
1451 cgitb.enable()
[9283]1452 process_cgi_request()
1453
1454
1455if __name__ == "__main__":
1456 main()
Note: See TracBrowser for help on using the repository browser.