| 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 |
|
|---|
| 7 | # Hack to make the script directory is also threated as a module search path.
|
|---|
| 8 | import sys
|
|---|
| 9 | import os
|
|---|
| 10 | sys.path.append(os.path.dirname(__file__))
|
|---|
| 11 |
|
|---|
| 12 | import cgi
|
|---|
| 13 | import cgitb
|
|---|
| 14 | import copy
|
|---|
| 15 | import glob
|
|---|
| 16 | import socket
|
|---|
| 17 | import string
|
|---|
| 18 | import subprocess
|
|---|
| 19 | import time
|
|---|
| 20 | import rdnap
|
|---|
| 21 | from pprint import pprint
|
|---|
| 22 | try:
|
|---|
| 23 | import yaml
|
|---|
| 24 | except ImportError, e:
|
|---|
| 25 | print e
|
|---|
| 26 | print "[ERROR] Please install the python-yaml or devel/py-yaml package"
|
|---|
| 27 | exit(1)
|
|---|
| 28 |
|
|---|
| 29 | try:
|
|---|
| 30 | from yaml import CLoader as Loader
|
|---|
| 31 | from yaml import CDumper as Dumper
|
|---|
| 32 | except ImportError:
|
|---|
| 33 | from yaml import Loader, Dumper
|
|---|
| 34 |
|
|---|
| 35 |
|
|---|
| 36 |
|
|---|
| 37 | NODE_DIR = os.path.dirname(__file__) + '/../nodes'
|
|---|
| 38 | __version__ = '$Id: gformat.py 8867 2011-03-02 18:09:48Z rick $'
|
|---|
| 39 |
|
|---|
| 40 |
|
|---|
| 41 | files = [
|
|---|
| 42 | 'authorized_keys',
|
|---|
| 43 | 'dnsmasq.conf',
|
|---|
| 44 | 'rc.conf.local',
|
|---|
| 45 | 'resolv.conf',
|
|---|
| 46 | 'wleiden.yaml'
|
|---|
| 47 | ]
|
|---|
| 48 |
|
|---|
| 49 | # Global variables uses
|
|---|
| 50 | OK = 10
|
|---|
| 51 | DOWN = 20
|
|---|
| 52 | UNKNOWN = 90
|
|---|
| 53 |
|
|---|
| 54 |
|
|---|
| 55 | def get_proxylist():
|
|---|
| 56 | """Get all available proxies proxyX sorting based on X number"""
|
|---|
| 57 | os.chdir(NODE_DIR)
|
|---|
| 58 | proxylist = sorted(glob.glob("proxy*"),
|
|---|
| 59 | key=lambda name: int(''.join([c for c in name if c in string.digits])),
|
|---|
| 60 | cmp=lambda x,y: x - y)
|
|---|
| 61 | return proxylist
|
|---|
| 62 |
|
|---|
| 63 |
|
|---|
| 64 |
|
|---|
| 65 | def valid_addr(addr):
|
|---|
| 66 | """ Show which address is valid in which are not """
|
|---|
| 67 | return str(addr).startswith('172.')
|
|---|
| 68 |
|
|---|
| 69 |
|
|---|
| 70 | def get_nodelist():
|
|---|
| 71 | """ Get all available nodes - sorted """
|
|---|
| 72 | os.chdir(NODE_DIR)
|
|---|
| 73 | nodelist = sorted(glob.glob("CNode*"))
|
|---|
| 74 | return nodelist
|
|---|
| 75 |
|
|---|
| 76 | def get_hostlist():
|
|---|
| 77 | """ Combined hosts and proxy list"""
|
|---|
| 78 | return get_nodelist() + get_proxylist()
|
|---|
| 79 |
|
|---|
| 80 | def angle_between_points(lat1,lat2,long1,long2):
|
|---|
| 81 | """
|
|---|
| 82 | Return Angle in radians between two GPS coordinates
|
|---|
| 83 | See: http://stackoverflow.com/questions/3809179/angle-between-2-gps-coordinates
|
|---|
| 84 | """
|
|---|
| 85 | dy = lat2 - lat1
|
|---|
| 86 | dx = math.cos(math.pi/180*lat1)*(long2 - long1)
|
|---|
| 87 | angle = math.atan2(dy,dx)
|
|---|
| 88 | return angle
|
|---|
| 89 |
|
|---|
| 90 | def angle_to_cd(angle):
|
|---|
| 91 | """ Return Dutch Cardinal Direction estimation in 'one digit' of radian angle """
|
|---|
| 92 |
|
|---|
| 93 | # For easy conversion get positive degree
|
|---|
| 94 | degrees = math.degrees(angle)
|
|---|
| 95 | if degrees < 0:
|
|---|
| 96 | 360 - abs(degrees)
|
|---|
| 97 |
|
|---|
| 98 | # Numbers can be confusing calculate from the 4 main directions
|
|---|
| 99 | p = 22.5
|
|---|
| 100 | if degrees < p:
|
|---|
| 101 | return "n"
|
|---|
| 102 | elif degrees < (90 - p):
|
|---|
| 103 | return "no"
|
|---|
| 104 | elif degrees < (90 + p):
|
|---|
| 105 | return "o"
|
|---|
| 106 | elif degrees < (180 - p):
|
|---|
| 107 | return "zo"
|
|---|
| 108 | elif degrees < (180 + p):
|
|---|
| 109 | return "z"
|
|---|
| 110 | elif degrees < (270 - p):
|
|---|
| 111 | return "zw"
|
|---|
| 112 | elif degrees < (270 + p):
|
|---|
| 113 | return "w"
|
|---|
| 114 | elif degrees < (360 - p):
|
|---|
| 115 | return "nw"
|
|---|
| 116 | else:
|
|---|
| 117 | return "n"
|
|---|
| 118 |
|
|---|
| 119 |
|
|---|
| 120 | def generate_title(nodelist):
|
|---|
| 121 | """ Main overview page """
|
|---|
| 122 | items = {'root' : "." }
|
|---|
| 123 | output = """
|
|---|
| 124 | <html>
|
|---|
| 125 | <head>
|
|---|
| 126 | <title>Wireless leiden Configurator - GFormat</title>
|
|---|
| 127 | <style type="text/css">
|
|---|
| 128 | th {background-color: #999999}
|
|---|
| 129 | tr:nth-child(odd) {background-color: #cccccc}
|
|---|
| 130 | tr:nth-child(even) {background-color: #ffffff}
|
|---|
| 131 | th, td {padding: 0.1em 1em}
|
|---|
| 132 | </style>
|
|---|
| 133 | </head>
|
|---|
| 134 | <body>
|
|---|
| 135 | <center>
|
|---|
| 136 | <form type="GET" action="%(root)s">
|
|---|
| 137 | <input type="hidden" name="action" value="update">
|
|---|
| 138 | <input type="submit" value="Update Configuration Database (SVN)">
|
|---|
| 139 | </form>
|
|---|
| 140 | <table>
|
|---|
| 141 | <caption><h3>Wireless Leiden Configurator</h3></caption>
|
|---|
| 142 | """ % items
|
|---|
| 143 |
|
|---|
| 144 | for node in nodelist:
|
|---|
| 145 | items['node'] = node
|
|---|
| 146 | output += '<tr><td><a href="%(root)s/%(node)s">%(node)s</a></td>' % items
|
|---|
| 147 | for config in files:
|
|---|
| 148 | items['config'] = config
|
|---|
| 149 | output += '<td><a href="%(root)s/%(node)s/%(config)s">%(config)s</a></td>' % items
|
|---|
| 150 | output += "</tr>"
|
|---|
| 151 | output += """
|
|---|
| 152 | </table>
|
|---|
| 153 | <hr />
|
|---|
| 154 | <em>%s</em>
|
|---|
| 155 | </center>
|
|---|
| 156 | </body>
|
|---|
| 157 | </html>
|
|---|
| 158 | """ % __version__
|
|---|
| 159 |
|
|---|
| 160 | return output
|
|---|
| 161 |
|
|---|
| 162 |
|
|---|
| 163 |
|
|---|
| 164 | def generate_node(node):
|
|---|
| 165 | """ Print overview of all files available for node """
|
|---|
| 166 | return "\n".join(files)
|
|---|
| 167 |
|
|---|
| 168 |
|
|---|
| 169 |
|
|---|
| 170 | def generate_header(ctag="#"):
|
|---|
| 171 | return """\
|
|---|
| 172 | %(ctag)s
|
|---|
| 173 | %(ctag)s DO NOT EDIT - Automatically generated by 'gformat'
|
|---|
| 174 | %(ctag)s Generated at %(date)s by %(host)s
|
|---|
| 175 | %(ctag)s
|
|---|
| 176 | """ % { 'ctag' : ctag, 'date' : time.ctime(), 'host' : socket.gethostname() }
|
|---|
| 177 |
|
|---|
| 178 |
|
|---|
| 179 |
|
|---|
| 180 | def parseaddr(s):
|
|---|
| 181 | """ Process IPv4 CIDR notation addr to a (binary) number """
|
|---|
| 182 | f = s.split('.')
|
|---|
| 183 | return (long(f[0]) << 24L) + \
|
|---|
| 184 | (long(f[1]) << 16L) + \
|
|---|
| 185 | (long(f[2]) << 8L) + \
|
|---|
| 186 | long(f[3])
|
|---|
| 187 |
|
|---|
| 188 |
|
|---|
| 189 |
|
|---|
| 190 | def showaddr(a):
|
|---|
| 191 | """ Display IPv4 addr in (dotted) CIDR notation """
|
|---|
| 192 | return "%d.%d.%d.%d" % ((a >> 24) & 0xff, (a >> 16) & 0xff, (a >> 8) & 0xff, a & 0xff)
|
|---|
| 193 |
|
|---|
| 194 |
|
|---|
| 195 | def is_member(ip, mask, canidate):
|
|---|
| 196 | """ Return True if canidate is part of ip/mask block"""
|
|---|
| 197 | ip_addr = gformat.parseaddr(ip)
|
|---|
| 198 | ip_canidate = gformat.parseaddr(canidate)
|
|---|
| 199 | mask = int(mask)
|
|---|
| 200 | ip_addr = ip_addr & ~((1 << (32 - mask)) - 1)
|
|---|
| 201 | ip_canidate = ip_canidate & ~((1 << (32 - mask)) - 1)
|
|---|
| 202 | return ip_addr == ip_canidate
|
|---|
| 203 |
|
|---|
| 204 |
|
|---|
| 205 |
|
|---|
| 206 |
|
|---|
| 207 | def netmask2subnet(netmask):
|
|---|
| 208 | """ Given a 'netmask' return corresponding CIDR """
|
|---|
| 209 | return showaddr(0xffffffff & (0xffffffff << (32 - int(netmask))))
|
|---|
| 210 |
|
|---|
| 211 |
|
|---|
| 212 |
|
|---|
| 213 | def generate_dnsmasq_conf(datadump):
|
|---|
| 214 | """ Generate configuration file '/usr/local/etc/dnsmasq.conf' """
|
|---|
| 215 | output = generate_header()
|
|---|
| 216 | output += """\
|
|---|
| 217 | # DHCP server options
|
|---|
| 218 | dhcp-authoritative
|
|---|
| 219 | dhcp-fqdn
|
|---|
| 220 | domain=dhcp.%(nodename_lower)s.%(domain)s
|
|---|
| 221 | domain-needed
|
|---|
| 222 | expand-hosts
|
|---|
| 223 |
|
|---|
| 224 | # Low memory footprint
|
|---|
| 225 | cache-size=10000
|
|---|
| 226 | \n""" % datadump
|
|---|
| 227 |
|
|---|
| 228 | for iface_key in datadump['iface_keys']:
|
|---|
| 229 | if not datadump[iface_key].has_key('comment'):
|
|---|
| 230 | datadump[iface_key]['comment'] = None
|
|---|
| 231 | output += "## %(interface)s - %(desc)s - %(comment)s\n" % datadump[iface_key]
|
|---|
| 232 |
|
|---|
| 233 | try:
|
|---|
| 234 | (dhcp_start, dhcp_stop) = datadump[iface_key]['dhcp'].split('-')
|
|---|
| 235 | (ip, netmask) = datadump[iface_key]['ip'].split('/')
|
|---|
| 236 | datadump[iface_key]['subnet'] = netmask2subnet(netmask)
|
|---|
| 237 | except (AttributeError, ValueError):
|
|---|
| 238 | output += "# not autoritive\n\n"
|
|---|
| 239 | continue
|
|---|
| 240 |
|
|---|
| 241 | dhcp_part = ".".join(ip.split('.')[0:3])
|
|---|
| 242 | datadump[iface_key]['dhcp_start'] = dhcp_part + "." + dhcp_start
|
|---|
| 243 | datadump[iface_key]['dhcp_stop'] = dhcp_part + "." + dhcp_stop
|
|---|
| 244 | output += "dhcp-range=%(interface)s,%(dhcp_start)s,%(dhcp_stop)s,%(subnet)s,24h\n\n" % datadump[iface_key]
|
|---|
| 245 |
|
|---|
| 246 | return output
|
|---|
| 247 |
|
|---|
| 248 |
|
|---|
| 249 |
|
|---|
| 250 | def generate_rc_conf_local(datadump):
|
|---|
| 251 | """ Generate configuration file '/etc/rc.conf.local' """
|
|---|
| 252 | output = generate_header("#");
|
|---|
| 253 | output += """\
|
|---|
| 254 | hostname='%(nodetype)s%(nodename)s.%(domain)s'
|
|---|
| 255 | location='%(location)s'
|
|---|
| 256 | """ % datadump
|
|---|
| 257 |
|
|---|
| 258 | # TProxy configuration
|
|---|
| 259 | output += "\n"
|
|---|
| 260 | try:
|
|---|
| 261 | if datadump['tproxy']:
|
|---|
| 262 | output += """\
|
|---|
| 263 | tproxy_enable='YES'
|
|---|
| 264 | tproxy_range='%(tproxy)s'
|
|---|
| 265 | """ % datadump
|
|---|
| 266 | except KeyError:
|
|---|
| 267 | output += "tproxy_enable='NO'\n"
|
|---|
| 268 |
|
|---|
| 269 | output += '\n'
|
|---|
| 270 | # lo0 configuration:
|
|---|
| 271 | # - 172.32.255.1/32 is the proxy.wleiden.net deflector
|
|---|
| 272 | # - masterip is special as it needs to be assigned to at
|
|---|
| 273 | # least one interface, so if not used assign to lo0
|
|---|
| 274 | addrs_list = { 'lo0' : ["127.0.0.1/8", "172.31.255.1/32"] }
|
|---|
| 275 | iface_map = {'lo0' : 'lo0'}
|
|---|
| 276 |
|
|---|
| 277 | masterip_used = False
|
|---|
| 278 | for iface_key in datadump['iface_keys']:
|
|---|
| 279 | if datadump[iface_key]['ip'].startswith(datadump['masterip']):
|
|---|
| 280 | masterip_used = True
|
|---|
| 281 | break
|
|---|
| 282 | if not masterip_used:
|
|---|
| 283 | addrs_list['lo0'].append(datadump['masterip'] + "/32")
|
|---|
| 284 |
|
|---|
| 285 | wlan_count = 0
|
|---|
| 286 | for iface_key in datadump['iface_keys']:
|
|---|
| 287 | ifacedump = datadump[iface_key]
|
|---|
| 288 | interface = ifacedump['interface']
|
|---|
| 289 | # By default no special interface mapping
|
|---|
| 290 | iface_map[interface] = interface
|
|---|
| 291 |
|
|---|
| 292 | # Add interface IP to list
|
|---|
| 293 | if addrs_list.has_key(interface):
|
|---|
| 294 | addrs_list[interface].append(ifacedump['ip'])
|
|---|
| 295 | else:
|
|---|
| 296 | addrs_list[interface] = [ifacedump['ip']]
|
|---|
| 297 |
|
|---|
| 298 | # Alias only needs IP assignment for now, this might change if we
|
|---|
| 299 | # are going to use virtual accesspoints
|
|---|
| 300 | if "alias" in iface_key:
|
|---|
| 301 | continue
|
|---|
| 302 |
|
|---|
| 303 | # XXX: Might want to deduct type directly from interface name
|
|---|
| 304 | if ifacedump['type'] in ['11a', '11b', '11g', 'wireless']:
|
|---|
| 305 | # Create wlanX interface
|
|---|
| 306 | ifacedump['wlanif'] ="wlan%i" % wlan_count
|
|---|
| 307 | iface_map[interface] = ifacedump['wlanif']
|
|---|
| 308 | wlan_count += 1
|
|---|
| 309 |
|
|---|
| 310 | # Default to station (client) mode
|
|---|
| 311 | ifacedump['wlanmode'] = "sta"
|
|---|
| 312 | if ifacedump['mode'] in ['master', 'master-wds']:
|
|---|
| 313 | ifacedump['wlanmode'] = "ap"
|
|---|
| 314 | # Default to 802.11b mode
|
|---|
| 315 | ifacedump['mode'] = '11b'
|
|---|
| 316 | if ifacedump['type'] in ['11a', '11b' '11g']:
|
|---|
| 317 | ifacedump['mode'] = ifacedump['type']
|
|---|
| 318 |
|
|---|
| 319 | if not ifacedump.has_key('channel'):
|
|---|
| 320 | if ifacedump['type'] == '11a':
|
|---|
| 321 | ifacedump['channel'] = 36
|
|---|
| 322 | else:
|
|---|
| 323 | ifacedump['channel'] = 1
|
|---|
| 324 |
|
|---|
| 325 | # Allow special hacks at the back like wds and stuff
|
|---|
| 326 | if not ifacedump.has_key('extra'):
|
|---|
| 327 | ifacedump['extra'] = 'regdomain ETSI country NL'
|
|---|
| 328 |
|
|---|
| 329 | output += "wlans_%(interface)s='%(wlanif)s'\n" % ifacedump
|
|---|
| 330 | output += ("create_args_%(wlanif)s='wlanmode %(wlanmode)s mode " +\
|
|---|
| 331 | "%(mode)s ssid %(ssid)s %(extra)s channel %(channel)s'\n") % ifacedump
|
|---|
| 332 |
|
|---|
| 333 | elif ifacedump['type'] in ['ethernet', 'eth']:
|
|---|
| 334 | # No special config needed besides IP
|
|---|
| 335 | pass
|
|---|
| 336 | else:
|
|---|
| 337 | assert False, "Unknown type " + ifacedump['type']
|
|---|
| 338 |
|
|---|
| 339 | # Print IP address which needs to be assigned over here
|
|---|
| 340 | output += "\n"
|
|---|
| 341 | for iface,addrs in sorted(addrs_list.iteritems()):
|
|---|
| 342 | output += "ipv4_addrs_%s='%s'\n" % (iface_map[iface], " ".join(addrs))
|
|---|
| 343 |
|
|---|
| 344 | return output
|
|---|
| 345 |
|
|---|
| 346 |
|
|---|
| 347 |
|
|---|
| 348 | def get_yaml(item):
|
|---|
| 349 | """ Get configuration yaml for 'item'"""
|
|---|
| 350 | gfile = NODE_DIR + '/%s/wleiden.yaml' % item
|
|---|
| 351 |
|
|---|
| 352 | f = open(gfile, 'r')
|
|---|
| 353 | datadump = yaml.load(f,Loader=Loader)
|
|---|
| 354 | f.close()
|
|---|
| 355 |
|
|---|
| 356 | return datadump
|
|---|
| 357 |
|
|---|
| 358 | def store_yaml(datadump):
|
|---|
| 359 | """ Store configuration yaml for 'item'"""
|
|---|
| 360 | gfile = NODE_DIR + '/%s/wleiden.yaml' % item
|
|---|
| 361 |
|
|---|
| 362 | f = open(gfile, 'w')
|
|---|
| 363 | f.write(generate_wleiden_yaml(datadump))
|
|---|
| 364 | f.close()
|
|---|
| 365 |
|
|---|
| 366 |
|
|---|
| 367 |
|
|---|
| 368 | def get_all_configs():
|
|---|
| 369 | """ Get dict with key 'host' with all configs present """
|
|---|
| 370 | configs = dict()
|
|---|
| 371 | for host in get_hostlist():
|
|---|
| 372 | datadump = get_yaml(host)
|
|---|
| 373 | configs[host] = datadump
|
|---|
| 374 | return configs
|
|---|
| 375 |
|
|---|
| 376 |
|
|---|
| 377 | def get_interface_keys(config):
|
|---|
| 378 | """ Quick hack to get all interface keys, later stage convert this to a iterator """
|
|---|
| 379 | return [elem for elem in config.keys() if (elem.startswith('iface_') and not "lo0" in elem)]
|
|---|
| 380 |
|
|---|
| 381 |
|
|---|
| 382 | def get_used_ips(configs):
|
|---|
| 383 | """ Return array of all IPs used in config files"""
|
|---|
| 384 | ip_list = []
|
|---|
| 385 | for config in configs:
|
|---|
| 386 | ip_list.append(config['masterip'])
|
|---|
| 387 | for iface_key in get_interface_keys(config):
|
|---|
| 388 | l = config[iface_key]['ip']
|
|---|
| 389 | addr, mask = l.split('/')
|
|---|
| 390 | # Special case do not process
|
|---|
| 391 | if valid_addr(addr):
|
|---|
| 392 | ip_list.append(addr)
|
|---|
| 393 | else:
|
|---|
| 394 | print "## IP '%s' in '%s' not valid" % (addr, config['nodename'])
|
|---|
| 395 | return sorted(ip_list)
|
|---|
| 396 |
|
|---|
| 397 |
|
|---|
| 398 |
|
|---|
| 399 | def write_yaml(item, datadump):
|
|---|
| 400 | """ Write configuration yaml for 'item'"""
|
|---|
| 401 | gfile = NODE_DIR + '/%s/wleiden.yaml' % item
|
|---|
| 402 |
|
|---|
| 403 | f = open(gfile, 'w')
|
|---|
| 404 | f.write(format_wleiden_yaml(datadump))
|
|---|
| 405 | f.close()
|
|---|
| 406 |
|
|---|
| 407 |
|
|---|
| 408 |
|
|---|
| 409 | def generate_resolv_conf(datadump):
|
|---|
| 410 | """ Generate configuration file '/etc/resolv.conf' """
|
|---|
| 411 | output = generate_header("#");
|
|---|
| 412 | output += """\
|
|---|
| 413 | search wleiden.net
|
|---|
| 414 | # Try local (cache) first
|
|---|
| 415 | nameserver 127.0.0.1
|
|---|
| 416 |
|
|---|
| 417 | # Proxies are recursive nameservers
|
|---|
| 418 | # needs to be in resolv.conf for dnsmasq as well
|
|---|
| 419 | """ % datadump
|
|---|
| 420 |
|
|---|
| 421 | for proxy in get_proxylist():
|
|---|
| 422 | proxy_ip = get_yaml(proxy)['masterip']
|
|---|
| 423 | output += "nameserver %-15s # %s\n" % (proxy_ip, proxy)
|
|---|
| 424 | return output
|
|---|
| 425 |
|
|---|
| 426 |
|
|---|
| 427 |
|
|---|
| 428 | def format_yaml_value(value):
|
|---|
| 429 | """ Get yaml value in right syntax for outputting """
|
|---|
| 430 | if isinstance(value,str):
|
|---|
| 431 | output = "'%s'" % value
|
|---|
| 432 | else:
|
|---|
| 433 | output = value
|
|---|
| 434 | return output
|
|---|
| 435 |
|
|---|
| 436 |
|
|---|
| 437 |
|
|---|
| 438 | def format_wleiden_yaml(datadump):
|
|---|
| 439 | """ Special formatting to ensure it is editable"""
|
|---|
| 440 | output = "# Genesis config yaml style\n"
|
|---|
| 441 | output += "# vim:ts=2:et:sw=2:ai\n"
|
|---|
| 442 | output += "#\n"
|
|---|
| 443 | iface_keys = [elem for elem in datadump.keys() if elem.startswith('iface_')]
|
|---|
| 444 | for key in sorted(set(datadump.keys()) - set(iface_keys)):
|
|---|
| 445 | output += "%-10s: %s\n" % (key, format_yaml_value(datadump[key]))
|
|---|
| 446 |
|
|---|
| 447 | output += "\n\n"
|
|---|
| 448 |
|
|---|
| 449 | key_order = [ 'comment', 'interface', 'ip', 'desc', 'sdesc', 'mode', 'type',
|
|---|
| 450 | 'extra_type', 'channel', 'ssid', 'dhcp' ]
|
|---|
| 451 |
|
|---|
| 452 | for iface_key in sorted(iface_keys):
|
|---|
| 453 | output += "%s:\n" % iface_key
|
|---|
| 454 | for key in key_order + list(sorted(set(datadump[iface_key].keys()) - set(key_order))):
|
|---|
| 455 | if datadump[iface_key].has_key(key):
|
|---|
| 456 | output += " %-11s: %s\n" % (key, format_yaml_value(datadump[iface_key][key]))
|
|---|
| 457 | output += "\n\n"
|
|---|
| 458 |
|
|---|
| 459 | return output
|
|---|
| 460 |
|
|---|
| 461 |
|
|---|
| 462 |
|
|---|
| 463 | def generate_wleiden_yaml(datadump):
|
|---|
| 464 | """ Generate (petty) version of wleiden.yaml"""
|
|---|
| 465 | output = generate_header("#")
|
|---|
| 466 | output += format_wleiden_yaml(datadump)
|
|---|
| 467 | return output
|
|---|
| 468 |
|
|---|
| 469 |
|
|---|
| 470 | def generate_yaml(datadump):
|
|---|
| 471 | return generate_config(datadump['nodename'], "wleiden.yaml", datadump)
|
|---|
| 472 |
|
|---|
| 473 |
|
|---|
| 474 |
|
|---|
| 475 | def generate_config(node, config, datadump=None):
|
|---|
| 476 | """ Print configuration file 'config' of 'node' """
|
|---|
| 477 | output = ""
|
|---|
| 478 | try:
|
|---|
| 479 | # Load config file
|
|---|
| 480 | if datadump == None:
|
|---|
| 481 | datadump = get_yaml(node)
|
|---|
| 482 |
|
|---|
| 483 | # Preformat certain needed variables for formatting and push those into special object
|
|---|
| 484 | datadump_extra = copy.deepcopy(datadump)
|
|---|
| 485 | if not datadump_extra.has_key('domain'):
|
|---|
| 486 | datadump_extra['domain'] = 'wleiden.net'
|
|---|
| 487 | datadump_extra['nodename_lower'] = datadump_extra['nodename'].lower()
|
|---|
| 488 | datadump_extra['iface_keys'] = sorted([elem for elem in datadump.keys() if elem.startswith('iface_')])
|
|---|
| 489 |
|
|---|
| 490 | if config == 'wleiden.yaml':
|
|---|
| 491 | output += generate_wleiden_yaml(datadump)
|
|---|
| 492 | elif config == 'authorized_keys':
|
|---|
| 493 | f = open("global_keys", 'r')
|
|---|
| 494 | output += f.read()
|
|---|
| 495 | f.close()
|
|---|
| 496 | elif config == 'dnsmasq.conf':
|
|---|
| 497 | output += generate_dnsmasq_conf(datadump_extra)
|
|---|
| 498 | elif config == 'rc.conf.local':
|
|---|
| 499 | output += generate_rc_conf_local(datadump_extra)
|
|---|
| 500 | elif config == 'resolv.conf':
|
|---|
| 501 | output += generate_resolv_conf(datadump_extra)
|
|---|
| 502 | else:
|
|---|
| 503 | assert False, "Config not found!"
|
|---|
| 504 | except IOError, e:
|
|---|
| 505 | output += "[ERROR] Config file not found"
|
|---|
| 506 | return output
|
|---|
| 507 |
|
|---|
| 508 |
|
|---|
| 509 |
|
|---|
| 510 | def process_cgi_request():
|
|---|
| 511 | """ When calling from CGI """
|
|---|
| 512 | # Update repository if requested
|
|---|
| 513 | form = cgi.FieldStorage()
|
|---|
| 514 | if form.getvalue("action") == "update":
|
|---|
| 515 | print "Refresh: 5; url=."
|
|---|
| 516 | print "Content-type:text/plain\r\n\r\n",
|
|---|
| 517 | print "[INFO] Updating subverion, please wait..."
|
|---|
| 518 | print subprocess.Popen(['svn', 'up', NODE_DIR], stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0],
|
|---|
| 519 | print "[INFO] All done, redirecting in 5 seconds"
|
|---|
| 520 | sys.exit(0)
|
|---|
| 521 |
|
|---|
| 522 |
|
|---|
| 523 | uri = os.environ['PATH_INFO'].strip('/').split('/')
|
|---|
| 524 | output = ""
|
|---|
| 525 | if not uri[0]:
|
|---|
| 526 | output += "Content-type:text/html\r\n\r\n"
|
|---|
| 527 | output += generate_title(get_hostlist())
|
|---|
| 528 | elif len(uri) == 1:
|
|---|
| 529 | output += "Content-type:text/plain\r\n\r\n"
|
|---|
| 530 | output += generate_node(uri[0])
|
|---|
| 531 | elif len(uri) == 2:
|
|---|
| 532 | output += "Content-type:text/plain\r\n\r\n"
|
|---|
| 533 | output += generate_config(uri[0], uri[1])
|
|---|
| 534 | else:
|
|---|
| 535 | assert False, "Invalid option"
|
|---|
| 536 | print output
|
|---|
| 537 |
|
|---|
| 538 | def get_fqdn(datadump):
|
|---|
| 539 | # Proxy naming convention is special
|
|---|
| 540 | if datadump['nodetype'] == 'Proxy':
|
|---|
| 541 | fqdn = datadump['nodename']
|
|---|
| 542 | else:
|
|---|
| 543 | # By default the full name is listed and also a shortname CNAME for easy use.
|
|---|
| 544 | fqdn = datadump['nodetype'] + datadump['nodename']
|
|---|
| 545 | return(fqdn)
|
|---|
| 546 |
|
|---|
| 547 |
|
|---|
| 548 |
|
|---|
| 549 | def make_dns():
|
|---|
| 550 | items = dict()
|
|---|
| 551 |
|
|---|
| 552 | # hostname is key, IP is value
|
|---|
| 553 | wleiden_zone = dict()
|
|---|
| 554 | wleiden_cname = dict()
|
|---|
| 555 |
|
|---|
| 556 | pool = dict()
|
|---|
| 557 | for node in get_hostlist():
|
|---|
| 558 | datadump = get_yaml(node)
|
|---|
| 559 |
|
|---|
| 560 | # Proxy naming convention is special
|
|---|
| 561 | fqdn = get_fqdn(datadump)
|
|---|
| 562 | if datadump['nodetype'] == 'CNode':
|
|---|
| 563 | wleiden_cname[datadump['nodename']] = fqdn
|
|---|
| 564 |
|
|---|
| 565 | wleiden_zone[fqdn] = datadump['masterip']
|
|---|
| 566 |
|
|---|
| 567 | # Hacking to get proper DHCP IPs and hostnames
|
|---|
| 568 | for iface_key in get_interface_keys(datadump):
|
|---|
| 569 | iface_name = datadump[iface_key]['interface'].replace(':',"-alias-")
|
|---|
| 570 | (ip, netmask) = datadump[iface_key]['ip'].split('/')
|
|---|
| 571 | try:
|
|---|
| 572 | (dhcp_start, dhcp_stop) = datadump[iface_key]['dhcp'].split('-')
|
|---|
| 573 | datadump[iface_key]['subnet'] = netmask2subnet(netmask)
|
|---|
| 574 | dhcp_part = ".".join(ip.split('.')[0:3])
|
|---|
| 575 | if ip != datadump['masterip']:
|
|---|
| 576 | wleiden_zone["dhcp-gateway-%s.%s" % (iface_name, fqdn)] = ip
|
|---|
| 577 | for i in range(int(dhcp_start), int(dhcp_stop) + 1):
|
|---|
| 578 | wleiden_zone["dhcp-%s-%s.%s" % (i, iface_name, fqdn)] = "%s.%s" % (dhcp_part, i)
|
|---|
| 579 | except (AttributeError, ValueError):
|
|---|
| 580 | # First push it into a pool, to indentify the counter-part later on
|
|---|
| 581 | addr = parseaddr(ip)
|
|---|
| 582 | netmask = int(netmask)
|
|---|
| 583 | addr = addr & ~((1 << (32 - netmask)) - 1)
|
|---|
| 584 | if pool.has_key(addr):
|
|---|
| 585 | pool[addr] += [(iface_name, fqdn, ip)]
|
|---|
| 586 | else:
|
|---|
| 587 | pool[addr] = [(iface_name, fqdn, ip)]
|
|---|
| 588 | continue
|
|---|
| 589 |
|
|---|
| 590 | # Automatic naming convention of interlinks namely 2 + remote.lower()
|
|---|
| 591 | for (key,value) in pool.iteritems():
|
|---|
| 592 | if len(value) == 1:
|
|---|
| 593 | (iface_name, fqdn, ip) = value[0]
|
|---|
| 594 | wleiden_zone["2unused-%s.%s" % (iface_name, fqdn)] = ip
|
|---|
| 595 | elif len(value) == 2:
|
|---|
| 596 | (a_iface_name, a_fqdn, a_ip) = value[0]
|
|---|
| 597 | (b_iface_name, b_fqdn, b_ip) = value[1]
|
|---|
| 598 | wleiden_zone["2%s.%s" % (b_fqdn,a_fqdn)] = a_ip
|
|---|
| 599 | wleiden_zone["2%s.%s" % (a_fqdn,b_fqdn)] = b_ip
|
|---|
| 600 | else:
|
|---|
| 601 | pool_members = [k[1] for k in value]
|
|---|
| 602 | for item in value:
|
|---|
| 603 | (iface_name, fqdn, ip) = item
|
|---|
| 604 | pool_name = "2pool-" + showaddr(key).replace('.','-') + "-" + "-".join(sorted(list(set(pool_members) - set([fqdn]))))
|
|---|
| 605 | wleiden_zone["%s.%s" % (pool_name, fqdn)] = ip
|
|---|
| 606 |
|
|---|
| 607 | # Include static DNS entries
|
|---|
| 608 | # XXX: Should they override the autogenerated results?
|
|---|
| 609 | # XXX: Convert input to yaml more useable.
|
|---|
| 610 | # Format:
|
|---|
| 611 | ##; this is a comment
|
|---|
| 612 | ## roomburgh=CNodeRoomburgh1
|
|---|
| 613 | ## apkerk1.CNodeVosko=172.17.176.8 ;this as well
|
|---|
| 614 | dns = yaml.load(open('../dns/staticDNS.yaml','r'))
|
|---|
| 615 | for comment, block in dns.iteritems():
|
|---|
| 616 | for k,v in block.iteritems():
|
|---|
| 617 | if valid_addr(v):
|
|---|
| 618 | wleiden_zone[k] = v
|
|---|
| 619 | else:
|
|---|
| 620 | wleiden_cname[k] = v
|
|---|
| 621 |
|
|---|
| 622 | details = dict()
|
|---|
| 623 | # 24 updates a day allowed
|
|---|
| 624 | details['serial'] = time.strftime('%Y%m%d%H')
|
|---|
| 625 |
|
|---|
| 626 | dns_header = '''
|
|---|
| 627 | $TTL 3h
|
|---|
| 628 | %(zone)s. SOA sunny.wleiden.net. beheer.lijst.wirelessleiden.nl. ( %(serial)s 1d 12h 1w 3h )
|
|---|
| 629 | ; Serial, Refresh, Retry, Expire, Neg. cache TTL
|
|---|
| 630 |
|
|---|
| 631 | NS sunny.wleiden.net.
|
|---|
| 632 | \n'''
|
|---|
| 633 |
|
|---|
| 634 |
|
|---|
| 635 | if not os.path.isdir('dns'):
|
|---|
| 636 | os.makedirs('dns')
|
|---|
| 637 | details['zone'] = 'wleiden.net'
|
|---|
| 638 | f = open("dns/db." + details['zone'], "w")
|
|---|
| 639 | f.write(dns_header % details)
|
|---|
| 640 |
|
|---|
| 641 | for host,ip in wleiden_zone.iteritems():
|
|---|
| 642 | if valid_addr(ip):
|
|---|
| 643 | f.write("%s.wleiden.net. IN A %s \n" % (host.lower(), ip))
|
|---|
| 644 | for source,dest in wleiden_cname.iteritems():
|
|---|
| 645 | f.write("%s.wleiden.net. IN CNAME %s.wleiden.net.\n" % (source.lower(), dest.lower()))
|
|---|
| 646 | f.close()
|
|---|
| 647 |
|
|---|
| 648 | # Create whole bunch of specific sub arpa zones. To keep it compliant
|
|---|
| 649 | for s in range(16,32):
|
|---|
| 650 | details['zone'] = '%i.172.in-addr.arpa' % s
|
|---|
| 651 | f = open("dns/db." + details['zone'], "w")
|
|---|
| 652 | f.write(dns_header % details)
|
|---|
| 653 |
|
|---|
| 654 | #XXX: Not effient, fix to proper data structure and do checks at other
|
|---|
| 655 | # stages
|
|---|
| 656 | for host,ip in wleiden_zone.iteritems():
|
|---|
| 657 | if valid_addr(ip):
|
|---|
| 658 | if int(ip.split('.')[1]) == s:
|
|---|
| 659 | rev_ip = '.'.join(reversed(ip.split('.')))
|
|---|
| 660 | f.write("%s.in-addr.arpa. IN PTR %s.wleiden.net.\n" % (rev_ip.lower(), host.lower()))
|
|---|
| 661 | f.close()
|
|---|
| 662 |
|
|---|
| 663 |
|
|---|
| 664 | def usage():
|
|---|
| 665 | print """Usage: %s <standalone [port] |test [test arguments]|static|dns>
|
|---|
| 666 | Examples:
|
|---|
| 667 | \tdns = Generate BIND compliant zone files in dns.
|
|---|
| 668 | \tstandalone = Run configurator webserver [default port=8000]
|
|---|
| 669 | \tstatic = Generate all config files and store on disk
|
|---|
| 670 | \t with format ./static/%%NODE%%/%%FILE%%
|
|---|
| 671 | \ttest CNodeRick dnsmasq.conf = Receive output of CGI script
|
|---|
| 672 | \t for arguments CNodeRick/dnsmasq.conf
|
|---|
| 673 | """
|
|---|
| 674 | exit(0)
|
|---|
| 675 |
|
|---|
| 676 |
|
|---|
| 677 |
|
|---|
| 678 | def main():
|
|---|
| 679 | """Hard working sub"""
|
|---|
| 680 | # Allow easy hacking using the CLI
|
|---|
| 681 | if not os.environ.has_key('PATH_INFO'):
|
|---|
| 682 | if len(sys.argv) < 2:
|
|---|
| 683 | usage()
|
|---|
| 684 |
|
|---|
| 685 | if sys.argv[1] == "standalone":
|
|---|
| 686 | import SocketServer
|
|---|
| 687 | import CGIHTTPServer
|
|---|
| 688 | # CGI does not go backward, little hack to get ourself in the right working directory.
|
|---|
| 689 | os.chdir(os.path.dirname(__file__) + '/..')
|
|---|
| 690 | try:
|
|---|
| 691 | PORT = int(sys.argv[2])
|
|---|
| 692 | except (IndexError,ValueError):
|
|---|
| 693 | PORT = 8000
|
|---|
| 694 |
|
|---|
| 695 | class MyCGIHTTPRequestHandler(CGIHTTPServer.CGIHTTPRequestHandler):
|
|---|
| 696 | """ Serve this CGI from the root of the webserver """
|
|---|
| 697 | def is_cgi(self):
|
|---|
| 698 | if "favicon" in self.path:
|
|---|
| 699 | return False
|
|---|
| 700 |
|
|---|
| 701 | self.cgi_info = (__file__, self.path)
|
|---|
| 702 | self.path = ''
|
|---|
| 703 | return True
|
|---|
| 704 | handler = MyCGIHTTPRequestHandler
|
|---|
| 705 | httpd = SocketServer.TCPServer(("", PORT), handler)
|
|---|
| 706 | httpd.server_name = 'localhost'
|
|---|
| 707 | httpd.server_port = PORT
|
|---|
| 708 |
|
|---|
| 709 | print "serving at port", PORT
|
|---|
| 710 | try:
|
|---|
| 711 | httpd.serve_forever()
|
|---|
| 712 | except KeyboardInterrupt:
|
|---|
| 713 | httpd.shutdown()
|
|---|
| 714 | elif sys.argv[1] == "test":
|
|---|
| 715 | os.environ['PATH_INFO'] = "/".join(sys.argv[2:])
|
|---|
| 716 | os.environ['SCRIPT_NAME'] = __file__
|
|---|
| 717 | process_cgi_request()
|
|---|
| 718 | elif sys.argv[1] == "static":
|
|---|
| 719 | items = dict()
|
|---|
| 720 | for node in get_hostlist():
|
|---|
| 721 | items['node'] = node
|
|---|
| 722 | items['wdir'] = "./static/%(node)s" % items
|
|---|
| 723 | if not os.path.isdir(items['wdir']):
|
|---|
| 724 | os.makedirs(items['wdir'])
|
|---|
| 725 | datadump = get_yaml(node)
|
|---|
| 726 | for config in files:
|
|---|
| 727 | items['config'] = config
|
|---|
| 728 | print "## Generating %(node)s %(config)s" % items
|
|---|
| 729 | f = open("%(wdir)s/%(config)s" % items, "w")
|
|---|
| 730 | f.write(generate_config(node, config, datadump))
|
|---|
| 731 | f.close()
|
|---|
| 732 | elif sys.argv[1] == "dns":
|
|---|
| 733 | make_dns()
|
|---|
| 734 | elif sys.argv[1] == "cleanup":
|
|---|
| 735 | # First generate all datadumps
|
|---|
| 736 | datadumps = dict()
|
|---|
| 737 | for host in get_hostlist():
|
|---|
| 738 | datadump = get_yaml(host)
|
|---|
| 739 | datadumps[get_fqdn(datadump)] = datadump
|
|---|
| 740 |
|
|---|
| 741 | datadump['latitude'], datadump['longitude'] = rdnap.rd2etrs(datadump['rdnap_x'], datadump['rdnap_y'])
|
|---|
| 742 | write_yaml(host, datadump)
|
|---|
| 743 | else:
|
|---|
| 744 | usage()
|
|---|
| 745 | else:
|
|---|
| 746 | cgitb.enable()
|
|---|
| 747 | process_cgi_request()
|
|---|
| 748 |
|
|---|
| 749 |
|
|---|
| 750 | if __name__ == "__main__":
|
|---|
| 751 | main()
|
|---|