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