[8242] | 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
|
---|
[8267] | 7 | import cgitb
|
---|
| 8 | import copy
|
---|
[8242] | 9 | import glob
|
---|
| 10 | import os
|
---|
| 11 | import socket
|
---|
| 12 | import string
|
---|
| 13 | import subprocess
|
---|
| 14 | import sys
|
---|
| 15 | import time
|
---|
| 16 | import yaml
|
---|
| 17 |
|
---|
[8258] | 18 | NODE_DIR = os.path.dirname(os.path.realpath(__file__))
|
---|
[8242] | 19 | __version__ = '$Id: gformat.py 8323 2010-08-12 18:51:19Z rick $'
|
---|
| 20 |
|
---|
[8267] | 21 |
|
---|
[8242] | 22 | files = [
|
---|
| 23 | 'authorized_keys',
|
---|
| 24 | 'dnsmasq.conf',
|
---|
| 25 | 'rc.conf.local',
|
---|
| 26 | 'resolv.conf',
|
---|
| 27 | 'wleiden.yaml'
|
---|
| 28 | ]
|
---|
| 29 |
|
---|
[8319] | 30 | # Global variables uses
|
---|
[8323] | 31 | OK = 10
|
---|
| 32 | DOWN = 20
|
---|
| 33 | UNKNOWN = 90
|
---|
[8257] | 34 |
|
---|
| 35 |
|
---|
[8267] | 36 | def 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 |
|
---|
[8321] | 46 | def valid_addr(addr):
|
---|
| 47 | """ Show which address is valid in which are not """
|
---|
| 48 | return str(addr).startswith('172.')
|
---|
| 49 |
|
---|
| 50 |
|
---|
[8267] | 51 | def get_nodelist():
|
---|
| 52 | """ Get all available nodes - sorted """
|
---|
| 53 | os.chdir(NODE_DIR)
|
---|
| 54 | nodelist = sorted(glob.glob("CNode*"))
|
---|
| 55 | return nodelist
|
---|
| 56 |
|
---|
[8296] | 57 | def get_hostlist():
|
---|
| 58 | """ Combined hosts and proxy list"""
|
---|
| 59 | return get_nodelist() + get_proxylist()
|
---|
[8267] | 60 |
|
---|
| 61 |
|
---|
| 62 | def generate_title(nodelist):
|
---|
[8257] | 63 | """ Main overview page """
|
---|
[8259] | 64 | items = {'root' : "." }
|
---|
[8267] | 65 | output = """
|
---|
[8257] | 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>
|
---|
[8259] | 78 | <form type="GET" action="%(root)s">
|
---|
[8257] | 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
|
---|
[8242] | 85 |
|
---|
[8296] | 86 | for node in nodelist:
|
---|
[8257] | 87 | items['node'] = node
|
---|
[8267] | 88 | output += '<tr><td><a href="%(root)s/%(node)s">%(node)s</a></td>' % items
|
---|
[8257] | 89 | for config in files:
|
---|
| 90 | items['config'] = config
|
---|
[8267] | 91 | output += '<td><a href="%(root)s/%(node)s/%(config)s">%(config)s</a></td>' % items
|
---|
| 92 | output += "</tr>"
|
---|
| 93 | output += """
|
---|
[8257] | 94 | </table>
|
---|
| 95 | <hr />
|
---|
| 96 | <em>%s</em>
|
---|
| 97 | </center>
|
---|
| 98 | </body>
|
---|
| 99 | </html>
|
---|
| 100 | """ % __version__
|
---|
[8242] | 101 |
|
---|
[8267] | 102 | return output
|
---|
[8257] | 103 |
|
---|
| 104 |
|
---|
[8267] | 105 |
|
---|
| 106 | def generate_node(node):
|
---|
[8257] | 107 | """ Print overview of all files available for node """
|
---|
[8267] | 108 | return "\n".join(files)
|
---|
[8242] | 109 |
|
---|
[8257] | 110 |
|
---|
| 111 |
|
---|
[8242] | 112 | def 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 |
|
---|
[8257] | 120 |
|
---|
| 121 |
|
---|
[8242] | 122 | def parseaddr(s):
|
---|
[8257] | 123 | """ Process IPv4 CIDR notation addr to a (binary) number """
|
---|
[8242] | 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 |
|
---|
[8257] | 130 |
|
---|
| 131 |
|
---|
[8242] | 132 | def showaddr(a):
|
---|
[8257] | 133 | """ Display IPv4 addr in (dotted) CIDR notation """
|
---|
[8242] | 134 | return "%d.%d.%d.%d" % ((a >> 24) & 0xff, (a >> 16) & 0xff, (a >> 8) & 0xff, a & 0xff)
|
---|
| 135 |
|
---|
[8257] | 136 |
|
---|
| 137 |
|
---|
[8242] | 138 | def netmask2subnet(netmask):
|
---|
[8257] | 139 | """ Given a 'netmask' return corresponding CIDR """
|
---|
[8242] | 140 | return showaddr(0xffffffff & (0xffffffff << (32 - int(netmask))))
|
---|
| 141 |
|
---|
[8257] | 142 |
|
---|
| 143 |
|
---|
[8242] | 144 | def generate_dnsmasq_conf(datadump):
|
---|
[8257] | 145 | """ Generate configuration file '/usr/local/etc/dnsmasq.conf' """
|
---|
[8242] | 146 | output = generate_header()
|
---|
| 147 | output += """\
|
---|
| 148 | # DHCP server options
|
---|
| 149 | dhcp-authoritative
|
---|
| 150 | dhcp-fqdn
|
---|
| 151 | domain=dhcp.%(nodename_lower)s.%(domain)s
|
---|
| 152 | domain-needed
|
---|
| 153 | expand-hosts
|
---|
| 154 |
|
---|
| 155 | # Low memory footprint
|
---|
| 156 | cache-size=10000
|
---|
| 157 | \n""" % datadump
|
---|
| 158 |
|
---|
| 159 | for iface_key in datadump['iface_keys']:
|
---|
[8262] | 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]
|
---|
[8242] | 163 |
|
---|
| 164 | try:
|
---|
[8257] | 165 | (dhcp_start, dhcp_stop) = datadump[iface_key]['dhcp'].split('-')
|
---|
[8242] | 166 | (ip, netmask) = datadump[iface_key]['ip'].split('/')
|
---|
| 167 | datadump[iface_key]['subnet'] = netmask2subnet(netmask)
|
---|
[8262] | 168 | except (AttributeError, ValueError):
|
---|
[8242] | 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 |
|
---|
[8257] | 179 |
|
---|
| 180 |
|
---|
[8242] | 181 | def generate_rc_conf_local(datadump):
|
---|
[8257] | 182 | """ Generate configuration file '/etc/rc.conf.local' """
|
---|
[8242] | 183 | output = generate_header("#");
|
---|
| 184 | output += """\
|
---|
| 185 | hostname='%(nodetype)s%(nodename)s.%(domain)s'
|
---|
| 186 | location='%(location)s'
|
---|
| 187 | """ % datadump
|
---|
| 188 |
|
---|
| 189 | # TProxy configuration
|
---|
| 190 | output += "\n"
|
---|
| 191 | try:
|
---|
| 192 | if datadump['tproxy']:
|
---|
| 193 | output += """\
|
---|
| 194 | tproxy_enable='YES'
|
---|
| 195 | tproxy_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 |
|
---|
[8297] | 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 |
|
---|
[8242] | 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"
|
---|
[8274] | 243 | if ifacedump['mode'] in ['master', 'master-wds']:
|
---|
[8242] | 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 " +\
|
---|
[8274] | 262 | "%(mode)s ssid %(ssid)s %(extra)s channel %(channel)s'\n") % ifacedump
|
---|
[8242] | 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 |
|
---|
[8257] | 277 |
|
---|
| 278 |
|
---|
[8242] | 279 | def get_yaml(item):
|
---|
[8257] | 280 | """ Get configuration yaml for 'item'"""
|
---|
[8258] | 281 | gfile = NODE_DIR + '/%s/wleiden.yaml' % item
|
---|
[8242] | 282 |
|
---|
| 283 | f = open(gfile, 'r')
|
---|
| 284 | datadump = yaml.load(f)
|
---|
| 285 | f.close()
|
---|
| 286 |
|
---|
| 287 | return datadump
|
---|
| 288 |
|
---|
[8257] | 289 |
|
---|
| 290 |
|
---|
[8317] | 291 | def 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 |
|
---|
[8319] | 300 | def 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)]
|
---|
[8317] | 303 |
|
---|
[8319] | 304 |
|
---|
[8317] | 305 | def get_used_ips(configs):
|
---|
| 306 | """ Return array of all IPs used in config files"""
|
---|
| 307 | ip_list = []
|
---|
[8319] | 308 | for config in configs:
|
---|
[8317] | 309 | ip_list.append(config['masterip'])
|
---|
[8319] | 310 | for iface_key in get_interface_keys(config):
|
---|
[8317] | 311 | l = config[iface_key]['ip']
|
---|
| 312 | addr, mask = l.split('/')
|
---|
| 313 | # Special case do not process
|
---|
[8321] | 314 | if not valid_addr(addr):
|
---|
[8317] | 315 | ip_list.append(addr)
|
---|
| 316 | return sorted(ip_list)
|
---|
| 317 |
|
---|
| 318 |
|
---|
| 319 |
|
---|
[8267] | 320 | def 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 |
|
---|
[8242] | 330 | def generate_resolv_conf(datadump):
|
---|
[8257] | 331 | """ Generate configuration file '/etc/resolv.conf' """
|
---|
[8242] | 332 | output = generate_header("#");
|
---|
| 333 | output += """\
|
---|
| 334 | search wleiden.net
|
---|
| 335 | # Try local (cache) first
|
---|
| 336 | nameserver 127.0.0.1
|
---|
| 337 |
|
---|
| 338 | # Proxies are recursive nameservers
|
---|
| 339 | # needs to be in resolv.conf for dnsmasq as well
|
---|
| 340 | """ % datadump
|
---|
| 341 |
|
---|
[8267] | 342 | for proxy in get_proxylist():
|
---|
[8242] | 343 | proxy_ip = get_yaml(proxy)['masterip']
|
---|
| 344 | output += "nameserver %-15s # %s\n" % (proxy_ip, proxy)
|
---|
| 345 | return output
|
---|
| 346 |
|
---|
| 347 |
|
---|
[8257] | 348 |
|
---|
[8267] | 349 | def 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 |
|
---|
| 359 | def format_wleiden_yaml(datadump):
|
---|
[8242] | 360 | """ Special formatting to ensure it is editable"""
|
---|
[8267] | 361 | output = "# Genesis config yaml style\n"
|
---|
[8262] | 362 | output += "# vim:ts=2:et:sw=2:ai\n"
|
---|
[8242] | 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)):
|
---|
[8267] | 366 | output += "%-10s: %s\n" % (key, format_yaml_value(datadump[key]))
|
---|
[8242] | 367 |
|
---|
| 368 | output += "\n\n"
|
---|
| 369 |
|
---|
[8272] | 370 | key_order = [ 'comment', 'interface', 'ip', 'desc', 'sdesc', 'mode', 'type',
|
---|
| 371 | 'extra_type', 'channel', 'ssid', 'dhcp' ]
|
---|
| 372 |
|
---|
[8242] | 373 | for iface_key in sorted(iface_keys):
|
---|
| 374 | output += "%s:\n" % iface_key
|
---|
[8272] | 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]))
|
---|
[8242] | 378 | output += "\n\n"
|
---|
| 379 |
|
---|
| 380 | return output
|
---|
| 381 |
|
---|
| 382 |
|
---|
[8257] | 383 |
|
---|
[8267] | 384 | def 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 |
|
---|
[8298] | 392 | def generate_config(node, config, datadump=None):
|
---|
[8257] | 393 | """ Print configuration file 'config' of 'node' """
|
---|
[8267] | 394 | output = ""
|
---|
[8242] | 395 | try:
|
---|
| 396 | # Load config file
|
---|
[8298] | 397 | if datadump == None:
|
---|
| 398 | datadump = get_yaml(node)
|
---|
[8242] | 399 |
|
---|
[8267] | 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 |
|
---|
[8242] | 407 | if config == 'wleiden.yaml':
|
---|
[8267] | 408 | output += generate_wleiden_yaml(datadump)
|
---|
| 409 | elif config == 'authorized_keys':
|
---|
[8242] | 410 | f = open("global_keys", 'r')
|
---|
[8267] | 411 | output += f.read()
|
---|
[8242] | 412 | f.close()
|
---|
| 413 | elif config == 'dnsmasq.conf':
|
---|
[8267] | 414 | output += generate_dnsmasq_conf(datadump_extra)
|
---|
[8242] | 415 | elif config == 'rc.conf.local':
|
---|
[8267] | 416 | output += generate_rc_conf_local(datadump_extra)
|
---|
[8242] | 417 | elif config == 'resolv.conf':
|
---|
[8267] | 418 | output += generate_resolv_conf(datadump_extra)
|
---|
[8242] | 419 | else:
|
---|
| 420 | assert False, "Config not found!"
|
---|
| 421 | except IOError, e:
|
---|
[8267] | 422 | output += "[ERROR] Config file not found"
|
---|
| 423 | return output
|
---|
[8242] | 424 |
|
---|
| 425 |
|
---|
[8257] | 426 |
|
---|
[8258] | 427 | def process_cgi_request():
|
---|
| 428 | """ When calling from CGI """
|
---|
| 429 | # Update repository if requested
|
---|
| 430 | form = cgi.FieldStorage()
|
---|
| 431 | if form.getvalue("action") == "update":
|
---|
[8259] | 432 | print "Refresh: 5; url=."
|
---|
[8258] | 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('/')
|
---|
[8267] | 441 | output = ""
|
---|
[8258] | 442 | if not uri[0]:
|
---|
[8267] | 443 | output += "Content-type:text/html\r\n\r\n"
|
---|
[8296] | 444 | output += generate_title(get_hostlist())
|
---|
[8258] | 445 | elif len(uri) == 1:
|
---|
[8267] | 446 | output += "Content-type:text/plain\r\n\r\n"
|
---|
| 447 | output += generate_node(uri[0])
|
---|
[8258] | 448 | elif len(uri) == 2:
|
---|
[8267] | 449 | output += "Content-type:text/plain\r\n\r\n"
|
---|
| 450 | output += generate_config(uri[0], uri[1])
|
---|
[8258] | 451 | else:
|
---|
| 452 | assert False, "Invalid option"
|
---|
[8267] | 453 | print output
|
---|
[8242] | 454 |
|
---|
[8259] | 455 |
|
---|
| 456 | def usage():
|
---|
[8296] | 457 | print """Usage: %s <standalone [port] |test [test arguments]|static>
|
---|
[8259] | 458 | Examples:
|
---|
| 459 | \tstandalone = Run configurator webserver [default port=8000]
|
---|
[8296] | 460 | \tstatic = Generate all config files and store on disk
|
---|
| 461 | \t with format ./static/%%NODE%%/%%FILE%%
|
---|
[8259] | 462 | \ttest CNodeRick dnsmasq.conf = Receive output of CGI script
|
---|
| 463 | \t for arguments CNodeRick/dnsmasq.conf
|
---|
| 464 | """
|
---|
| 465 | exit(0)
|
---|
| 466 |
|
---|
| 467 |
|
---|
| 468 |
|
---|
[8267] | 469 | def 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()
|
---|
[8296] | 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'])
|
---|
[8298] | 511 | datadump = get_yaml(node)
|
---|
[8296] | 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")
|
---|
[8298] | 516 | f.write(generate_config(node, config, datadump))
|
---|
[8296] | 517 | f.close()
|
---|
[8267] | 518 | else:
|
---|
| 519 | usage()
|
---|
| 520 | else:
|
---|
| 521 | cgitb.enable()
|
---|
| 522 | process_cgi_request()
|
---|
| 523 |
|
---|
[8257] | 524 |
|
---|
[8267] | 525 | if __name__ == "__main__":
|
---|
| 526 | main()
|
---|