source: genesis/nodes/gformat.py@ 8321

Last change on this file since 8321 was 8321, checked in by rick, 15 years ago

Grumble keys got confused everywhere

  • Property svn:executable set to *
  • Property svn:keywords set to Id
File size: 14.5 KB
Line 
1#!/usr/bin/env python
2#
3# vim:ts=2:et:sw=2:ai
4# Wireless Leiden configuration generator, based on yaml files'
5# Rick van der Zwet <info@rickvanderzwet.nl>
6import cgi
7import cgitb
8import copy
9import glob
10import os
11import socket
12import string
13import subprocess
14import sys
15import time
16import yaml
17
18NODE_DIR = os.path.dirname(os.path.realpath(__file__))
19__version__ = '$Id: gformat.py 8321 2010-08-12 15:33:42Z rick $'
20
21
22files = [
23 'authorized_keys',
24 'dnsmasq.conf',
25 'rc.conf.local',
26 'resolv.conf',
27 'wleiden.yaml'
28 ]
29
30# Global variables uses
31OK = 0
32UNKNOWN = 1
33DOWN = 2
34
35
36def get_proxylist():
37 """Get all available proxies proxyX sorting based on X number"""
38 os.chdir(NODE_DIR)
39 proxylist = sorted(glob.glob("proxy*"),
40 key=lambda name: int(''.join([c for c in name if c in string.digits])),
41 cmp=lambda x,y: x - y)
42 return proxylist
43
44
45
46def valid_addr(addr):
47 """ Show which address is valid in which are not """
48 return str(addr).startswith('172.')
49
50
51def get_nodelist():
52 """ Get all available nodes - sorted """
53 os.chdir(NODE_DIR)
54 nodelist = sorted(glob.glob("CNode*"))
55 return nodelist
56
57def get_hostlist():
58 """ Combined hosts and proxy list"""
59 return get_nodelist() + get_proxylist()
60
61
62def generate_title(nodelist):
63 """ Main overview page """
64 items = {'root' : "." }
65 output = """
66<html>
67 <head>
68 <title>Wireless leiden Configurator - GFormat</title>
69 <style type="text/css">
70 th {background-color: #999999}
71 tr:nth-child(odd) {background-color: #cccccc}
72 tr:nth-child(even) {background-color: #ffffff}
73 th, td {padding: 0.1em 1em}
74 </style>
75 </head>
76 <body>
77 <center>
78 <form type="GET" action="%(root)s">
79 <input type="hidden" name="action" value="update">
80 <input type="submit" value="Update Configuration Database (SVN)">
81 </form>
82 <table>
83 <caption><h3>Wireless Leiden Configurator</h3></caption>
84 """ % items
85
86 for node in nodelist:
87 items['node'] = node
88 output += '<tr><td><a href="%(root)s/%(node)s">%(node)s</a></td>' % items
89 for config in files:
90 items['config'] = config
91 output += '<td><a href="%(root)s/%(node)s/%(config)s">%(config)s</a></td>' % items
92 output += "</tr>"
93 output += """
94 </table>
95 <hr />
96 <em>%s</em>
97 </center>
98 </body>
99</html>
100 """ % __version__
101
102 return output
103
104
105
106def generate_node(node):
107 """ Print overview of all files available for node """
108 return "\n".join(files)
109
110
111
112def generate_header(ctag="#"):
113 return """\
114%(ctag)s
115%(ctag)s DO NOT EDIT - Automatically generated by 'gformat'
116%(ctag)s Generated at %(date)s by %(host)s
117%(ctag)s
118""" % { 'ctag' : ctag, 'date' : time.ctime(), 'host' : socket.gethostname() }
119
120
121
122def parseaddr(s):
123 """ Process IPv4 CIDR notation addr to a (binary) number """
124 f = s.split('.')
125 return (long(f[0]) << 24L) + \
126 (long(f[1]) << 16L) + \
127 (long(f[2]) << 8L) + \
128 long(f[3])
129
130
131
132def showaddr(a):
133 """ Display IPv4 addr in (dotted) CIDR notation """
134 return "%d.%d.%d.%d" % ((a >> 24) & 0xff, (a >> 16) & 0xff, (a >> 8) & 0xff, a & 0xff)
135
136
137
138def netmask2subnet(netmask):
139 """ Given a 'netmask' return corresponding CIDR """
140 return showaddr(0xffffffff & (0xffffffff << (32 - int(netmask))))
141
142
143
144def generate_dnsmasq_conf(datadump):
145 """ Generate configuration file '/usr/local/etc/dnsmasq.conf' """
146 output = generate_header()
147 output += """\
148# DHCP server options
149dhcp-authoritative
150dhcp-fqdn
151domain=dhcp.%(nodename_lower)s.%(domain)s
152domain-needed
153expand-hosts
154
155# Low memory footprint
156cache-size=10000
157 \n""" % datadump
158
159 for iface_key in datadump['iface_keys']:
160 if not datadump[iface_key].has_key('comment'):
161 datadump[iface_key]['comment'] = None
162 output += "## %(interface)s - %(desc)s - %(comment)s\n" % datadump[iface_key]
163
164 try:
165 (dhcp_start, dhcp_stop) = datadump[iface_key]['dhcp'].split('-')
166 (ip, netmask) = datadump[iface_key]['ip'].split('/')
167 datadump[iface_key]['subnet'] = netmask2subnet(netmask)
168 except (AttributeError, ValueError):
169 output += "# not autoritive\n\n"
170 continue
171
172 dhcp_part = ".".join(ip.split('.')[0:3])
173 datadump[iface_key]['dhcp_start'] = dhcp_part + "." + dhcp_start
174 datadump[iface_key]['dhcp_stop'] = dhcp_part + "." + dhcp_stop
175 output += "dhcp-range=%(interface)s,%(dhcp_start)s,%(dhcp_stop)s,%(subnet)s,24h\n\n" % datadump[iface_key]
176
177 return output
178
179
180
181def generate_rc_conf_local(datadump):
182 """ Generate configuration file '/etc/rc.conf.local' """
183 output = generate_header("#");
184 output += """\
185hostname='%(nodetype)s%(nodename)s.%(domain)s'
186location='%(location)s'
187""" % datadump
188
189 # TProxy configuration
190 output += "\n"
191 try:
192 if datadump['tproxy']:
193 output += """\
194tproxy_enable='YES'
195tproxy_range='%(tproxy)s'
196""" % datadump
197 except KeyError:
198 output += "tproxy_enable='NO'\n"
199
200 output += '\n'
201 # lo0 configuration:
202 # - 172.32.255.1/32 is the proxy.wleiden.net deflector
203 # - masterip is special as it needs to be assigned to at
204 # least one interface, so if not used assign to lo0
205 addrs_list = { 'lo0' : ["127.0.0.1/8", "172.31.255.1/32"] }
206 iface_map = {'lo0' : 'lo0'}
207
208 masterip_used = False
209 for iface_key in datadump['iface_keys']:
210 if datadump[iface_key]['ip'].startswith(datadump['masterip']):
211 masterip_used = True
212 break
213 if not masterip_used:
214 addrs_list['lo0'].append(datadump['masterip'] + "/32")
215
216 wlan_count = 0
217 for iface_key in datadump['iface_keys']:
218 ifacedump = datadump[iface_key]
219 interface = ifacedump['interface']
220 # By default no special interface mapping
221 iface_map[interface] = interface
222
223 # Add interface IP to list
224 if addrs_list.has_key(interface):
225 addrs_list[interface].append(ifacedump['ip'])
226 else:
227 addrs_list[interface] = [ifacedump['ip']]
228
229 # Alias only needs IP assignment for now, this might change if we
230 # are going to use virtual accesspoints
231 if "alias" in iface_key:
232 continue
233
234 # XXX: Might want to deduct type directly from interface name
235 if ifacedump['type'] in ['11a', '11b', '11g', 'wireless']:
236 # Create wlanX interface
237 ifacedump['wlanif'] ="wlan%i" % wlan_count
238 iface_map[interface] = ifacedump['wlanif']
239 wlan_count += 1
240
241 # Default to station (client) mode
242 ifacedump['wlanmode'] = "sta"
243 if ifacedump['mode'] in ['master', 'master-wds']:
244 ifacedump['wlanmode'] = "ap"
245 # Default to 802.11b mode
246 ifacedump['mode'] = '11b'
247 if ifacedump['type'] in ['11a', '11b' '11g']:
248 ifacedump['mode'] = ifacedump['type']
249
250 if not ifacedump.has_key('channel'):
251 if ifacedump['type'] == '11a':
252 ifacedump['channel'] = 36
253 else:
254 ifacedump['channel'] = 1
255
256 # Allow special hacks at the back like wds and stuff
257 if not ifacedump.has_key('extra'):
258 ifacedump['extra'] = 'regdomain ETSI country NL'
259
260 output += "wlans_%(interface)s='%(wlanif)s'\n" % ifacedump
261 output += ("create_args_%(wlanif)s='wlanmode %(wlanmode)s mode " +\
262 "%(mode)s ssid %(ssid)s %(extra)s channel %(channel)s'\n") % ifacedump
263
264 elif ifacedump['type'] in ['ethernet', 'eth']:
265 # No special config needed besides IP
266 pass
267 else:
268 assert False, "Unknown type " + ifacedump['type']
269
270 # Print IP address which needs to be assigned over here
271 output += "\n"
272 for iface,addrs in sorted(addrs_list.iteritems()):
273 output += "ipv4_addrs_%s='%s'\n" % (iface_map[iface], " ".join(addrs))
274
275 return output
276
277
278
279def get_yaml(item):
280 """ Get configuration yaml for 'item'"""
281 gfile = NODE_DIR + '/%s/wleiden.yaml' % item
282
283 f = open(gfile, 'r')
284 datadump = yaml.load(f)
285 f.close()
286
287 return datadump
288
289
290
291def get_all_configs():
292 """ Get dict with key 'host' with all configs present """
293 configs = dict()
294 for host in get_hostlist():
295 datadump = get_yaml(host)
296 configs[host] = datadump
297 return configs
298
299
300def get_interface_keys(config):
301 """ Quick hack to get all interface keys, later stage convert this to a iterator """
302 return [elem for elem in config.keys() if (elem.startswith('iface_') and not "lo0" in elem)]
303
304
305def get_used_ips(configs):
306 """ Return array of all IPs used in config files"""
307 ip_list = []
308 for config in configs:
309 ip_list.append(config['masterip'])
310 for iface_key in get_interface_keys(config):
311 l = config[iface_key]['ip']
312 addr, mask = l.split('/')
313 # Special case do not process
314 if not valid_addr(addr):
315 ip_list.append(addr)
316 return sorted(ip_list)
317
318
319
320def write_yaml(item, datadump):
321 """ Write configuration yaml for 'item'"""
322 gfile = NODE_DIR + '/%s/wleiden.yaml' % item
323
324 f = open(gfile, 'w')
325 f.write(format_wleiden_yaml(datadump))
326 f.close()
327
328
329
330def generate_resolv_conf(datadump):
331 """ Generate configuration file '/etc/resolv.conf' """
332 output = generate_header("#");
333 output += """\
334search wleiden.net
335# Try local (cache) first
336nameserver 127.0.0.1
337
338# Proxies are recursive nameservers
339# needs to be in resolv.conf for dnsmasq as well
340""" % datadump
341
342 for proxy in get_proxylist():
343 proxy_ip = get_yaml(proxy)['masterip']
344 output += "nameserver %-15s # %s\n" % (proxy_ip, proxy)
345 return output
346
347
348
349def format_yaml_value(value):
350 """ Get yaml value in right syntax for outputting """
351 if isinstance(value,str):
352 output = "'%s'" % value
353 else:
354 output = value
355 return output
356
357
358
359def format_wleiden_yaml(datadump):
360 """ Special formatting to ensure it is editable"""
361 output = "# Genesis config yaml style\n"
362 output += "# vim:ts=2:et:sw=2:ai\n"
363 output += "#\n"
364 iface_keys = [elem for elem in datadump.keys() if elem.startswith('iface_')]
365 for key in sorted(set(datadump.keys()) - set(iface_keys)):
366 output += "%-10s: %s\n" % (key, format_yaml_value(datadump[key]))
367
368 output += "\n\n"
369
370 key_order = [ 'comment', 'interface', 'ip', 'desc', 'sdesc', 'mode', 'type',
371 'extra_type', 'channel', 'ssid', 'dhcp' ]
372
373 for iface_key in sorted(iface_keys):
374 output += "%s:\n" % iface_key
375 for key in key_order + list(sorted(set(datadump[iface_key].keys()) - set(key_order))):
376 if datadump[iface_key].has_key(key):
377 output += " %-11s: %s\n" % (key, format_yaml_value(datadump[iface_key][key]))
378 output += "\n\n"
379
380 return output
381
382
383
384def generate_wleiden_yaml(datadump):
385 """ Generate (petty) version of wleiden.yaml"""
386 output = generate_header("#")
387 output += format_wleiden_yaml(datadump)
388 return output
389
390
391
392def generate_config(node, config, datadump=None):
393 """ Print configuration file 'config' of 'node' """
394 output = ""
395 try:
396 # Load config file
397 if datadump == None:
398 datadump = get_yaml(node)
399
400 # Preformat certain needed variables for formatting and push those into special object
401 datadump_extra = copy.deepcopy(datadump)
402 if not datadump_extra.has_key('domain'):
403 datadump_extra['domain'] = 'wleiden.net'
404 datadump_extra['nodename_lower'] = datadump_extra['nodename'].lower()
405 datadump_extra['iface_keys'] = sorted([elem for elem in datadump.keys() if elem.startswith('iface_')])
406
407 if config == 'wleiden.yaml':
408 output += generate_wleiden_yaml(datadump)
409 elif config == 'authorized_keys':
410 f = open("global_keys", 'r')
411 output += f.read()
412 f.close()
413 elif config == 'dnsmasq.conf':
414 output += generate_dnsmasq_conf(datadump_extra)
415 elif config == 'rc.conf.local':
416 output += generate_rc_conf_local(datadump_extra)
417 elif config == 'resolv.conf':
418 output += generate_resolv_conf(datadump_extra)
419 else:
420 assert False, "Config not found!"
421 except IOError, e:
422 output += "[ERROR] Config file not found"
423 return output
424
425
426
427def process_cgi_request():
428 """ When calling from CGI """
429 # Update repository if requested
430 form = cgi.FieldStorage()
431 if form.getvalue("action") == "update":
432 print "Refresh: 5; url=."
433 print "Content-type:text/plain\r\n\r\n",
434 print "[INFO] Updating subverion, please wait..."
435 print subprocess.Popen(['svn', 'up', NODE_DIR], stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0],
436 print "[INFO] All done, redirecting in 5 seconds"
437 sys.exit(0)
438
439
440 uri = os.environ['PATH_INFO'].strip('/').split('/')
441 output = ""
442 if not uri[0]:
443 output += "Content-type:text/html\r\n\r\n"
444 output += generate_title(get_hostlist())
445 elif len(uri) == 1:
446 output += "Content-type:text/plain\r\n\r\n"
447 output += generate_node(uri[0])
448 elif len(uri) == 2:
449 output += "Content-type:text/plain\r\n\r\n"
450 output += generate_config(uri[0], uri[1])
451 else:
452 assert False, "Invalid option"
453 print output
454
455
456def usage():
457 print """Usage: %s <standalone [port] |test [test arguments]|static>
458Examples:
459\tstandalone = Run configurator webserver [default port=8000]
460\tstatic = Generate all config files and store on disk
461\t with format ./static/%%NODE%%/%%FILE%%
462\ttest CNodeRick dnsmasq.conf = Receive output of CGI script
463\t for arguments CNodeRick/dnsmasq.conf
464"""
465 exit(0)
466
467
468
469def main():
470 """Hard working sub"""
471 # Allow easy hacking using the CLI
472 if not os.environ.has_key('PATH_INFO'):
473 if len(sys.argv) < 2:
474 usage()
475
476 if sys.argv[1] == "standalone":
477 import SocketServer
478 import CGIHTTPServer
479 try:
480 PORT = int(sys.argv[2])
481 except (IndexError,ValueError):
482 PORT = 8000
483
484 class MyCGIHTTPRequestHandler(CGIHTTPServer.CGIHTTPRequestHandler):
485 """ Serve this CGI from the root of the webserver """
486 def is_cgi(self):
487 if "favicon" in self.path:
488 return False
489
490 self.cgi_info = (__file__, self.path)
491 self.path = ''
492 return True
493 handler = MyCGIHTTPRequestHandler
494 httpd = SocketServer.TCPServer(("", PORT), handler)
495 httpd.server_name = 'localhost'
496 httpd.server_port = PORT
497
498 print "serving at port", PORT
499 httpd.serve_forever()
500 elif sys.argv[1] == "test":
501 os.environ['PATH_INFO'] = "/".join(sys.argv[2:])
502 os.environ['SCRIPT_NAME'] = __file__
503 process_cgi_request()
504 elif sys.argv[1] == "static":
505 items = dict()
506 for node in get_hostlist():
507 items['node'] = node
508 items['wdir'] = "./static/%(node)s" % items
509 if not os.path.isdir(items['wdir']):
510 os.makedirs(items['wdir'])
511 datadump = get_yaml(node)
512 for config in files:
513 items['config'] = config
514 print "## Generating %(node)s %(config)s" % items
515 f = open("%(wdir)s/%(config)s" % items, "w")
516 f.write(generate_config(node, config, datadump))
517 f.close()
518 else:
519 usage()
520 else:
521 cgitb.enable()
522 process_cgi_request()
523
524
525if __name__ == "__main__":
526 main()
Note: See TracBrowser for help on using the repository browser.