source: genesis/tools/gformat.py@ 10881

Last change on this file since 10881 was 10881, checked in by rick, 14 years ago

Make the interface keys wat meer standaard.

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