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