1 | #!/usr/bin/env python
|
---|
2 | #
|
---|
3 | # vim:ts=2:et:sw=2:ai
|
---|
4 | # Wireless Leiden configuration generator, based on yaml files'
|
---|
5 | # Rick van der Zwet <info@rickvanderzwet.nl>
|
---|
6 | import cgi
|
---|
7 | import cgitb
|
---|
8 | import copy
|
---|
9 | import glob
|
---|
10 | import os
|
---|
11 | import socket
|
---|
12 | import string
|
---|
13 | import subprocess
|
---|
14 | import sys
|
---|
15 | import time
|
---|
16 | import make_map
|
---|
17 | from pprint import pprint
|
---|
18 | try:
|
---|
19 | import yaml
|
---|
20 | except ImportError, e:
|
---|
21 | print e
|
---|
22 | print "[ERROR] Please install the python-yaml or devel/py-yaml package"
|
---|
23 | exit(1)
|
---|
24 |
|
---|
25 | try:
|
---|
26 | from yaml import CLoader as Loader
|
---|
27 | from yaml import CDumper as Dumper
|
---|
28 | except ImportError:
|
---|
29 | from yaml import Loader, Dumper
|
---|
30 |
|
---|
31 |
|
---|
32 |
|
---|
33 | NODE_DIR = os.path.dirname(os.path.realpath(__file__))
|
---|
34 | __version__ = '$Id: gformat.py 8588 2010-10-30 02:28:19Z rick $'
|
---|
35 |
|
---|
36 |
|
---|
37 | files = [
|
---|
38 | 'authorized_keys',
|
---|
39 | 'dnsmasq.conf',
|
---|
40 | 'rc.conf.local',
|
---|
41 | 'resolv.conf',
|
---|
42 | 'wleiden.yaml'
|
---|
43 | ]
|
---|
44 |
|
---|
45 | # Global variables uses
|
---|
46 | OK = 10
|
---|
47 | DOWN = 20
|
---|
48 | UNKNOWN = 90
|
---|
49 |
|
---|
50 |
|
---|
51 | def get_proxylist():
|
---|
52 | """Get all available proxies proxyX sorting based on X number"""
|
---|
53 | os.chdir(NODE_DIR)
|
---|
54 | proxylist = sorted(glob.glob("proxy*"),
|
---|
55 | key=lambda name: int(''.join([c for c in name if c in string.digits])),
|
---|
56 | cmp=lambda x,y: x - y)
|
---|
57 | return proxylist
|
---|
58 |
|
---|
59 |
|
---|
60 |
|
---|
61 | def valid_addr(addr):
|
---|
62 | """ Show which address is valid in which are not """
|
---|
63 | return str(addr).startswith('172.')
|
---|
64 |
|
---|
65 |
|
---|
66 | def get_nodelist():
|
---|
67 | """ Get all available nodes - sorted """
|
---|
68 | os.chdir(NODE_DIR)
|
---|
69 | nodelist = sorted(glob.glob("CNode*"))
|
---|
70 | return nodelist
|
---|
71 |
|
---|
72 | def get_hostlist():
|
---|
73 | """ Combined hosts and proxy list"""
|
---|
74 | return get_nodelist() + get_proxylist()
|
---|
75 |
|
---|
76 | def angle_between_points(lat1,lat2,long1,long2):
|
---|
77 | """
|
---|
78 | Return Angle in radians between two GPS coordinates
|
---|
79 | See: http://stackoverflow.com/questions/3809179/angle-between-2-gps-coordinates
|
---|
80 | """
|
---|
81 | dy = lat2 - lat1
|
---|
82 | dx = math.cos(math.pi/180*lat1)*(long2 - long1)
|
---|
83 | angle = math.atan2(dy,dx)
|
---|
84 | return angle
|
---|
85 |
|
---|
86 | def angle_to_cd(angle):
|
---|
87 | """ Return Dutch Cardinal Direction estimation in 'one digit' of radian angle """
|
---|
88 |
|
---|
89 | # For easy conversion get positive degree
|
---|
90 | degrees = math.degrees(angle)
|
---|
91 | if degrees < 0:
|
---|
92 | 360 - abs(degrees)
|
---|
93 |
|
---|
94 | # Numbers can be confusing calculate from the 4 main directions
|
---|
95 | p = 22.5
|
---|
96 | if degrees < p:
|
---|
97 | return "n"
|
---|
98 | elif degrees < (90 - p):
|
---|
99 | return "no"
|
---|
100 | elif degrees < (90 + p):
|
---|
101 | return "o"
|
---|
102 | elif degrees < (180 - p):
|
---|
103 | return "zo"
|
---|
104 | elif degrees < (180 + p):
|
---|
105 | return "z"
|
---|
106 | elif degrees < (270 - p):
|
---|
107 | return "zw"
|
---|
108 | elif degrees < (270 + p):
|
---|
109 | return "w"
|
---|
110 | elif degrees < (360 - p):
|
---|
111 | return "nw"
|
---|
112 | else:
|
---|
113 | return "n"
|
---|
114 |
|
---|
115 |
|
---|
116 | def generate_title(nodelist):
|
---|
117 | """ Main overview page """
|
---|
118 | items = {'root' : "." }
|
---|
119 | output = """
|
---|
120 | <html>
|
---|
121 | <head>
|
---|
122 | <title>Wireless leiden Configurator - GFormat</title>
|
---|
123 | <style type="text/css">
|
---|
124 | th {background-color: #999999}
|
---|
125 | tr:nth-child(odd) {background-color: #cccccc}
|
---|
126 | tr:nth-child(even) {background-color: #ffffff}
|
---|
127 | th, td {padding: 0.1em 1em}
|
---|
128 | </style>
|
---|
129 | </head>
|
---|
130 | <body>
|
---|
131 | <center>
|
---|
132 | <form type="GET" action="%(root)s">
|
---|
133 | <input type="hidden" name="action" value="update">
|
---|
134 | <input type="submit" value="Update Configuration Database (SVN)">
|
---|
135 | </form>
|
---|
136 | <table>
|
---|
137 | <caption><h3>Wireless Leiden Configurator</h3></caption>
|
---|
138 | """ % items
|
---|
139 |
|
---|
140 | for node in nodelist:
|
---|
141 | items['node'] = node
|
---|
142 | output += '<tr><td><a href="%(root)s/%(node)s">%(node)s</a></td>' % items
|
---|
143 | for config in files:
|
---|
144 | items['config'] = config
|
---|
145 | output += '<td><a href="%(root)s/%(node)s/%(config)s">%(config)s</a></td>' % items
|
---|
146 | output += "</tr>"
|
---|
147 | output += """
|
---|
148 | </table>
|
---|
149 | <hr />
|
---|
150 | <em>%s</em>
|
---|
151 | </center>
|
---|
152 | </body>
|
---|
153 | </html>
|
---|
154 | """ % __version__
|
---|
155 |
|
---|
156 | return output
|
---|
157 |
|
---|
158 |
|
---|
159 |
|
---|
160 | def generate_node(node):
|
---|
161 | """ Print overview of all files available for node """
|
---|
162 | return "\n".join(files)
|
---|
163 |
|
---|
164 |
|
---|
165 |
|
---|
166 | def generate_header(ctag="#"):
|
---|
167 | return """\
|
---|
168 | %(ctag)s
|
---|
169 | %(ctag)s DO NOT EDIT - Automatically generated by 'gformat'
|
---|
170 | %(ctag)s Generated at %(date)s by %(host)s
|
---|
171 | %(ctag)s
|
---|
172 | """ % { 'ctag' : ctag, 'date' : time.ctime(), 'host' : socket.gethostname() }
|
---|
173 |
|
---|
174 |
|
---|
175 |
|
---|
176 | def parseaddr(s):
|
---|
177 | """ Process IPv4 CIDR notation addr to a (binary) number """
|
---|
178 | f = s.split('.')
|
---|
179 | return (long(f[0]) << 24L) + \
|
---|
180 | (long(f[1]) << 16L) + \
|
---|
181 | (long(f[2]) << 8L) + \
|
---|
182 | long(f[3])
|
---|
183 |
|
---|
184 |
|
---|
185 |
|
---|
186 | def showaddr(a):
|
---|
187 | """ Display IPv4 addr in (dotted) CIDR notation """
|
---|
188 | return "%d.%d.%d.%d" % ((a >> 24) & 0xff, (a >> 16) & 0xff, (a >> 8) & 0xff, a & 0xff)
|
---|
189 |
|
---|
190 |
|
---|
191 | def is_member(ip, mask, canidate):
|
---|
192 | """ Return True if canidate is part of ip/mask block"""
|
---|
193 | ip_addr = gformat.parseaddr(ip)
|
---|
194 | ip_canidate = gformat.parseaddr(canidate)
|
---|
195 | mask = int(mask)
|
---|
196 | ip_addr = ip_addr & ~((1 << (32 - mask)) - 1)
|
---|
197 | ip_canidate = ip_canidate & ~((1 << (32 - mask)) - 1)
|
---|
198 | return ip_addr == ip_canidate
|
---|
199 |
|
---|
200 |
|
---|
201 |
|
---|
202 |
|
---|
203 | def netmask2subnet(netmask):
|
---|
204 | """ Given a 'netmask' return corresponding CIDR """
|
---|
205 | return showaddr(0xffffffff & (0xffffffff << (32 - int(netmask))))
|
---|
206 |
|
---|
207 |
|
---|
208 |
|
---|
209 | def generate_dnsmasq_conf(datadump):
|
---|
210 | """ Generate configuration file '/usr/local/etc/dnsmasq.conf' """
|
---|
211 | output = generate_header()
|
---|
212 | output += """\
|
---|
213 | # DHCP server options
|
---|
214 | dhcp-authoritative
|
---|
215 | dhcp-fqdn
|
---|
216 | domain=dhcp.%(nodename_lower)s.%(domain)s
|
---|
217 | domain-needed
|
---|
218 | expand-hosts
|
---|
219 |
|
---|
220 | # Low memory footprint
|
---|
221 | cache-size=10000
|
---|
222 | \n""" % datadump
|
---|
223 |
|
---|
224 | for iface_key in datadump['iface_keys']:
|
---|
225 | if not datadump[iface_key].has_key('comment'):
|
---|
226 | datadump[iface_key]['comment'] = None
|
---|
227 | output += "## %(interface)s - %(desc)s - %(comment)s\n" % datadump[iface_key]
|
---|
228 |
|
---|
229 | try:
|
---|
230 | (dhcp_start, dhcp_stop) = datadump[iface_key]['dhcp'].split('-')
|
---|
231 | (ip, netmask) = datadump[iface_key]['ip'].split('/')
|
---|
232 | datadump[iface_key]['subnet'] = netmask2subnet(netmask)
|
---|
233 | except (AttributeError, ValueError):
|
---|
234 | output += "# not autoritive\n\n"
|
---|
235 | continue
|
---|
236 |
|
---|
237 | dhcp_part = ".".join(ip.split('.')[0:3])
|
---|
238 | datadump[iface_key]['dhcp_start'] = dhcp_part + "." + dhcp_start
|
---|
239 | datadump[iface_key]['dhcp_stop'] = dhcp_part + "." + dhcp_stop
|
---|
240 | output += "dhcp-range=%(interface)s,%(dhcp_start)s,%(dhcp_stop)s,%(subnet)s,24h\n\n" % datadump[iface_key]
|
---|
241 |
|
---|
242 | return output
|
---|
243 |
|
---|
244 |
|
---|
245 |
|
---|
246 | def generate_rc_conf_local(datadump):
|
---|
247 | """ Generate configuration file '/etc/rc.conf.local' """
|
---|
248 | output = generate_header("#");
|
---|
249 | output += """\
|
---|
250 | hostname='%(nodetype)s%(nodename)s.%(domain)s'
|
---|
251 | location='%(location)s'
|
---|
252 | """ % datadump
|
---|
253 |
|
---|
254 | # TProxy configuration
|
---|
255 | output += "\n"
|
---|
256 | try:
|
---|
257 | if datadump['tproxy']:
|
---|
258 | output += """\
|
---|
259 | tproxy_enable='YES'
|
---|
260 | tproxy_range='%(tproxy)s'
|
---|
261 | """ % datadump
|
---|
262 | except KeyError:
|
---|
263 | output += "tproxy_enable='NO'\n"
|
---|
264 |
|
---|
265 | output += '\n'
|
---|
266 | # lo0 configuration:
|
---|
267 | # - 172.32.255.1/32 is the proxy.wleiden.net deflector
|
---|
268 | # - masterip is special as it needs to be assigned to at
|
---|
269 | # least one interface, so if not used assign to lo0
|
---|
270 | addrs_list = { 'lo0' : ["127.0.0.1/8", "172.31.255.1/32"] }
|
---|
271 | iface_map = {'lo0' : 'lo0'}
|
---|
272 |
|
---|
273 | masterip_used = False
|
---|
274 | for iface_key in datadump['iface_keys']:
|
---|
275 | if datadump[iface_key]['ip'].startswith(datadump['masterip']):
|
---|
276 | masterip_used = True
|
---|
277 | break
|
---|
278 | if not masterip_used:
|
---|
279 | addrs_list['lo0'].append(datadump['masterip'] + "/32")
|
---|
280 |
|
---|
281 | wlan_count = 0
|
---|
282 | for iface_key in datadump['iface_keys']:
|
---|
283 | ifacedump = datadump[iface_key]
|
---|
284 | interface = ifacedump['interface']
|
---|
285 | # By default no special interface mapping
|
---|
286 | iface_map[interface] = interface
|
---|
287 |
|
---|
288 | # Add interface IP to list
|
---|
289 | if addrs_list.has_key(interface):
|
---|
290 | addrs_list[interface].append(ifacedump['ip'])
|
---|
291 | else:
|
---|
292 | addrs_list[interface] = [ifacedump['ip']]
|
---|
293 |
|
---|
294 | # Alias only needs IP assignment for now, this might change if we
|
---|
295 | # are going to use virtual accesspoints
|
---|
296 | if "alias" in iface_key:
|
---|
297 | continue
|
---|
298 |
|
---|
299 | # XXX: Might want to deduct type directly from interface name
|
---|
300 | if ifacedump['type'] in ['11a', '11b', '11g', 'wireless']:
|
---|
301 | # Create wlanX interface
|
---|
302 | ifacedump['wlanif'] ="wlan%i" % wlan_count
|
---|
303 | iface_map[interface] = ifacedump['wlanif']
|
---|
304 | wlan_count += 1
|
---|
305 |
|
---|
306 | # Default to station (client) mode
|
---|
307 | ifacedump['wlanmode'] = "sta"
|
---|
308 | if ifacedump['mode'] in ['master', 'master-wds']:
|
---|
309 | ifacedump['wlanmode'] = "ap"
|
---|
310 | # Default to 802.11b mode
|
---|
311 | ifacedump['mode'] = '11b'
|
---|
312 | if ifacedump['type'] in ['11a', '11b' '11g']:
|
---|
313 | ifacedump['mode'] = ifacedump['type']
|
---|
314 |
|
---|
315 | if not ifacedump.has_key('channel'):
|
---|
316 | if ifacedump['type'] == '11a':
|
---|
317 | ifacedump['channel'] = 36
|
---|
318 | else:
|
---|
319 | ifacedump['channel'] = 1
|
---|
320 |
|
---|
321 | # Allow special hacks at the back like wds and stuff
|
---|
322 | if not ifacedump.has_key('extra'):
|
---|
323 | ifacedump['extra'] = 'regdomain ETSI country NL'
|
---|
324 |
|
---|
325 | output += "wlans_%(interface)s='%(wlanif)s'\n" % ifacedump
|
---|
326 | output += ("create_args_%(wlanif)s='wlanmode %(wlanmode)s mode " +\
|
---|
327 | "%(mode)s ssid %(ssid)s %(extra)s channel %(channel)s'\n") % ifacedump
|
---|
328 |
|
---|
329 | elif ifacedump['type'] in ['ethernet', 'eth']:
|
---|
330 | # No special config needed besides IP
|
---|
331 | pass
|
---|
332 | else:
|
---|
333 | assert False, "Unknown type " + ifacedump['type']
|
---|
334 |
|
---|
335 | # Print IP address which needs to be assigned over here
|
---|
336 | output += "\n"
|
---|
337 | for iface,addrs in sorted(addrs_list.iteritems()):
|
---|
338 | output += "ipv4_addrs_%s='%s'\n" % (iface_map[iface], " ".join(addrs))
|
---|
339 |
|
---|
340 | return output
|
---|
341 |
|
---|
342 |
|
---|
343 |
|
---|
344 | def get_yaml(item):
|
---|
345 | """ Get configuration yaml for 'item'"""
|
---|
346 | gfile = NODE_DIR + '/%s/wleiden.yaml' % item
|
---|
347 |
|
---|
348 | f = open(gfile, 'r')
|
---|
349 | datadump = yaml.load(f,Loader=Loader)
|
---|
350 | f.close()
|
---|
351 |
|
---|
352 | return datadump
|
---|
353 |
|
---|
354 | def store_yaml(datadump):
|
---|
355 | """ Store configuration yaml for 'item'"""
|
---|
356 | gfile = NODE_DIR + '/%s/wleiden.yaml' % item
|
---|
357 |
|
---|
358 | f = open(gfile, 'w')
|
---|
359 | f.write(generate_wleiden_yaml(datadump))
|
---|
360 | f.close()
|
---|
361 |
|
---|
362 |
|
---|
363 |
|
---|
364 | def get_all_configs():
|
---|
365 | """ Get dict with key 'host' with all configs present """
|
---|
366 | configs = dict()
|
---|
367 | for host in get_hostlist():
|
---|
368 | datadump = get_yaml(host)
|
---|
369 | configs[host] = datadump
|
---|
370 | return configs
|
---|
371 |
|
---|
372 |
|
---|
373 | def get_interface_keys(config):
|
---|
374 | """ Quick hack to get all interface keys, later stage convert this to a iterator """
|
---|
375 | return [elem for elem in config.keys() if (elem.startswith('iface_') and not "lo0" in elem)]
|
---|
376 |
|
---|
377 |
|
---|
378 | def get_used_ips(configs):
|
---|
379 | """ Return array of all IPs used in config files"""
|
---|
380 | ip_list = []
|
---|
381 | for config in configs:
|
---|
382 | ip_list.append(config['masterip'])
|
---|
383 | for iface_key in get_interface_keys(config):
|
---|
384 | l = config[iface_key]['ip']
|
---|
385 | addr, mask = l.split('/')
|
---|
386 | # Special case do not process
|
---|
387 | if valid_addr(addr):
|
---|
388 | ip_list.append(addr)
|
---|
389 | else:
|
---|
390 | print "## IP '%s' in '%s' not valid" % (addr, config['nodename'])
|
---|
391 | return sorted(ip_list)
|
---|
392 |
|
---|
393 |
|
---|
394 |
|
---|
395 | def write_yaml(item, datadump):
|
---|
396 | """ Write configuration yaml for 'item'"""
|
---|
397 | gfile = NODE_DIR + '/%s/wleiden.yaml' % item
|
---|
398 |
|
---|
399 | f = open(gfile, 'w')
|
---|
400 | f.write(format_wleiden_yaml(datadump))
|
---|
401 | f.close()
|
---|
402 |
|
---|
403 |
|
---|
404 |
|
---|
405 | def generate_resolv_conf(datadump):
|
---|
406 | """ Generate configuration file '/etc/resolv.conf' """
|
---|
407 | output = generate_header("#");
|
---|
408 | output += """\
|
---|
409 | search wleiden.net
|
---|
410 | # Try local (cache) first
|
---|
411 | nameserver 127.0.0.1
|
---|
412 |
|
---|
413 | # Proxies are recursive nameservers
|
---|
414 | # needs to be in resolv.conf for dnsmasq as well
|
---|
415 | """ % datadump
|
---|
416 |
|
---|
417 | for proxy in get_proxylist():
|
---|
418 | proxy_ip = get_yaml(proxy)['masterip']
|
---|
419 | output += "nameserver %-15s # %s\n" % (proxy_ip, proxy)
|
---|
420 | return output
|
---|
421 |
|
---|
422 |
|
---|
423 |
|
---|
424 | def format_yaml_value(value):
|
---|
425 | """ Get yaml value in right syntax for outputting """
|
---|
426 | if isinstance(value,str):
|
---|
427 | output = "'%s'" % value
|
---|
428 | else:
|
---|
429 | output = value
|
---|
430 | return output
|
---|
431 |
|
---|
432 |
|
---|
433 |
|
---|
434 | def format_wleiden_yaml(datadump):
|
---|
435 | """ Special formatting to ensure it is editable"""
|
---|
436 | output = "# Genesis config yaml style\n"
|
---|
437 | output += "# vim:ts=2:et:sw=2:ai\n"
|
---|
438 | output += "#\n"
|
---|
439 | iface_keys = [elem for elem in datadump.keys() if elem.startswith('iface_')]
|
---|
440 | for key in sorted(set(datadump.keys()) - set(iface_keys)):
|
---|
441 | output += "%-10s: %s\n" % (key, format_yaml_value(datadump[key]))
|
---|
442 |
|
---|
443 | output += "\n\n"
|
---|
444 |
|
---|
445 | key_order = [ 'comment', 'interface', 'ip', 'desc', 'sdesc', 'mode', 'type',
|
---|
446 | 'extra_type', 'channel', 'ssid', 'dhcp' ]
|
---|
447 |
|
---|
448 | for iface_key in sorted(iface_keys):
|
---|
449 | output += "%s:\n" % iface_key
|
---|
450 | for key in key_order + list(sorted(set(datadump[iface_key].keys()) - set(key_order))):
|
---|
451 | if datadump[iface_key].has_key(key):
|
---|
452 | output += " %-11s: %s\n" % (key, format_yaml_value(datadump[iface_key][key]))
|
---|
453 | output += "\n\n"
|
---|
454 |
|
---|
455 | return output
|
---|
456 |
|
---|
457 |
|
---|
458 |
|
---|
459 | def generate_wleiden_yaml(datadump):
|
---|
460 | """ Generate (petty) version of wleiden.yaml"""
|
---|
461 | output = generate_header("#")
|
---|
462 | output += format_wleiden_yaml(datadump)
|
---|
463 | return output
|
---|
464 |
|
---|
465 |
|
---|
466 | def generate_yaml(datadump):
|
---|
467 | return generate_config(datadump['nodename'], "wleiden.yaml", datadump)
|
---|
468 |
|
---|
469 |
|
---|
470 |
|
---|
471 | def generate_config(node, config, datadump=None):
|
---|
472 | """ Print configuration file 'config' of 'node' """
|
---|
473 | output = ""
|
---|
474 | try:
|
---|
475 | # Load config file
|
---|
476 | if datadump == None:
|
---|
477 | datadump = get_yaml(node)
|
---|
478 |
|
---|
479 | # Preformat certain needed variables for formatting and push those into special object
|
---|
480 | datadump_extra = copy.deepcopy(datadump)
|
---|
481 | if not datadump_extra.has_key('domain'):
|
---|
482 | datadump_extra['domain'] = 'wleiden.net'
|
---|
483 | datadump_extra['nodename_lower'] = datadump_extra['nodename'].lower()
|
---|
484 | datadump_extra['iface_keys'] = sorted([elem for elem in datadump.keys() if elem.startswith('iface_')])
|
---|
485 |
|
---|
486 | if config == 'wleiden.yaml':
|
---|
487 | output += generate_wleiden_yaml(datadump)
|
---|
488 | elif config == 'authorized_keys':
|
---|
489 | f = open("global_keys", 'r')
|
---|
490 | output += f.read()
|
---|
491 | f.close()
|
---|
492 | elif config == 'dnsmasq.conf':
|
---|
493 | output += generate_dnsmasq_conf(datadump_extra)
|
---|
494 | elif config == 'rc.conf.local':
|
---|
495 | output += generate_rc_conf_local(datadump_extra)
|
---|
496 | elif config == 'resolv.conf':
|
---|
497 | output += generate_resolv_conf(datadump_extra)
|
---|
498 | else:
|
---|
499 | assert False, "Config not found!"
|
---|
500 | except IOError, e:
|
---|
501 | output += "[ERROR] Config file not found"
|
---|
502 | return output
|
---|
503 |
|
---|
504 |
|
---|
505 |
|
---|
506 | def process_cgi_request():
|
---|
507 | """ When calling from CGI """
|
---|
508 | # Update repository if requested
|
---|
509 | form = cgi.FieldStorage()
|
---|
510 | if form.getvalue("action") == "update":
|
---|
511 | print "Refresh: 5; url=."
|
---|
512 | print "Content-type:text/plain\r\n\r\n",
|
---|
513 | print "[INFO] Updating subverion, please wait..."
|
---|
514 | print subprocess.Popen(['svn', 'up', NODE_DIR], stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0],
|
---|
515 | print "[INFO] All done, redirecting in 5 seconds"
|
---|
516 | sys.exit(0)
|
---|
517 |
|
---|
518 |
|
---|
519 | uri = os.environ['PATH_INFO'].strip('/').split('/')
|
---|
520 | output = ""
|
---|
521 | if not uri[0]:
|
---|
522 | output += "Content-type:text/html\r\n\r\n"
|
---|
523 | output += generate_title(get_hostlist())
|
---|
524 | elif len(uri) == 1:
|
---|
525 | output += "Content-type:text/plain\r\n\r\n"
|
---|
526 | output += generate_node(uri[0])
|
---|
527 | elif len(uri) == 2:
|
---|
528 | output += "Content-type:text/plain\r\n\r\n"
|
---|
529 | output += generate_config(uri[0], uri[1])
|
---|
530 | else:
|
---|
531 | assert False, "Invalid option"
|
---|
532 | print output
|
---|
533 |
|
---|
534 | def get_fqdn(datadump):
|
---|
535 | # Proxy naming convention is special
|
---|
536 | if datadump['nodetype'] == 'Proxy':
|
---|
537 | fqdn = datadump['nodename']
|
---|
538 | else:
|
---|
539 | # By default the full name is listed and also a shortname CNAME for easy use.
|
---|
540 | fqdn = datadump['nodetype'] + datadump['nodename']
|
---|
541 | return(fqdn)
|
---|
542 |
|
---|
543 |
|
---|
544 |
|
---|
545 | def make_dns():
|
---|
546 | items = dict()
|
---|
547 | # hostname is key, IP is value
|
---|
548 | wleiden_zone = dict()
|
---|
549 | wleiden_cname = dict()
|
---|
550 | pool = dict()
|
---|
551 | for node in get_hostlist():
|
---|
552 | datadump = get_yaml(node)
|
---|
553 |
|
---|
554 | # Proxy naming convention is special
|
---|
555 | fqdn = get_fqdn(datadump)
|
---|
556 | if datadump['nodetype'] == 'CNode':
|
---|
557 | wleiden_cname[datadump['nodename']] = fqdn
|
---|
558 |
|
---|
559 | wleiden_zone[fqdn] = datadump['masterip']
|
---|
560 |
|
---|
561 | #items['node'] = node
|
---|
562 | #items['wdir'] = "./static/%(node)s" % items
|
---|
563 | #if not os.path.isdir(items['wdir']):
|
---|
564 | # os.makedirs(items['wdir'])
|
---|
565 | for iface_key in get_interface_keys(datadump):
|
---|
566 | iface_name = datadump[iface_key]['interface'].replace(':',"_alias_")
|
---|
567 | (ip, netmask) = datadump[iface_key]['ip'].split('/')
|
---|
568 | try:
|
---|
569 | (dhcp_start, dhcp_stop) = datadump[iface_key]['dhcp'].split('-')
|
---|
570 | datadump[iface_key]['subnet'] = netmask2subnet(netmask)
|
---|
571 | dhcp_part = ".".join(ip.split('.')[0:3])
|
---|
572 | if ip != datadump['masterip']:
|
---|
573 | wleiden_zone["dhcp-gateway-%s.%s" % (iface_name, fqdn)] = ip
|
---|
574 | for i in range(int(dhcp_start), int(dhcp_stop) + 1):
|
---|
575 | wleiden_zone["dhcp-%s-%s.%s" % (i, iface_name, fqdn)] = "%s.%s" % (dhcp_part, i)
|
---|
576 | except (AttributeError, ValueError):
|
---|
577 | # First push it into a pool, to indentify the counter-part later on
|
---|
578 | addr = parseaddr(ip)
|
---|
579 | netmask = int(netmask)
|
---|
580 | addr = addr & ~((1 << (32 - netmask)) - 1)
|
---|
581 | if pool.has_key(addr):
|
---|
582 | pool[addr] += [(iface_name, fqdn, ip)]
|
---|
583 | else:
|
---|
584 | pool[addr] = [(iface_name, fqdn, ip)]
|
---|
585 | continue
|
---|
586 |
|
---|
587 | # wleiden_zone["2%s-%s.%s" % ("unused", iface_name, fqdn)] = ip
|
---|
588 | # #XXX: automatic naming convention namely 2 + remote.lower()
|
---|
589 | for (key,value) in pool.iteritems():
|
---|
590 | if len(value) == 1:
|
---|
591 | (iface_name, fqdn, ip) = value[0]
|
---|
592 | wleiden_zone["2unused-%s.%s" % (iface_name, fqdn)] = ip
|
---|
593 | elif len(value) == 2:
|
---|
594 | (a_iface_name, a_fqdn, a_ip) = value[0]
|
---|
595 | (b_iface_name, b_fqdn, b_ip) = value[1]
|
---|
596 | wleiden_zone["2%s.%s" % (b_fqdn,a_fqdn)] = a_ip
|
---|
597 | wleiden_zone["2%s.%s" % (a_fqdn,b_fqdn)] = b_ip
|
---|
598 | else:
|
---|
599 | pool_members = [k[1] for k in value]
|
---|
600 | for item in value:
|
---|
601 | (iface_name, fqdn, ip) = item
|
---|
602 | pool_name = "2pool-" + showaddr(key).replace('.','-') + "-" + "_".join(sorted(list(set(pool_members) - set([fqdn]))))
|
---|
603 | wleiden_zone["%s.%s" % (pool_name, fqdn)] = ip
|
---|
604 |
|
---|
605 |
|
---|
606 | f = open("db.wleiden.net", "w")
|
---|
607 | for host,ip in wleiden_zone.iteritems():
|
---|
608 | f.write("%s.wleiden.net. A %s ~\n" % (host, ip))
|
---|
609 | for source,dest in wleiden_cname.iteritems():
|
---|
610 | f.write("%s.wleiden.net. CNAME %s.wleiden.net. ~\n" % (source, dest))
|
---|
611 | f.close()
|
---|
612 | f = open("db.172.in-addr.arpa", "w")
|
---|
613 | for host,ip in wleiden_zone.iteritems():
|
---|
614 | rev_ip = '.'.join(reversed(ip.split('.')))
|
---|
615 | f.write("%s.in-addr.arpa. PTR %s.wleiden.net. ~\n" % (rev_ip, host))
|
---|
616 | f.close()
|
---|
617 |
|
---|
618 |
|
---|
619 | def usage():
|
---|
620 | print """Usage: %s <standalone [port] |test [test arguments]|static>
|
---|
621 | Examples:
|
---|
622 | \tstandalone = Run configurator webserver [default port=8000]
|
---|
623 | \tstatic = Generate all config files and store on disk
|
---|
624 | \t with format ./static/%%NODE%%/%%FILE%%
|
---|
625 | \ttest CNodeRick dnsmasq.conf = Receive output of CGI script
|
---|
626 | \t for arguments CNodeRick/dnsmasq.conf
|
---|
627 | """
|
---|
628 | exit(0)
|
---|
629 |
|
---|
630 |
|
---|
631 |
|
---|
632 | def main():
|
---|
633 | """Hard working sub"""
|
---|
634 | # Allow easy hacking using the CLI
|
---|
635 | if not os.environ.has_key('PATH_INFO'):
|
---|
636 | if len(sys.argv) < 2:
|
---|
637 | usage()
|
---|
638 |
|
---|
639 | if sys.argv[1] == "standalone":
|
---|
640 | import SocketServer
|
---|
641 | import CGIHTTPServer
|
---|
642 | try:
|
---|
643 | PORT = int(sys.argv[2])
|
---|
644 | except (IndexError,ValueError):
|
---|
645 | PORT = 8000
|
---|
646 |
|
---|
647 | class MyCGIHTTPRequestHandler(CGIHTTPServer.CGIHTTPRequestHandler):
|
---|
648 | """ Serve this CGI from the root of the webserver """
|
---|
649 | def is_cgi(self):
|
---|
650 | if "favicon" in self.path:
|
---|
651 | return False
|
---|
652 |
|
---|
653 | self.cgi_info = (__file__, self.path)
|
---|
654 | self.path = ''
|
---|
655 | return True
|
---|
656 | handler = MyCGIHTTPRequestHandler
|
---|
657 | httpd = SocketServer.TCPServer(("", PORT), handler)
|
---|
658 | httpd.server_name = 'localhost'
|
---|
659 | httpd.server_port = PORT
|
---|
660 |
|
---|
661 | print "serving at port", PORT
|
---|
662 | httpd.serve_forever()
|
---|
663 | elif sys.argv[1] == "test":
|
---|
664 | os.environ['PATH_INFO'] = "/".join(sys.argv[2:])
|
---|
665 | os.environ['SCRIPT_NAME'] = __file__
|
---|
666 | process_cgi_request()
|
---|
667 | elif sys.argv[1] == "static":
|
---|
668 | items = dict()
|
---|
669 | for node in get_hostlist():
|
---|
670 | items['node'] = node
|
---|
671 | items['wdir'] = "./static/%(node)s" % items
|
---|
672 | if not os.path.isdir(items['wdir']):
|
---|
673 | os.makedirs(items['wdir'])
|
---|
674 | datadump = get_yaml(node)
|
---|
675 | for config in files:
|
---|
676 | items['config'] = config
|
---|
677 | print "## Generating %(node)s %(config)s" % items
|
---|
678 | f = open("%(wdir)s/%(config)s" % items, "w")
|
---|
679 | f.write(generate_config(node, config, datadump))
|
---|
680 | f.close()
|
---|
681 | elif sys.argv[1] == "dns":
|
---|
682 | make_dns()
|
---|
683 | elif sys.argv[1] == "cleanup":
|
---|
684 | # First generate all datadumps
|
---|
685 | datadumps = dict()
|
---|
686 | for host in get_hostlist():
|
---|
687 | datadump = get_yaml(host)
|
---|
688 | datadumps[get_fqdn(datadump)] = datadump
|
---|
689 |
|
---|
690 | datadump['latitude'], datadump['longitude'] = make_map.rd2etrs(datadump['rdnap_x'], datadump['rdnap_y'])
|
---|
691 | write_yaml(host, datadump)
|
---|
692 | else:
|
---|
693 | usage()
|
---|
694 | else:
|
---|
695 | cgitb.enable()
|
---|
696 | process_cgi_request()
|
---|
697 |
|
---|
698 |
|
---|
699 | if __name__ == "__main__":
|
---|
700 | main()
|
---|