[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
|
---|
| 10 | sys.path.append(os.path.dirname(__file__))
|
---|
| 11 |
|
---|
[8242] | 12 | import cgi
|
---|
[8267] | 13 | import cgitb
|
---|
| 14 | import copy
|
---|
[8242] | 15 | import glob
|
---|
| 16 | import socket
|
---|
| 17 | import string
|
---|
| 18 | import subprocess
|
---|
| 19 | import time
|
---|
[8622] | 20 | import rdnap
|
---|
[8584] | 21 | from pprint import pprint
|
---|
[8575] | 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)
|
---|
[8588] | 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 |
|
---|
[8575] | 35 |
|
---|
[8242] | 36 |
|
---|
[8622] | 37 | NODE_DIR = os.getcwd()
|
---|
[8242] | 38 | __version__ = '$Id: gformat.py 8636 2010-11-02 19:51:07Z richardvm $'
|
---|
| 39 |
|
---|
[8267] | 40 |
|
---|
[8242] | 41 | files = [
|
---|
| 42 | 'authorized_keys',
|
---|
| 43 | 'dnsmasq.conf',
|
---|
| 44 | 'rc.conf.local',
|
---|
| 45 | 'resolv.conf',
|
---|
| 46 | 'wleiden.yaml'
|
---|
| 47 | ]
|
---|
| 48 |
|
---|
[8319] | 49 | # Global variables uses
|
---|
[8323] | 50 | OK = 10
|
---|
| 51 | DOWN = 20
|
---|
| 52 | UNKNOWN = 90
|
---|
[8257] | 53 |
|
---|
| 54 |
|
---|
[8267] | 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 |
|
---|
[8321] | 65 | def valid_addr(addr):
|
---|
| 66 | """ Show which address is valid in which are not """
|
---|
| 67 | return str(addr).startswith('172.')
|
---|
| 68 |
|
---|
| 69 |
|
---|
[8267] | 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 |
|
---|
[8296] | 76 | def get_hostlist():
|
---|
| 77 | """ Combined hosts and proxy list"""
|
---|
| 78 | return get_nodelist() + get_proxylist()
|
---|
[8267] | 79 |
|
---|
[8588] | 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
|
---|
[8267] | 89 |
|
---|
[8588] | 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 |
|
---|
[8267] | 120 | def generate_title(nodelist):
|
---|
[8257] | 121 | """ Main overview page """
|
---|
[8259] | 122 | items = {'root' : "." }
|
---|
[8267] | 123 | output = """
|
---|
[8257] | 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>
|
---|
[8259] | 136 | <form type="GET" action="%(root)s">
|
---|
[8257] | 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
|
---|
[8242] | 143 |
|
---|
[8296] | 144 | for node in nodelist:
|
---|
[8257] | 145 | items['node'] = node
|
---|
[8267] | 146 | output += '<tr><td><a href="%(root)s/%(node)s">%(node)s</a></td>' % items
|
---|
[8257] | 147 | for config in files:
|
---|
| 148 | items['config'] = config
|
---|
[8267] | 149 | output += '<td><a href="%(root)s/%(node)s/%(config)s">%(config)s</a></td>' % items
|
---|
| 150 | output += "</tr>"
|
---|
| 151 | output += """
|
---|
[8257] | 152 | </table>
|
---|
| 153 | <hr />
|
---|
| 154 | <em>%s</em>
|
---|
| 155 | </center>
|
---|
| 156 | </body>
|
---|
| 157 | </html>
|
---|
| 158 | """ % __version__
|
---|
[8242] | 159 |
|
---|
[8267] | 160 | return output
|
---|
[8257] | 161 |
|
---|
| 162 |
|
---|
[8267] | 163 |
|
---|
| 164 | def generate_node(node):
|
---|
[8257] | 165 | """ Print overview of all files available for node """
|
---|
[8267] | 166 | return "\n".join(files)
|
---|
[8242] | 167 |
|
---|
[8257] | 168 |
|
---|
| 169 |
|
---|
[8242] | 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 |
|
---|
[8257] | 178 |
|
---|
| 179 |
|
---|
[8242] | 180 | def parseaddr(s):
|
---|
[8257] | 181 | """ Process IPv4 CIDR notation addr to a (binary) number """
|
---|
[8242] | 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 |
|
---|
[8257] | 188 |
|
---|
| 189 |
|
---|
[8242] | 190 | def showaddr(a):
|
---|
[8257] | 191 | """ Display IPv4 addr in (dotted) CIDR notation """
|
---|
[8242] | 192 | return "%d.%d.%d.%d" % ((a >> 24) & 0xff, (a >> 16) & 0xff, (a >> 8) & 0xff, a & 0xff)
|
---|
| 193 |
|
---|
[8257] | 194 |
|
---|
[8584] | 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 |
|
---|
[8257] | 204 |
|
---|
[8584] | 205 |
|
---|
| 206 |
|
---|
[8242] | 207 | def netmask2subnet(netmask):
|
---|
[8257] | 208 | """ Given a 'netmask' return corresponding CIDR """
|
---|
[8242] | 209 | return showaddr(0xffffffff & (0xffffffff << (32 - int(netmask))))
|
---|
| 210 |
|
---|
[8257] | 211 |
|
---|
| 212 |
|
---|
[8242] | 213 | def generate_dnsmasq_conf(datadump):
|
---|
[8257] | 214 | """ Generate configuration file '/usr/local/etc/dnsmasq.conf' """
|
---|
[8242] | 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']:
|
---|
[8262] | 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]
|
---|
[8242] | 232 |
|
---|
| 233 | try:
|
---|
[8257] | 234 | (dhcp_start, dhcp_stop) = datadump[iface_key]['dhcp'].split('-')
|
---|
[8242] | 235 | (ip, netmask) = datadump[iface_key]['ip'].split('/')
|
---|
| 236 | datadump[iface_key]['subnet'] = netmask2subnet(netmask)
|
---|
[8262] | 237 | except (AttributeError, ValueError):
|
---|
[8242] | 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 |
|
---|
[8257] | 248 |
|
---|
| 249 |
|
---|
[8242] | 250 | def generate_rc_conf_local(datadump):
|
---|
[8257] | 251 | """ Generate configuration file '/etc/rc.conf.local' """
|
---|
[8242] | 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 |
|
---|
[8297] | 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 |
|
---|
[8242] | 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"
|
---|
[8274] | 312 | if ifacedump['mode'] in ['master', 'master-wds']:
|
---|
[8242] | 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 " +\
|
---|
[8274] | 331 | "%(mode)s ssid %(ssid)s %(extra)s channel %(channel)s'\n") % ifacedump
|
---|
[8242] | 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 |
|
---|
[8257] | 346 |
|
---|
| 347 |
|
---|
[8242] | 348 | def get_yaml(item):
|
---|
[8257] | 349 | """ Get configuration yaml for 'item'"""
|
---|
[8258] | 350 | gfile = NODE_DIR + '/%s/wleiden.yaml' % item
|
---|
[8242] | 351 |
|
---|
| 352 | f = open(gfile, 'r')
|
---|
[8588] | 353 | datadump = yaml.load(f,Loader=Loader)
|
---|
[8242] | 354 | f.close()
|
---|
| 355 |
|
---|
| 356 | return datadump
|
---|
| 357 |
|
---|
[8588] | 358 | def store_yaml(datadump):
|
---|
| 359 | """ Store configuration yaml for 'item'"""
|
---|
| 360 | gfile = NODE_DIR + '/%s/wleiden.yaml' % item
|
---|
[8257] | 361 |
|
---|
[8588] | 362 | f = open(gfile, 'w')
|
---|
| 363 | f.write(generate_wleiden_yaml(datadump))
|
---|
| 364 | f.close()
|
---|
[8257] | 365 |
|
---|
[8588] | 366 |
|
---|
| 367 |
|
---|
[8317] | 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 |
|
---|
[8319] | 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)]
|
---|
[8317] | 380 |
|
---|
[8319] | 381 |
|
---|
[8317] | 382 | def get_used_ips(configs):
|
---|
| 383 | """ Return array of all IPs used in config files"""
|
---|
| 384 | ip_list = []
|
---|
[8319] | 385 | for config in configs:
|
---|
[8317] | 386 | ip_list.append(config['masterip'])
|
---|
[8319] | 387 | for iface_key in get_interface_keys(config):
|
---|
[8317] | 388 | l = config[iface_key]['ip']
|
---|
| 389 | addr, mask = l.split('/')
|
---|
| 390 | # Special case do not process
|
---|
[8332] | 391 | if valid_addr(addr):
|
---|
| 392 | ip_list.append(addr)
|
---|
| 393 | else:
|
---|
| 394 | print "## IP '%s' in '%s' not valid" % (addr, config['nodename'])
|
---|
[8317] | 395 | return sorted(ip_list)
|
---|
| 396 |
|
---|
| 397 |
|
---|
| 398 |
|
---|
[8267] | 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 |
|
---|
[8242] | 409 | def generate_resolv_conf(datadump):
|
---|
[8257] | 410 | """ Generate configuration file '/etc/resolv.conf' """
|
---|
[8242] | 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 |
|
---|
[8267] | 421 | for proxy in get_proxylist():
|
---|
[8242] | 422 | proxy_ip = get_yaml(proxy)['masterip']
|
---|
| 423 | output += "nameserver %-15s # %s\n" % (proxy_ip, proxy)
|
---|
| 424 | return output
|
---|
| 425 |
|
---|
| 426 |
|
---|
[8257] | 427 |
|
---|
[8267] | 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):
|
---|
[8242] | 439 | """ Special formatting to ensure it is editable"""
|
---|
[8267] | 440 | output = "# Genesis config yaml style\n"
|
---|
[8262] | 441 | output += "# vim:ts=2:et:sw=2:ai\n"
|
---|
[8242] | 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)):
|
---|
[8267] | 445 | output += "%-10s: %s\n" % (key, format_yaml_value(datadump[key]))
|
---|
[8242] | 446 |
|
---|
| 447 | output += "\n\n"
|
---|
| 448 |
|
---|
[8272] | 449 | key_order = [ 'comment', 'interface', 'ip', 'desc', 'sdesc', 'mode', 'type',
|
---|
| 450 | 'extra_type', 'channel', 'ssid', 'dhcp' ]
|
---|
| 451 |
|
---|
[8242] | 452 | for iface_key in sorted(iface_keys):
|
---|
| 453 | output += "%s:\n" % iface_key
|
---|
[8272] | 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]))
|
---|
[8242] | 457 | output += "\n\n"
|
---|
| 458 |
|
---|
| 459 | return output
|
---|
| 460 |
|
---|
| 461 |
|
---|
[8257] | 462 |
|
---|
[8267] | 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 |
|
---|
[8588] | 470 | def generate_yaml(datadump):
|
---|
| 471 | return generate_config(datadump['nodename'], "wleiden.yaml", datadump)
|
---|
| 472 |
|
---|
[8267] | 473 |
|
---|
[8588] | 474 |
|
---|
[8298] | 475 | def generate_config(node, config, datadump=None):
|
---|
[8257] | 476 | """ Print configuration file 'config' of 'node' """
|
---|
[8267] | 477 | output = ""
|
---|
[8242] | 478 | try:
|
---|
| 479 | # Load config file
|
---|
[8298] | 480 | if datadump == None:
|
---|
| 481 | datadump = get_yaml(node)
|
---|
[8242] | 482 |
|
---|
[8267] | 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 |
|
---|
[8242] | 490 | if config == 'wleiden.yaml':
|
---|
[8267] | 491 | output += generate_wleiden_yaml(datadump)
|
---|
| 492 | elif config == 'authorized_keys':
|
---|
[8242] | 493 | f = open("global_keys", 'r')
|
---|
[8267] | 494 | output += f.read()
|
---|
[8242] | 495 | f.close()
|
---|
| 496 | elif config == 'dnsmasq.conf':
|
---|
[8267] | 497 | output += generate_dnsmasq_conf(datadump_extra)
|
---|
[8242] | 498 | elif config == 'rc.conf.local':
|
---|
[8267] | 499 | output += generate_rc_conf_local(datadump_extra)
|
---|
[8242] | 500 | elif config == 'resolv.conf':
|
---|
[8267] | 501 | output += generate_resolv_conf(datadump_extra)
|
---|
[8242] | 502 | else:
|
---|
| 503 | assert False, "Config not found!"
|
---|
| 504 | except IOError, e:
|
---|
[8267] | 505 | output += "[ERROR] Config file not found"
|
---|
| 506 | return output
|
---|
[8242] | 507 |
|
---|
| 508 |
|
---|
[8257] | 509 |
|
---|
[8258] | 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":
|
---|
[8259] | 515 | print "Refresh: 5; url=."
|
---|
[8258] | 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('/')
|
---|
[8267] | 524 | output = ""
|
---|
[8258] | 525 | if not uri[0]:
|
---|
[8267] | 526 | output += "Content-type:text/html\r\n\r\n"
|
---|
[8296] | 527 | output += generate_title(get_hostlist())
|
---|
[8258] | 528 | elif len(uri) == 1:
|
---|
[8267] | 529 | output += "Content-type:text/plain\r\n\r\n"
|
---|
| 530 | output += generate_node(uri[0])
|
---|
[8258] | 531 | elif len(uri) == 2:
|
---|
[8267] | 532 | output += "Content-type:text/plain\r\n\r\n"
|
---|
| 533 | output += generate_config(uri[0], uri[1])
|
---|
[8258] | 534 | else:
|
---|
| 535 | assert False, "Invalid option"
|
---|
[8267] | 536 | print output
|
---|
[8242] | 537 |
|
---|
[8588] | 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 |
|
---|
[8259] | 548 |
|
---|
[8588] | 549 | def make_dns():
|
---|
| 550 | items = dict()
|
---|
[8598] | 551 |
|
---|
[8588] | 552 | # hostname is key, IP is value
|
---|
| 553 | wleiden_zone = dict()
|
---|
| 554 | wleiden_cname = dict()
|
---|
[8598] | 555 |
|
---|
[8588] | 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 |
|
---|
[8598] | 567 | # Hacking to get proper DHCP IPs and hostnames
|
---|
[8588] | 568 | for iface_key in get_interface_keys(datadump):
|
---|
[8598] | 569 | iface_name = datadump[iface_key]['interface'].replace(':',"-alias-")
|
---|
[8588] | 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 |
|
---|
[8598] | 590 | # Automatic naming convention of interlinks namely 2 + remote.lower()
|
---|
[8588] | 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
|
---|
[8598] | 604 | pool_name = "2pool-" + showaddr(key).replace('.','-') + "-" + "-".join(sorted(list(set(pool_members) - set([fqdn]))))
|
---|
[8588] | 605 | wleiden_zone["%s.%s" % (pool_name, fqdn)] = ip
|
---|
[8598] | 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
|
---|
[8622] | 614 | dns = yaml.load(open('../dns/staticDNS.yaml','r'))
|
---|
| 615 | for comment, block in dns.iteritems():
|
---|
| 616 | for k,v in block.iteritems():
|
---|
[8598] | 617 | if valid_addr(v):
|
---|
| 618 | wleiden_zone[k] = v
|
---|
| 619 | else:
|
---|
| 620 | wleiden_cname[k] = v
|
---|
[8588] | 621 |
|
---|
[8598] | 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 |
|
---|
[8588] | 634 |
|
---|
[8598] | 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 |
|
---|
[8588] | 641 | for host,ip in wleiden_zone.iteritems():
|
---|
[8598] | 642 | if valid_addr(ip):
|
---|
[8636] | 643 | f.write("%s.wleiden.net. IN A %s \n" % (host.lower(), ip))
|
---|
[8588] | 644 | for source,dest in wleiden_cname.iteritems():
|
---|
[8636] | 645 | f.write("%s.wleiden.net. IN CNAME %s.wleiden.net.\n" % (source.lower(), dest.lower()))
|
---|
[8588] | 646 | f.close()
|
---|
[8598] | 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)
|
---|
[8588] | 653 |
|
---|
[8598] | 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('.')))
|
---|
[8636] | 660 | f.write("%s.in-addr.arpa. IN PTR %s.wleiden.net.\n" % (rev_ip.lower(), host.lower()))
|
---|
[8598] | 661 | f.close()
|
---|
[8588] | 662 |
|
---|
[8598] | 663 |
|
---|
[8259] | 664 | def usage():
|
---|
[8598] | 665 | print """Usage: %s <standalone [port] |test [test arguments]|static|dns>
|
---|
[8259] | 666 | Examples:
|
---|
[8598] | 667 | \tdns = Generate BIND compliant zone files in dns.
|
---|
[8259] | 668 | \tstandalone = Run configurator webserver [default port=8000]
|
---|
[8296] | 669 | \tstatic = Generate all config files and store on disk
|
---|
| 670 | \t with format ./static/%%NODE%%/%%FILE%%
|
---|
[8259] | 671 | \ttest CNodeRick dnsmasq.conf = Receive output of CGI script
|
---|
| 672 | \t for arguments CNodeRick/dnsmasq.conf
|
---|
| 673 | """
|
---|
| 674 | exit(0)
|
---|
| 675 |
|
---|
| 676 |
|
---|
| 677 |
|
---|
[8267] | 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 | try:
|
---|
| 689 | PORT = int(sys.argv[2])
|
---|
| 690 | except (IndexError,ValueError):
|
---|
| 691 | PORT = 8000
|
---|
| 692 |
|
---|
| 693 | class MyCGIHTTPRequestHandler(CGIHTTPServer.CGIHTTPRequestHandler):
|
---|
| 694 | """ Serve this CGI from the root of the webserver """
|
---|
| 695 | def is_cgi(self):
|
---|
| 696 | if "favicon" in self.path:
|
---|
| 697 | return False
|
---|
| 698 |
|
---|
| 699 | self.cgi_info = (__file__, self.path)
|
---|
| 700 | self.path = ''
|
---|
| 701 | return True
|
---|
| 702 | handler = MyCGIHTTPRequestHandler
|
---|
| 703 | httpd = SocketServer.TCPServer(("", PORT), handler)
|
---|
| 704 | httpd.server_name = 'localhost'
|
---|
| 705 | httpd.server_port = PORT
|
---|
| 706 |
|
---|
| 707 | print "serving at port", PORT
|
---|
| 708 | httpd.serve_forever()
|
---|
| 709 | elif sys.argv[1] == "test":
|
---|
| 710 | os.environ['PATH_INFO'] = "/".join(sys.argv[2:])
|
---|
| 711 | os.environ['SCRIPT_NAME'] = __file__
|
---|
| 712 | process_cgi_request()
|
---|
[8296] | 713 | elif sys.argv[1] == "static":
|
---|
| 714 | items = dict()
|
---|
| 715 | for node in get_hostlist():
|
---|
| 716 | items['node'] = node
|
---|
| 717 | items['wdir'] = "./static/%(node)s" % items
|
---|
| 718 | if not os.path.isdir(items['wdir']):
|
---|
| 719 | os.makedirs(items['wdir'])
|
---|
[8298] | 720 | datadump = get_yaml(node)
|
---|
[8296] | 721 | for config in files:
|
---|
| 722 | items['config'] = config
|
---|
| 723 | print "## Generating %(node)s %(config)s" % items
|
---|
| 724 | f = open("%(wdir)s/%(config)s" % items, "w")
|
---|
[8298] | 725 | f.write(generate_config(node, config, datadump))
|
---|
[8296] | 726 | f.close()
|
---|
[8584] | 727 | elif sys.argv[1] == "dns":
|
---|
[8588] | 728 | make_dns()
|
---|
| 729 | elif sys.argv[1] == "cleanup":
|
---|
| 730 | # First generate all datadumps
|
---|
| 731 | datadumps = dict()
|
---|
| 732 | for host in get_hostlist():
|
---|
| 733 | datadump = get_yaml(host)
|
---|
| 734 | datadumps[get_fqdn(datadump)] = datadump
|
---|
| 735 |
|
---|
[8622] | 736 | datadump['latitude'], datadump['longitude'] = rdnap.rd2etrs(datadump['rdnap_x'], datadump['rdnap_y'])
|
---|
[8588] | 737 | write_yaml(host, datadump)
|
---|
| 738 | else:
|
---|
| 739 | usage()
|
---|
| 740 | else:
|
---|
| 741 | cgitb.enable()
|
---|
| 742 | process_cgi_request()
|
---|
| 743 |
|
---|
| 744 |
|
---|
| 745 | if __name__ == "__main__":
|
---|
| 746 | main()
|
---|