source: genesis/tools/gformat.py@ 10734

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

Aliases moeten in shared-network groups gezet worden.

Related-To: nodefactory#156

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