source: genesis/nodes/gformat.py@ 8258

Last change on this file since 8258 was 8258, checked in by rick, 14 years ago
  • More generic paths
  • Hack to allow easy checking
  • Property svn:executable set to *
  • Property svn:keywords set to Id
File size: 9.9 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 glob
8import os
9import socket
10import string
11import subprocess
12import sys
13import time
14import yaml
15
16NODE_DIR = os.path.dirname(os.path.realpath(__file__))
17__version__ = '$Id: gformat.py 8258 2010-08-08 09:58:32Z rick $'
18
19files = [
20 'authorized_keys',
21 'dnsmasq.conf',
22 'rc.conf.local',
23 'resolv.conf',
24 'wleiden.yaml'
25 ]
26
27
28
29def print_title(nodelist):
30 """ Main overview page """
31 items = {'root' : os.environ['SCRIPT_NAME'] }
32 print """
33<html>
34 <head>
35 <title>Wireless leiden Configurator - GFormat</title>
36 <style type="text/css">
37 th {background-color: #999999}
38 tr:nth-child(odd) {background-color: #cccccc}
39 tr:nth-child(even) {background-color: #ffffff}
40 th, td {padding: 0.1em 1em}
41 </style>
42 </head>
43 <body>
44 <center>
45 <form type="GET" action="">
46 <input type="hidden" name="action" value="update">
47 <input type="submit" value="Update Configuration Database (SVN)">
48 </form>
49 <table>
50 <caption><h3>Wireless Leiden Configurator</h3></caption>
51 """ % items
52
53 for node in sorted(nodelist):
54 items['node'] = node
55 print '<tr><td><a href="%(root)s/%(node)s">%(node)s</a></td>' % items
56 for config in files:
57 items['config'] = config
58 print '<td><a href="%(root)s/%(node)s/%(config)s">%(config)s</a></td>' % items
59 print "</tr>"
60 print """
61 </table>
62 <hr />
63 <em>%s</em>
64 </center>
65 </body>
66</html>
67 """ % __version__
68
69
70
71def print_node(node):
72 """ Print overview of all files available for node """
73 print "\n".join(files)
74
75
76
77def generate_header(ctag="#"):
78 return """\
79%(ctag)s
80%(ctag)s DO NOT EDIT - Automatically generated by 'gformat'
81%(ctag)s Generated at %(date)s by %(host)s
82%(ctag)s
83""" % { 'ctag' : ctag, 'date' : time.ctime(), 'host' : socket.gethostname() }
84
85
86
87def parseaddr(s):
88 """ Process IPv4 CIDR notation addr to a (binary) number """
89 f = s.split('.')
90 return (long(f[0]) << 24L) + \
91 (long(f[1]) << 16L) + \
92 (long(f[2]) << 8L) + \
93 long(f[3])
94
95
96
97def showaddr(a):
98 """ Display IPv4 addr in (dotted) CIDR notation """
99 return "%d.%d.%d.%d" % ((a >> 24) & 0xff, (a >> 16) & 0xff, (a >> 8) & 0xff, a & 0xff)
100
101
102
103def netmask2subnet(netmask):
104 """ Given a 'netmask' return corresponding CIDR """
105 return showaddr(0xffffffff & (0xffffffff << (32 - int(netmask))))
106
107
108
109def generate_dnsmasq_conf(datadump):
110 """ Generate configuration file '/usr/local/etc/dnsmasq.conf' """
111 output = generate_header()
112 output += """\
113# DHCP server options
114dhcp-authoritative
115dhcp-fqdn
116domain=dhcp.%(nodename_lower)s.%(domain)s
117domain-needed
118expand-hosts
119
120# Low memory footprint
121cache-size=10000
122 \n""" % datadump
123
124 for iface_key in datadump['iface_keys']:
125 output += "## %(interface)s %(desc)s\n" % datadump[iface_key]
126
127 try:
128 (dhcp_start, dhcp_stop) = datadump[iface_key]['dhcp'].split('-')
129 (ip, netmask) = datadump[iface_key]['ip'].split('/')
130 datadump[iface_key]['subnet'] = netmask2subnet(netmask)
131 except AttributeError:
132 output += "# not autoritive\n\n"
133 continue
134
135 dhcp_part = ".".join(ip.split('.')[0:3])
136 datadump[iface_key]['dhcp_start'] = dhcp_part + "." + dhcp_start
137 datadump[iface_key]['dhcp_stop'] = dhcp_part + "." + dhcp_stop
138 output += "dhcp-range=%(interface)s,%(dhcp_start)s,%(dhcp_stop)s,%(subnet)s,24h\n\n" % datadump[iface_key]
139
140 return output
141
142
143
144def generate_rc_conf_local(datadump):
145 """ Generate configuration file '/etc/rc.conf.local' """
146 output = generate_header("#");
147 output += """\
148hostname='%(nodetype)s%(nodename)s.%(domain)s'
149location='%(location)s'
150""" % datadump
151
152 # TProxy configuration
153 output += "\n"
154 try:
155 if datadump['tproxy']:
156 output += """\
157tproxy_enable='YES'
158tproxy_range='%(tproxy)s'
159""" % datadump
160 except KeyError:
161 output += "tproxy_enable='NO'\n"
162
163 output += '\n'
164 # lo0 configuration:
165 # - 172.32.255.1/32 is the proxy.wleiden.net deflector
166 # - masterip is special as it needs to be assigned to at
167 # least one interface, so if not used assign to lo0
168 addrs_list = { 'lo0' : ["127.0.0.1/8", "172.31.255.1/32"] }
169 iface_map = {'lo0' : 'lo0'}
170 if not any([datadump[iface_key]['ip'].startswith(datadump['masterip']) \
171 for iface_key in datadump['iface_keys']]):
172 lo0_addrs.append(datadump['masterip'] + "/32")
173
174 wlan_count = 0
175 for iface_key in datadump['iface_keys']:
176 ifacedump = datadump[iface_key]
177 interface = ifacedump['interface']
178 # By default no special interface mapping
179 iface_map[interface] = interface
180
181 # Add interface IP to list
182 if addrs_list.has_key(interface):
183 addrs_list[interface].append(ifacedump['ip'])
184 else:
185 addrs_list[interface] = [ifacedump['ip']]
186
187 # Alias only needs IP assignment for now, this might change if we
188 # are going to use virtual accesspoints
189 if "alias" in iface_key:
190 continue
191
192 # XXX: Might want to deduct type directly from interface name
193 if ifacedump['type'] in ['11a', '11b', '11g', 'wireless']:
194 # Create wlanX interface
195 ifacedump['wlanif'] ="wlan%i" % wlan_count
196 iface_map[interface] = ifacedump['wlanif']
197 wlan_count += 1
198
199 # Default to station (client) mode
200 ifacedump['wlanmode'] = "sta"
201 if ifacedump['mode'] in ['master']:
202 ifacedump['wlanmode'] = "ap"
203 # Default to 802.11b mode
204 ifacedump['mode'] = '11b'
205 if ifacedump['type'] in ['11a', '11b' '11g']:
206 ifacedump['mode'] = ifacedump['type']
207
208 if not ifacedump.has_key('channel'):
209 if ifacedump['type'] == '11a':
210 ifacedump['channel'] = 36
211 else:
212 ifacedump['channel'] = 1
213
214 # Allow special hacks at the back like wds and stuff
215 if not ifacedump.has_key('extra'):
216 ifacedump['extra'] = 'regdomain ETSI country NL'
217
218 output += "wlans_%(interface)s='%(wlanif)s'\n" % ifacedump
219 output += ("create_args_%(wlanif)s='wlanmode %(wlanmode)s mode " +\
220 "%(mode)s ssid %(ssid)s channel %(channel)s %(extra)s'\n") % ifacedump
221
222 elif ifacedump['type'] in ['ethernet', 'eth']:
223 # No special config needed besides IP
224 pass
225 else:
226 assert False, "Unknown type " + ifacedump['type']
227
228 # Print IP address which needs to be assigned over here
229 output += "\n"
230 for iface,addrs in sorted(addrs_list.iteritems()):
231 output += "ipv4_addrs_%s='%s'\n" % (iface_map[iface], " ".join(addrs))
232
233 return output
234
235
236
237def get_yaml(item):
238 """ Get configuration yaml for 'item'"""
239 gfile = NODE_DIR + '/%s/wleiden.yaml' % item
240 gfile = 'test.yaml'
241
242 f = open(gfile, 'r')
243 datadump = yaml.load(f)
244 f.close()
245
246 return datadump
247
248
249
250def generate_resolv_conf(datadump):
251 """ Generate configuration file '/etc/resolv.conf' """
252 output = generate_header("#");
253 output += """\
254search wleiden.net
255# Try local (cache) first
256nameserver 127.0.0.1
257
258# Proxies are recursive nameservers
259# needs to be in resolv.conf for dnsmasq as well
260""" % datadump
261
262 # proxyX sorting based on X number
263 os.chdir(NODE_DIR)
264 proxies = sorted(glob.glob("proxy*"),
265 key=lambda name: int(''.join([c for c in name if c in string.digits])),
266 cmp=lambda x,y: x - y)
267
268 for proxy in proxies:
269 proxy_ip = get_yaml(proxy)['masterip']
270 output += "nameserver %-15s # %s\n" % (proxy_ip, proxy)
271 return output
272
273
274
275def generate_wleiden_yaml(datadump):
276 """ Special formatting to ensure it is editable"""
277 output = generate_header("#")
278 output += "# Genesis config yaml style\n"
279 output += "#\n"
280 iface_keys = [elem for elem in datadump.keys() if elem.startswith('iface_')]
281 for key in sorted(set(datadump.keys()) - set(iface_keys)):
282 output += "%s: %s\n" % (key, datadump[key])
283
284 output += "\n\n"
285
286 for iface_key in sorted(iface_keys):
287 output += "%s:\n" % iface_key
288 output += yaml.dump(datadump[iface_key], default_flow_style=False)
289 output += "\n\n"
290
291 return output
292
293
294
295def print_config(node, config):
296 """ Print configuration file 'config' of 'node' """
297 try:
298 # Load config file
299 datadump = get_yaml(node)
300
301 if config == 'wleiden.yaml':
302 print generate_wleiden_yaml(datadump)
303 return
304
305 # Preformat certain needed variables for formatting
306 if not datadump.has_key('domain'):
307 datadump['domain'] = 'wleiden.net'
308 datadump['nodename_lower'] = datadump['nodename'].lower()
309 datadump['iface_keys'] = sorted([elem for elem in datadump.keys() if elem.startswith('iface_')])
310
311 if config == 'authorized_keys':
312 f = open("global_keys", 'r')
313 print f.read()
314 f.close()
315 elif config == 'dnsmasq.conf':
316 print generate_dnsmasq_conf(datadump)
317 elif config == 'rc.conf.local':
318 print generate_rc_conf_local(datadump)
319 elif config == 'resolv.conf':
320 print generate_resolv_conf(datadump)
321 else:
322 assert False, "Config not found!"
323 except IOError, e:
324 print "[ERROR] Config file not found"
325
326
327
328def process_cgi_request():
329 """ When calling from CGI """
330 # Update repository if requested
331 form = cgi.FieldStorage()
332 if form.getvalue("action") == "update":
333 print "Refresh: 5; url=%s" % os.environ['SCRIPT_NAME']
334 print "Content-type:text/plain\r\n\r\n",
335 print "[INFO] Updating subverion, please wait..."
336 print subprocess.Popen(['svn', 'up', NODE_DIR], stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0],
337 print "[INFO] All done, redirecting in 5 seconds"
338 sys.exit(0)
339
340 os.chdir(NODE_DIR)
341 nodelist = glob.glob("CNode*")
342
343 uri = os.environ['PATH_INFO'].strip('/').split('/')
344 if not uri[0]:
345 print "Content-type:text/html\r\n\r\n",
346 print_title(nodelist)
347 elif len(uri) == 1:
348 print "Content-type:text/plain\r\n\r\n",
349 print_node(uri[0])
350 elif len(uri) == 2:
351 print "Content-type:text/plain\r\n\r\n",
352 print_config(uri[0], uri[1])
353 else:
354 assert False, "Invalid option"
355
356# Allow easy hacking using the CLI
357if not os.environ.has_key('PATH_INFO'):
358 os.environ['PATH_INFO'] = "/".join(sys.argv[1:])
359 os.environ['SCRIPT_NAME'] = __file__
360
361process_cgi_request()
Note: See TracBrowser for help on using the repository browser.