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