source: genesis/nodes/gformat.py@ 8257

Last change on this file since 8257 was 8257, checked in by rick, 14 years ago

Ready for testing

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