source: genesis/nodes/gformat.py@ 8242

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

I am getting tried of the perl misery in both config and the 'template' engine. This will replace it pretty darn soon

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