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