[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
|
---|
[10378] | 33 | import make_network_kml
|
---|
[8584] | 34 | from pprint import pprint
|
---|
[10281] | 35 | from collections import defaultdict
|
---|
[8575] | 36 | try:
|
---|
| 37 | import yaml
|
---|
| 38 | except ImportError, e:
|
---|
| 39 | print e
|
---|
| 40 | print "[ERROR] Please install the python-yaml or devel/py-yaml package"
|
---|
| 41 | exit(1)
|
---|
[8588] | 42 |
|
---|
| 43 | try:
|
---|
| 44 | from yaml import CLoader as Loader
|
---|
| 45 | from yaml import CDumper as Dumper
|
---|
| 46 | except ImportError:
|
---|
| 47 | from yaml import Loader, Dumper
|
---|
| 48 |
|
---|
[10584] | 49 | from jinja2 import Environment, Template
|
---|
| 50 | def yesorno(value):
|
---|
| 51 | return "YES" if bool(value) else "NO"
|
---|
| 52 | env = Environment()
|
---|
| 53 | env.filters['yesorno'] = yesorno
|
---|
| 54 | def render_template(datadump, template):
|
---|
| 55 | result = env.from_string(template).render(datadump)
|
---|
| 56 | # Make it look pretty to the naked eye, as jinja templates are not so
|
---|
| 57 | # friendly when it comes to whitespace formatting
|
---|
| 58 | ## Remove extra whitespace at end of line lstrip() style.
|
---|
| 59 | result = re.sub(r'\n[\ ]+','\n', result)
|
---|
| 60 | ## Include only a single newline between an definition and a comment
|
---|
| 61 | result = re.sub(r'(["\'])\n+([a-z]|\n#\n)',r'\1\n\2', result)
|
---|
| 62 | ## Remove extra newlines after single comment
|
---|
| 63 | result = re.sub(r'(#\n)\n+([a-z])',r'\1\2', result)
|
---|
| 64 | return result
|
---|
[10110] | 65 |
|
---|
[9697] | 66 | import logging
|
---|
| 67 | logging.basicConfig(format='# %(levelname)s: %(message)s' )
|
---|
| 68 | logger = logging.getLogger()
|
---|
| 69 | logger.setLevel(logging.DEBUG)
|
---|
[8242] | 70 |
|
---|
[9283] | 71 |
|
---|
[8948] | 72 | if os.environ.has_key('CONFIGROOT'):
|
---|
| 73 | NODE_DIR = os.environ['CONFIGROOT']
|
---|
| 74 | else:
|
---|
[9283] | 75 | NODE_DIR = os.path.abspath(os.path.dirname(__file__)) + '/../nodes'
|
---|
[8242] | 76 | __version__ = '$Id: gformat.py 10597 2012-04-26 18:14:50Z rick $'
|
---|
| 77 |
|
---|
[8267] | 78 |
|
---|
[9283] | 79 | files = [
|
---|
[8242] | 80 | 'authorized_keys',
|
---|
| 81 | 'dnsmasq.conf',
|
---|
[10410] | 82 | 'dhcpd.conf',
|
---|
[8242] | 83 | 'rc.conf.local',
|
---|
| 84 | 'resolv.conf',
|
---|
[10069] | 85 | 'motd',
|
---|
[10054] | 86 | 'wleiden.yaml',
|
---|
[8242] | 87 | ]
|
---|
| 88 |
|
---|
[8319] | 89 | # Global variables uses
|
---|
[8323] | 90 | OK = 10
|
---|
| 91 | DOWN = 20
|
---|
| 92 | UNKNOWN = 90
|
---|
[8257] | 93 |
|
---|
[10391] | 94 | def get_yaml(item):
|
---|
| 95 | """ Get configuration yaml for 'item'"""
|
---|
| 96 | gfile = os.path.join(NODE_DIR,item,'wleiden.yaml')
|
---|
[8257] | 97 |
|
---|
[10461] | 98 | # Use some boring defaults
|
---|
[10584] | 99 | datadump = { 'service_proxy_normal' : False, 'service_proxy_ileiden' : False, 'service_accesspoint' : True }
|
---|
[10391] | 100 | f = open(gfile, 'r')
|
---|
[10461] | 101 | datadump.update(yaml.load(f,Loader=Loader))
|
---|
[10391] | 102 | f.close()
|
---|
| 103 |
|
---|
| 104 | # Preformat certain needed variables for formatting and push those into special object
|
---|
| 105 | datadump['autogen_iface_keys'] = get_interface_keys(datadump)
|
---|
| 106 |
|
---|
| 107 | wlan_count=0
|
---|
| 108 | for key in datadump['autogen_iface_keys']:
|
---|
| 109 | if datadump[key]['type'] in ['11a', '11b', '11g', 'wireless']:
|
---|
| 110 | datadump[key]['autogen_ifname'] = 'wlan%i' % wlan_count
|
---|
| 111 | wlan_count += 1
|
---|
| 112 | else:
|
---|
| 113 | datadump[key]['autogen_ifname'] = datadump[key]['interface'].split(':')[0]
|
---|
| 114 |
|
---|
[10459] | 115 | dhcp_interfaces = [datadump[key]['autogen_ifname'] for key in datadump['autogen_iface_keys'] if datadump[key]['dhcp']]
|
---|
| 116 | datadump['autogen_dhcp_interfaces'] = ','.join(dhcp_interfaces)
|
---|
[10391] | 117 | datadump['autogen_item'] = item
|
---|
| 118 |
|
---|
| 119 | datadump['autogen_realname'] = get_realname(datadump)
|
---|
| 120 | datadump['autogen_domain'] = datadump['domain'] if datadump.has_key('domain') else 'wleiden.net.'
|
---|
| 121 | datadump['autogen_fqdn'] = datadump['autogen_realname'] + '.' + datadump['autogen_domain']
|
---|
| 122 | return datadump
|
---|
| 123 |
|
---|
| 124 |
|
---|
| 125 | def store_yaml(datadump, header=False):
|
---|
| 126 | """ Store configuration yaml for 'item'"""
|
---|
| 127 | item = datadump['autogen_item']
|
---|
| 128 | gfile = os.path.join(NODE_DIR,item,'wleiden.yaml')
|
---|
| 129 |
|
---|
| 130 | f = open(gfile, 'w')
|
---|
| 131 | f.write(generate_wleiden_yaml(datadump, header))
|
---|
| 132 | f.close()
|
---|
| 133 |
|
---|
| 134 |
|
---|
| 135 |
|
---|
[10281] | 136 | def make_relations():
|
---|
[10270] | 137 | """ Process _ALL_ yaml files to get connection relations """
|
---|
| 138 | errors = ""
|
---|
[10281] | 139 | poel = defaultdict(list)
|
---|
[10270] | 140 | for host in get_hostlist():
|
---|
| 141 | try:
|
---|
| 142 | datadump = get_yaml(host)
|
---|
| 143 | for iface_key in datadump['autogen_iface_keys']:
|
---|
| 144 | l = datadump[iface_key]['ip']
|
---|
| 145 | addr, mask = l.split('/')
|
---|
| 146 |
|
---|
| 147 | # Not parsing of these folks please
|
---|
| 148 | if not valid_addr(addr):
|
---|
| 149 | continue
|
---|
| 150 |
|
---|
| 151 | addr = parseaddr(addr)
|
---|
| 152 | mask = int(mask)
|
---|
[10281] | 153 | network = addr & ~((1 << (32 - mask)) - 1)
|
---|
| 154 | poel[network] += [(host,datadump[iface_key])]
|
---|
[10270] | 155 | except (KeyError, ValueError), e:
|
---|
| 156 | errors += "[FOUT] in '%s' interface '%s'" % (host,iface_key)
|
---|
| 157 | errors += e
|
---|
| 158 | continue
|
---|
| 159 | return (poel, errors)
|
---|
| 160 |
|
---|
| 161 |
|
---|
[8267] | 162 | def get_proxylist():
|
---|
| 163 | """Get all available proxies proxyX sorting based on X number"""
|
---|
[10041] | 164 | proxylist = sorted([os.path.basename(x) for x in glob.glob("%s/proxy*" % NODE_DIR)],
|
---|
[8267] | 165 | key=lambda name: int(''.join([c for c in name if c in string.digits])),
|
---|
[10364] | 166 | cmp=lambda x,y: x - y) + sorted([os.path.basename(x) for x in glob.glob("%s/Proxy*" % NODE_DIR)])
|
---|
[8267] | 167 | return proxylist
|
---|
| 168 |
|
---|
[10192] | 169 | def get_hybridlist():
|
---|
[10461] | 170 | """Get all available hybrid nodes/proxies"""
|
---|
| 171 | hybridlist = sorted([os.path.basename(x) for x in glob.glob("%s/Hybrid*" % NODE_DIR)])
|
---|
[10192] | 172 | return hybridlist
|
---|
[8267] | 173 |
|
---|
| 174 |
|
---|
[8321] | 175 | def valid_addr(addr):
|
---|
| 176 | """ Show which address is valid in which are not """
|
---|
| 177 | return str(addr).startswith('172.')
|
---|
| 178 |
|
---|
| 179 |
|
---|
[8267] | 180 | def get_nodelist():
|
---|
| 181 | """ Get all available nodes - sorted """
|
---|
[10041] | 182 | nodelist = sorted([os.path.basename(x) for x in glob.glob("%s/CNode*" % NODE_DIR)])
|
---|
[8267] | 183 | return nodelist
|
---|
| 184 |
|
---|
[8296] | 185 | def get_hostlist():
|
---|
| 186 | """ Combined hosts and proxy list"""
|
---|
[10192] | 187 | return get_nodelist() + get_proxylist() + get_hybridlist()
|
---|
[8267] | 188 |
|
---|
[8588] | 189 | def angle_between_points(lat1,lat2,long1,long2):
|
---|
[9283] | 190 | """
|
---|
[8588] | 191 | Return Angle in radians between two GPS coordinates
|
---|
| 192 | See: http://stackoverflow.com/questions/3809179/angle-between-2-gps-coordinates
|
---|
| 193 | """
|
---|
| 194 | dy = lat2 - lat1
|
---|
| 195 | dx = math.cos(math.pi/180*lat1)*(long2 - long1)
|
---|
| 196 | angle = math.atan2(dy,dx)
|
---|
| 197 | return angle
|
---|
[8267] | 198 |
|
---|
[8588] | 199 | def angle_to_cd(angle):
|
---|
| 200 | """ Return Dutch Cardinal Direction estimation in 'one digit' of radian angle """
|
---|
| 201 |
|
---|
| 202 | # For easy conversion get positive degree
|
---|
| 203 | degrees = math.degrees(angle)
|
---|
| 204 | if degrees < 0:
|
---|
| 205 | 360 - abs(degrees)
|
---|
| 206 |
|
---|
| 207 | # Numbers can be confusing calculate from the 4 main directions
|
---|
| 208 | p = 22.5
|
---|
| 209 | if degrees < p:
|
---|
| 210 | return "n"
|
---|
[9283] | 211 | elif degrees < (90 - p):
|
---|
[8588] | 212 | return "no"
|
---|
[9283] | 213 | elif degrees < (90 + p):
|
---|
[8588] | 214 | return "o"
|
---|
[9283] | 215 | elif degrees < (180 - p):
|
---|
[8588] | 216 | return "zo"
|
---|
[9283] | 217 | elif degrees < (180 + p):
|
---|
[8588] | 218 | return "z"
|
---|
[9283] | 219 | elif degrees < (270 - p):
|
---|
[8588] | 220 | return "zw"
|
---|
[9283] | 221 | elif degrees < (270 + p):
|
---|
[8588] | 222 | return "w"
|
---|
[9283] | 223 | elif degrees < (360 - p):
|
---|
[8588] | 224 | return "nw"
|
---|
| 225 | else:
|
---|
| 226 | return "n"
|
---|
| 227 |
|
---|
| 228 |
|
---|
[8267] | 229 | def generate_title(nodelist):
|
---|
[8257] | 230 | """ Main overview page """
|
---|
[9283] | 231 | items = {'root' : "." }
|
---|
[8267] | 232 | output = """
|
---|
[8257] | 233 | <html>
|
---|
| 234 | <head>
|
---|
| 235 | <title>Wireless leiden Configurator - GFormat</title>
|
---|
| 236 | <style type="text/css">
|
---|
| 237 | th {background-color: #999999}
|
---|
| 238 | tr:nth-child(odd) {background-color: #cccccc}
|
---|
| 239 | tr:nth-child(even) {background-color: #ffffff}
|
---|
| 240 | th, td {padding: 0.1em 1em}
|
---|
| 241 | </style>
|
---|
| 242 | </head>
|
---|
| 243 | <body>
|
---|
| 244 | <center>
|
---|
[8259] | 245 | <form type="GET" action="%(root)s">
|
---|
[8257] | 246 | <input type="hidden" name="action" value="update">
|
---|
| 247 | <input type="submit" value="Update Configuration Database (SVN)">
|
---|
| 248 | </form>
|
---|
| 249 | <table>
|
---|
| 250 | <caption><h3>Wireless Leiden Configurator</h3></caption>
|
---|
| 251 | """ % items
|
---|
[8242] | 252 |
|
---|
[8296] | 253 | for node in nodelist:
|
---|
[8257] | 254 | items['node'] = node
|
---|
[8267] | 255 | output += '<tr><td><a href="%(root)s/%(node)s">%(node)s</a></td>' % items
|
---|
[8257] | 256 | for config in files:
|
---|
| 257 | items['config'] = config
|
---|
[8267] | 258 | output += '<td><a href="%(root)s/%(node)s/%(config)s">%(config)s</a></td>' % items
|
---|
| 259 | output += "</tr>"
|
---|
| 260 | output += """
|
---|
[8257] | 261 | </table>
|
---|
| 262 | <hr />
|
---|
| 263 | <em>%s</em>
|
---|
| 264 | </center>
|
---|
| 265 | </body>
|
---|
| 266 | </html>
|
---|
| 267 | """ % __version__
|
---|
[8242] | 268 |
|
---|
[8267] | 269 | return output
|
---|
[8257] | 270 |
|
---|
| 271 |
|
---|
[8267] | 272 |
|
---|
| 273 | def generate_node(node):
|
---|
[8257] | 274 | """ Print overview of all files available for node """
|
---|
[8267] | 275 | return "\n".join(files)
|
---|
[8242] | 276 |
|
---|
[10270] | 277 | def generate_node_overview(host):
|
---|
| 278 | """ Print overview of all files available for node """
|
---|
| 279 | datadump = get_yaml(host)
|
---|
| 280 | params = { 'host' : host }
|
---|
| 281 | output = "<em><a href='..'>Back to overview</a></em><hr />"
|
---|
| 282 | output += "<h2>Available files:</h2><ul>"
|
---|
| 283 | for cf in files:
|
---|
| 284 | params['cf'] = cf
|
---|
| 285 | output += '<li><a href="%(host)s/%(cf)s">%(cf)s</a></li>\n' % params
|
---|
| 286 | output += "</ul>"
|
---|
[8257] | 287 |
|
---|
[10270] | 288 | # Generate and connection listing
|
---|
| 289 | output += "<h2>Connected To:</h2><ul>"
|
---|
[10281] | 290 | (poel, errors) = make_relations()
|
---|
| 291 | for network, hosts in poel.iteritems():
|
---|
| 292 | if host in [x[0] for x in hosts]:
|
---|
| 293 | if len(hosts) == 1:
|
---|
| 294 | # Single not connected interface
|
---|
| 295 | continue
|
---|
| 296 | for remote,ifacedump in hosts:
|
---|
| 297 | if remote == host:
|
---|
| 298 | # This side of the interface
|
---|
| 299 | continue
|
---|
| 300 | params = { 'remote': remote, 'remote_ip' : ifacedump['ip'] }
|
---|
| 301 | output += '<li><a href="%(remote)s">%(remote)s</a> -- %(remote_ip)s</li>\n' % params
|
---|
[10270] | 302 | output += "</ul>"
|
---|
[10281] | 303 | output += "<h2>MOTD details:</h2><pre>" + generate_motd(datadump) + "</pre>"
|
---|
[8257] | 304 |
|
---|
[10270] | 305 | output += "<hr /><em><a href='..'>Back to overview</a></em>"
|
---|
| 306 | return output
|
---|
| 307 |
|
---|
| 308 |
|
---|
[8242] | 309 | def generate_header(ctag="#"):
|
---|
| 310 | return """\
|
---|
[9283] | 311 | %(ctag)s
|
---|
[8242] | 312 | %(ctag)s DO NOT EDIT - Automatically generated by 'gformat'
|
---|
| 313 | %(ctag)s Generated at %(date)s by %(host)s
|
---|
[9283] | 314 | %(ctag)s
|
---|
[8242] | 315 | """ % { 'ctag' : ctag, 'date' : time.ctime(), 'host' : socket.gethostname() }
|
---|
| 316 |
|
---|
[8257] | 317 |
|
---|
| 318 |
|
---|
[8242] | 319 | def parseaddr(s):
|
---|
[8257] | 320 | """ Process IPv4 CIDR notation addr to a (binary) number """
|
---|
[8242] | 321 | f = s.split('.')
|
---|
| 322 | return (long(f[0]) << 24L) + \
|
---|
| 323 | (long(f[1]) << 16L) + \
|
---|
| 324 | (long(f[2]) << 8L) + \
|
---|
| 325 | long(f[3])
|
---|
| 326 |
|
---|
[8257] | 327 |
|
---|
| 328 |
|
---|
[8242] | 329 | def showaddr(a):
|
---|
[8257] | 330 | """ Display IPv4 addr in (dotted) CIDR notation """
|
---|
[8242] | 331 | return "%d.%d.%d.%d" % ((a >> 24) & 0xff, (a >> 16) & 0xff, (a >> 8) & 0xff, a & 0xff)
|
---|
| 332 |
|
---|
[8257] | 333 |
|
---|
[8584] | 334 | def is_member(ip, mask, canidate):
|
---|
| 335 | """ Return True if canidate is part of ip/mask block"""
|
---|
| 336 | ip_addr = gformat.parseaddr(ip)
|
---|
| 337 | ip_canidate = gformat.parseaddr(canidate)
|
---|
| 338 | mask = int(mask)
|
---|
| 339 | ip_addr = ip_addr & ~((1 << (32 - mask)) - 1)
|
---|
| 340 | ip_canidate = ip_canidate & ~((1 << (32 - mask)) - 1)
|
---|
| 341 | return ip_addr == ip_canidate
|
---|
[8257] | 342 |
|
---|
[8584] | 343 |
|
---|
| 344 |
|
---|
[10410] | 345 | def cidr2netmask(netmask):
|
---|
[8257] | 346 | """ Given a 'netmask' return corresponding CIDR """
|
---|
[8242] | 347 | return showaddr(0xffffffff & (0xffffffff << (32 - int(netmask))))
|
---|
| 348 |
|
---|
[10410] | 349 | def get_network(addr, mask):
|
---|
| 350 | return showaddr(parseaddr(addr) & ~((1 << (32 - int(mask))) - 1))
|
---|
[8257] | 351 |
|
---|
| 352 |
|
---|
[10410] | 353 | def generate_dhcpd_conf(datadump):
|
---|
| 354 | """ Generate config file '/usr/local/etc/dhcpd.conf """
|
---|
| 355 | output = generate_header()
|
---|
| 356 | output += Template("""\
|
---|
| 357 | # option definitions common to all supported networks...
|
---|
| 358 | option domain-name "dhcp.{{ autogen_fqdn }}";
|
---|
| 359 |
|
---|
| 360 | default-lease-time 600;
|
---|
| 361 | max-lease-time 7200;
|
---|
| 362 |
|
---|
| 363 | # Use this to enble / disable dynamic dns updates globally.
|
---|
| 364 | #ddns-update-style none;
|
---|
| 365 |
|
---|
| 366 | # If this DHCP server is the official DHCP server for the local
|
---|
| 367 | # network, the authoritative directive should be uncommented.
|
---|
| 368 | authoritative;
|
---|
| 369 |
|
---|
| 370 | # Use this to send dhcp log messages to a different log file (you also
|
---|
| 371 | # have to hack syslog.conf to complete the redirection).
|
---|
| 372 | log-facility local7;
|
---|
| 373 |
|
---|
| 374 | #
|
---|
| 375 | # Interface definitions
|
---|
| 376 | #
|
---|
| 377 | \n""").render(datadump)
|
---|
| 378 |
|
---|
| 379 | for iface_key in datadump['autogen_iface_keys']:
|
---|
| 380 | if not datadump[iface_key].has_key('comment'):
|
---|
[10455] | 381 | datadump[iface_key]['comment'] = None
|
---|
[10410] | 382 | output += "## %(interface)s - %(desc)s - %(comment)s\n" % datadump[iface_key]
|
---|
| 383 |
|
---|
| 384 | (addr, mask) = datadump[iface_key]['ip'].split('/')
|
---|
| 385 | datadump[iface_key]['addr'] = addr
|
---|
| 386 | datadump[iface_key]['netmask'] = cidr2netmask(mask)
|
---|
| 387 | datadump[iface_key]['subnet'] = get_network(addr, mask)
|
---|
| 388 | try:
|
---|
| 389 | (dhcp_start, dhcp_stop) = datadump[iface_key]['dhcp'].split('-')
|
---|
| 390 | except (AttributeError, ValueError):
|
---|
| 391 | output += "subnet %(subnet)s netmask %(netmask)s {\n ### not autoritive\n}\n\n" % datadump[iface_key]
|
---|
| 392 | continue
|
---|
| 393 |
|
---|
| 394 | dhcp_part = ".".join(addr.split('.')[0:3])
|
---|
| 395 | datadump[iface_key]['dhcp_start'] = dhcp_part + "." + dhcp_start
|
---|
| 396 | datadump[iface_key]['dhcp_stop'] = dhcp_part + "." + dhcp_stop
|
---|
| 397 | output += """\
|
---|
| 398 | subnet %(subnet)s netmask %(netmask)s {
|
---|
| 399 | range %(dhcp_start)s %(dhcp_stop)s;
|
---|
| 400 | option routers %(addr)s;
|
---|
| 401 | option domain-name-servers %(addr)s;
|
---|
| 402 | }
|
---|
| 403 | \n""" % datadump[iface_key]
|
---|
| 404 |
|
---|
| 405 | return output
|
---|
| 406 |
|
---|
| 407 |
|
---|
| 408 |
|
---|
[8242] | 409 | def generate_dnsmasq_conf(datadump):
|
---|
[8257] | 410 | """ Generate configuration file '/usr/local/etc/dnsmasq.conf' """
|
---|
[8242] | 411 | output = generate_header()
|
---|
[10368] | 412 | output += Template("""\
|
---|
[9283] | 413 | # DHCP server options
|
---|
[8242] | 414 | dhcp-authoritative
|
---|
| 415 | dhcp-fqdn
|
---|
[10391] | 416 | domain=dhcp.{{ autogen_fqdn }}
|
---|
[8242] | 417 | domain-needed
|
---|
| 418 | expand-hosts
|
---|
[10120] | 419 | log-async=100
|
---|
[8242] | 420 |
|
---|
| 421 | # Low memory footprint
|
---|
| 422 | cache-size=10000
|
---|
| 423 |
|
---|
[10368] | 424 | \n""").render(datadump)
|
---|
| 425 |
|
---|
[10281] | 426 | for iface_key in datadump['autogen_iface_keys']:
|
---|
[8262] | 427 | if not datadump[iface_key].has_key('comment'):
|
---|
[10455] | 428 | datadump[iface_key]['comment'] = None
|
---|
[8262] | 429 | output += "## %(interface)s - %(desc)s - %(comment)s\n" % datadump[iface_key]
|
---|
[8242] | 430 |
|
---|
| 431 | try:
|
---|
[8257] | 432 | (dhcp_start, dhcp_stop) = datadump[iface_key]['dhcp'].split('-')
|
---|
[10410] | 433 | (ip, cidr) = datadump[iface_key]['ip'].split('/')
|
---|
| 434 | datadump[iface_key]['netmask'] = cidr2netmask(cidr)
|
---|
[8262] | 435 | except (AttributeError, ValueError):
|
---|
[8242] | 436 | output += "# not autoritive\n\n"
|
---|
| 437 | continue
|
---|
| 438 |
|
---|
| 439 | dhcp_part = ".".join(ip.split('.')[0:3])
|
---|
| 440 | datadump[iface_key]['dhcp_start'] = dhcp_part + "." + dhcp_start
|
---|
| 441 | datadump[iface_key]['dhcp_stop'] = dhcp_part + "." + dhcp_stop
|
---|
[10410] | 442 | output += "dhcp-range=%(interface)s,%(dhcp_start)s,%(dhcp_stop)s,%(netmask)s,24h\n\n" % datadump[iface_key]
|
---|
[9283] | 443 |
|
---|
[8242] | 444 | return output
|
---|
| 445 |
|
---|
[8257] | 446 |
|
---|
| 447 |
|
---|
[8242] | 448 | def generate_rc_conf_local(datadump):
|
---|
[8257] | 449 | """ Generate configuration file '/etc/rc.conf.local' """
|
---|
[10455] | 450 | if not datadump.has_key('ileiden'):
|
---|
| 451 | datadump['autogen_ileiden_enable'] = False
|
---|
| 452 | else:
|
---|
| 453 | datadump['autogen_ileiden_enable'] = datadump['ileiden']
|
---|
[10110] | 454 |
|
---|
[10547] | 455 | datadump['autogen_ileiden_enable'] = switchFormat(datadump['autogen_ileiden_enable'])
|
---|
| 456 |
|
---|
[10112] | 457 | ileiden_proxies = []
|
---|
[10367] | 458 | normal_proxies = []
|
---|
[10112] | 459 | for proxy in get_proxylist():
|
---|
| 460 | proxydump = get_yaml(proxy)
|
---|
| 461 | if proxydump['ileiden']:
|
---|
| 462 | ileiden_proxies.append(proxydump)
|
---|
[10367] | 463 | else:
|
---|
| 464 | normal_proxies.append(proxydump)
|
---|
[10461] | 465 | for host in get_hybridlist():
|
---|
| 466 | hostdump = get_yaml(host)
|
---|
[10584] | 467 | if hostdump['service_proxy_ileiden']:
|
---|
[10461] | 468 | ileiden_proxies.append(hostdump)
|
---|
[10584] | 469 | if hostdump['service_proxy_normal']:
|
---|
[10461] | 470 | normal_proxies.append(hostdump)
|
---|
| 471 |
|
---|
[10585] | 472 | datadump['autogen_ileiden_proxies'] = ileiden_proxies
|
---|
| 473 | datadump['autogen_normal_proxies'] = normal_proxies
|
---|
| 474 | datadump['autogen_ileiden_proxies_ips'] = ','.join([x['masterip'] for x in ileiden_proxies])
|
---|
[10112] | 475 | datadump['autogen_ileiden_proxies_names'] = ','.join([x['autogen_item'] for x in ileiden_proxies])
|
---|
[10585] | 476 | datadump['autogen_normal_proxies_ips'] = ','.join([x['masterip'] for x in normal_proxies])
|
---|
[10367] | 477 | datadump['autogen_normal_proxies_names'] = ','.join([x['autogen_item'] for x in normal_proxies])
|
---|
[10112] | 478 |
|
---|
[8242] | 479 | output = generate_header("#");
|
---|
[10584] | 480 | output += render_template(datadump, """\
|
---|
[10391] | 481 | hostname='{{ autogen_fqdn }}'
|
---|
[10110] | 482 | location='{{ location }}'
|
---|
| 483 | nodetype="{{ nodetype }}"
|
---|
[9283] | 484 |
|
---|
[10459] | 485 | #
|
---|
| 486 | # Configured listings
|
---|
| 487 | #
|
---|
| 488 | captive_portal_whitelist=""
|
---|
| 489 | {% if nodetype == "Proxy" %}
|
---|
[10054] | 490 | #
|
---|
[10459] | 491 | # Proxy Configuration
|
---|
[10054] | 492 | #
|
---|
[10110] | 493 | {% if gateway -%}
|
---|
| 494 | defaultrouter="{{ gateway }}"
|
---|
| 495 | {% else -%}
|
---|
| 496 | #defaultrouter="NOTSET"
|
---|
| 497 | {% endif -%}
|
---|
| 498 | internalif="{{ internalif }}"
|
---|
[10112] | 499 | ileiden_enable="{{ autogen_ileiden_enable }}"
|
---|
| 500 | gateway_enable="{{ autogen_ileiden_enable }}"
|
---|
[10238] | 501 | pf_enable="yes"
|
---|
[10302] | 502 | pf_rules="/etc/pf.conf"
|
---|
[10455] | 503 | {% if autogen_ileiden_enable -%}
|
---|
[10234] | 504 | pf_flags="-D ext_if={{ externalif }} -D int_if={{ internalif }} -D publicnat={80,443}"
|
---|
[10238] | 505 | lvrouted_enable="{{ autogen_ileiden_enable }}"
|
---|
| 506 | lvrouted_flags="-u -s s00p3rs3kr3t -m 28"
|
---|
| 507 | {% else -%}
|
---|
| 508 | pf_flags="-D ext_if={{ externalif }} -D int_if={{ internalif }} -D publicnat={0}"
|
---|
[10310] | 509 | {% endif -%}
|
---|
[10238] | 510 | {% if internalroute -%}
|
---|
| 511 | static_routes="wleiden"
|
---|
| 512 | route_wleiden="-net 172.16.0.0/12 {{ internalroute }}"
|
---|
[10110] | 513 | {% endif -%}
|
---|
[10054] | 514 |
|
---|
[10584] | 515 | {% elif nodetype == "Hybrid" %}
|
---|
| 516 | #
|
---|
| 517 | # Hybrid Configuration
|
---|
| 518 | #
|
---|
[10597] | 519 | list_ileiden_proxies=`cat <<EOF | awk '{ print $1 }' | tr '\\n' ','
|
---|
[10585] | 520 | {% for item in autogen_ileiden_proxies -%}
|
---|
| 521 | {{ "%-16s"|format(item.masterip) }} # {{ item.autogen_realname }}
|
---|
| 522 | {% endfor -%}
|
---|
| 523 | EOF`
|
---|
[10597] | 524 | list_normal_proxies=`cat <<EOF | awk '{ print $1 }' | tr '\\n' ','
|
---|
[10585] | 525 | {% for item in autogen_normal_proxies -%}
|
---|
| 526 | {{ "%-16s"|format(item.masterip) }} # {{ item.autogen_realname }}
|
---|
| 527 | {% endfor -%}
|
---|
| 528 | EOF`
|
---|
| 529 |
|
---|
[10584] | 530 | captive_portal_interfaces="{{ autogen_dhcp_interfaces|default('none', true) }}"
|
---|
| 531 | externalif="{{ externalif|default('vr0', true) }}"
|
---|
| 532 | masterip="{{ masterip }}"
|
---|
| 533 |
|
---|
| 534 | # Defined services
|
---|
| 535 | service_proxy_ileiden="{{ service_proxy_ileiden|yesorno }}"
|
---|
| 536 | service_proxy_normal="{{ service_proxy_normal|yesorno }}"
|
---|
| 537 | service_accesspoint="{{ service_accesspoint|yesorno }}"
|
---|
| 538 | #
|
---|
[10459] | 539 |
|
---|
[10587] | 540 | {% if service_proxy_ileiden %}
|
---|
[10584] | 541 | pf_rules="/etc/pf.hybrid.conf"
|
---|
| 542 | pf_flags="-D ext_if=$externalif -D ext_if_net=$externalif:network -D masterip=$masterip"
|
---|
[10587] | 543 | pf_flags="$pf_flags -D publicnat=80,443"
|
---|
| 544 | {% elif service_proxy_normal %}
|
---|
[10588] | 545 | pf_rules="/etc/pf.proxy.conf"
|
---|
[10587] | 546 | pf_flags="-D ext_if=$externalif -D ext_if_net=$externalif:network -D masterip=$masterip"
|
---|
| 547 | pf_flags="$pf_flags -D ext_if_gw=${ext_if_gw:-"{{ gateway|default('127.127.127.127') }}"}"
|
---|
| 548 | lvrouted_flags="$lvrouted_flags -z $list_ileiden_proxies"
|
---|
[10584] | 549 | {% else %}
|
---|
| 550 | pf_rules="/etc/pf.node.conf"
|
---|
[10587] | 551 | pf_flags=""
|
---|
[10584] | 552 | {% endif %}
|
---|
[10459] | 553 |
|
---|
[10584] | 554 | {% if service_proxy_normal %}
|
---|
| 555 | tinyproxy_enable="yes"
|
---|
| 556 | {% else %}
|
---|
| 557 | pen_wrapper_enable="yes"
|
---|
| 558 | {% endif %}
|
---|
[10460] | 559 |
|
---|
[10584] | 560 | {% if service_accesspoint %}
|
---|
| 561 | pf_flags="$pf_flags -D captive_portal_interfaces=$captive_portal_interfaces"
|
---|
| 562 | {% endif %}
|
---|
[10459] | 563 |
|
---|
[10584] | 564 | {% if board == "ALIX2" %}
|
---|
| 565 | #
|
---|
| 566 | # ''Fat'' configuration, board has 256MB RAM
|
---|
| 567 | #
|
---|
| 568 | dnsmasq_enable="NO"
|
---|
| 569 | named_enable="YES"
|
---|
| 570 | dhcpd_enable="YES"
|
---|
| 571 | {% endif -%}
|
---|
[10459] | 572 |
|
---|
[10584] | 573 | {% if service_proxy_ileiden and gateway %}
|
---|
| 574 | defaultrouter="{{ gateway }}"
|
---|
| 575 | {% endif %}
|
---|
| 576 | {% elif nodetype == "CNode" %}
|
---|
[10459] | 577 | #
|
---|
[10054] | 578 | # NODE iLeiden Configuration
|
---|
[10112] | 579 | #
|
---|
[10585] | 580 |
|
---|
| 581 | # iLeiden Proxies {{ autogen_ileiden_proxies_names }}
|
---|
| 582 | list_ileiden_proxies="{{ autogen_ileiden_proxies_ips }}"
|
---|
| 583 | # normal Proxies {{ autogen_normal_proxies_names }}
|
---|
| 584 | list_normal_proxies="{{ autogen_normal_proxies_ips }}"
|
---|
| 585 |
|
---|
[10564] | 586 | captive_portal_interfaces="{{ autogen_dhcp_interfaces }}"
|
---|
[10367] | 587 |
|
---|
[10459] | 588 | {% if tproxy -%}
|
---|
| 589 | tproxy_enable='YES'
|
---|
| 590 | tproxy_range='{{ tproxy }}'
|
---|
| 591 | {% else -%}
|
---|
| 592 | tproxy_enable='NO'
|
---|
| 593 | {% endif -%}
|
---|
| 594 |
|
---|
[10367] | 595 | lvrouted_flags="-u -s s00p3rs3kr3t -m 28 -z $list_ileiden_proxies"
|
---|
[10110] | 596 | {% endif %}
|
---|
| 597 |
|
---|
[10584] | 598 | #
|
---|
| 599 | # Interface definitions
|
---|
| 600 | #\n
|
---|
| 601 | """)
|
---|
| 602 |
|
---|
[8242] | 603 | # lo0 configuration:
|
---|
| 604 | # - 172.32.255.1/32 is the proxy.wleiden.net deflector
|
---|
[9283] | 605 | # - masterip is special as it needs to be assigned to at
|
---|
[8242] | 606 | # least one interface, so if not used assign to lo0
|
---|
[9808] | 607 | addrs_list = { 'lo0' : [("127.0.0.1/8", "LocalHost"), ("172.31.255.1/32","Proxy IP")] }
|
---|
[9283] | 608 | iface_map = {'lo0' : 'lo0'}
|
---|
[10366] | 609 | dhclient_if = {'lo0' : False}
|
---|
[8242] | 610 |
|
---|
[8297] | 611 | masterip_used = False
|
---|
[10281] | 612 | for iface_key in datadump['autogen_iface_keys']:
|
---|
[8297] | 613 | if datadump[iface_key]['ip'].startswith(datadump['masterip']):
|
---|
| 614 | masterip_used = True
|
---|
| 615 | break
|
---|
[9283] | 616 | if not masterip_used:
|
---|
[10108] | 617 | addrs_list['lo0'].append((datadump['masterip'] + "/32", 'Master IP Not used in interface'))
|
---|
[8297] | 618 |
|
---|
[10281] | 619 | for iface_key in datadump['autogen_iface_keys']:
|
---|
[8242] | 620 | ifacedump = datadump[iface_key]
|
---|
[10162] | 621 | ifname = ifacedump['autogen_ifname']
|
---|
[8242] | 622 |
|
---|
[10366] | 623 | # Flag dhclient is possible
|
---|
| 624 | dhclient_if[ifname] = ifacedump.has_key('dhcpclient') and ifacedump['dhcpclient']
|
---|
[10318] | 625 |
|
---|
[8242] | 626 | # Add interface IP to list
|
---|
[9808] | 627 | item = (ifacedump['ip'], ifacedump['desc'])
|
---|
[10162] | 628 | if addrs_list.has_key(ifname):
|
---|
| 629 | addrs_list[ifname].append(item)
|
---|
[8242] | 630 | else:
|
---|
[10162] | 631 | addrs_list[ifname] = [item]
|
---|
[8242] | 632 |
|
---|
| 633 | # Alias only needs IP assignment for now, this might change if we
|
---|
| 634 | # are going to use virtual accesspoints
|
---|
| 635 | if "alias" in iface_key:
|
---|
| 636 | continue
|
---|
| 637 |
|
---|
| 638 | # XXX: Might want to deduct type directly from interface name
|
---|
| 639 | if ifacedump['type'] in ['11a', '11b', '11g', 'wireless']:
|
---|
| 640 | # Default to station (client) mode
|
---|
| 641 | ifacedump['wlanmode'] = "sta"
|
---|
[10166] | 642 | if ifacedump['mode'] in ['master', 'master-wds', 'ap', 'ap-wds']:
|
---|
[8242] | 643 | ifacedump['wlanmode'] = "ap"
|
---|
| 644 | # Default to 802.11b mode
|
---|
| 645 | ifacedump['mode'] = '11b'
|
---|
| 646 | if ifacedump['type'] in ['11a', '11b' '11g']:
|
---|
[9283] | 647 | ifacedump['mode'] = ifacedump['type']
|
---|
[8242] | 648 |
|
---|
| 649 | if not ifacedump.has_key('channel'):
|
---|
| 650 | if ifacedump['type'] == '11a':
|
---|
| 651 | ifacedump['channel'] = 36
|
---|
| 652 | else:
|
---|
| 653 | ifacedump['channel'] = 1
|
---|
| 654 |
|
---|
| 655 | # Allow special hacks at the back like wds and stuff
|
---|
| 656 | if not ifacedump.has_key('extra'):
|
---|
| 657 | ifacedump['extra'] = 'regdomain ETSI country NL'
|
---|
| 658 |
|
---|
[10054] | 659 | output += "wlans_%(interface)s='%(autogen_ifname)s'\n" % ifacedump
|
---|
| 660 | output += ("create_args_%(autogen_ifname)s='wlanmode %(wlanmode)s mode " +\
|
---|
[8274] | 661 | "%(mode)s ssid %(ssid)s %(extra)s channel %(channel)s'\n") % ifacedump
|
---|
[9283] | 662 |
|
---|
[8242] | 663 | elif ifacedump['type'] in ['ethernet', 'eth']:
|
---|
| 664 | # No special config needed besides IP
|
---|
| 665 | pass
|
---|
| 666 | else:
|
---|
| 667 | assert False, "Unknown type " + ifacedump['type']
|
---|
| 668 |
|
---|
[9283] | 669 | # Print IP address which needs to be assigned over here
|
---|
[8242] | 670 | output += "\n"
|
---|
| 671 | for iface,addrs in sorted(addrs_list.iteritems()):
|
---|
[10079] | 672 | for addr, comment in sorted(addrs,key=lambda x: parseaddr(x[0].split('/')[0])):
|
---|
[9808] | 673 | output += "# %s || %s || %s\n" % (iface, addr, comment)
|
---|
[8242] | 674 |
|
---|
[10366] | 675 | # Write DHCLIENT entry
|
---|
| 676 | if dhclient_if[iface]:
|
---|
| 677 | output += "ifconfig_%s='SYNCDHCP'\n\n" % (iface)
|
---|
| 678 | else:
|
---|
| 679 | output += "ipv4_addrs_%s='%s'\n\n" % (iface, " ".join([x[0] for x in addrs]))
|
---|
| 680 |
|
---|
[8242] | 681 | return output
|
---|
| 682 |
|
---|
[8257] | 683 |
|
---|
| 684 |
|
---|
[8242] | 685 |
|
---|
[8317] | 686 | def get_all_configs():
|
---|
| 687 | """ Get dict with key 'host' with all configs present """
|
---|
| 688 | configs = dict()
|
---|
| 689 | for host in get_hostlist():
|
---|
| 690 | datadump = get_yaml(host)
|
---|
| 691 | configs[host] = datadump
|
---|
| 692 | return configs
|
---|
| 693 |
|
---|
| 694 |
|
---|
[8319] | 695 | def get_interface_keys(config):
|
---|
| 696 | """ Quick hack to get all interface keys, later stage convert this to a iterator """
|
---|
[10054] | 697 | return sorted([elem for elem in config.keys() if (elem.startswith('iface_') and not "lo0" in elem)])
|
---|
[8317] | 698 |
|
---|
[8319] | 699 |
|
---|
[8317] | 700 | def get_used_ips(configs):
|
---|
| 701 | """ Return array of all IPs used in config files"""
|
---|
| 702 | ip_list = []
|
---|
[8319] | 703 | for config in configs:
|
---|
[8317] | 704 | ip_list.append(config['masterip'])
|
---|
[8319] | 705 | for iface_key in get_interface_keys(config):
|
---|
[8317] | 706 | l = config[iface_key]['ip']
|
---|
| 707 | addr, mask = l.split('/')
|
---|
| 708 | # Special case do not process
|
---|
[8332] | 709 | if valid_addr(addr):
|
---|
| 710 | ip_list.append(addr)
|
---|
| 711 | else:
|
---|
[9728] | 712 | logger.error("## IP '%s' in '%s' not valid" % (addr, config['nodename']))
|
---|
[8317] | 713 | return sorted(ip_list)
|
---|
| 714 |
|
---|
| 715 |
|
---|
| 716 |
|
---|
[8242] | 717 | def generate_resolv_conf(datadump):
|
---|
[8257] | 718 | """ Generate configuration file '/etc/resolv.conf' """
|
---|
[10468] | 719 | # XXX: This should properly going to be an datastructure soon
|
---|
| 720 | datadump['autogen_header'] = generate_header("#")
|
---|
| 721 | datadump['autogen_edge_nameservers'] = ''
|
---|
| 722 | for host in get_proxylist():
|
---|
| 723 | hostdump = get_yaml(host)
|
---|
| 724 | datadump['autogen_edge_nameservers'] += "nameserver %(masterip)-15s # %(autogen_realname)s\n" % hostdump
|
---|
| 725 | for host in get_hybridlist():
|
---|
| 726 | hostdump = get_yaml(host)
|
---|
[10584] | 727 | if hostdump['service_proxy_ileiden'] or hostdump['service_proxy_normal']:
|
---|
[10468] | 728 | datadump['autogen_edge_nameservers'] += "nameserver %(masterip)-15s # %(autogen_realname)s\n" % hostdump
|
---|
| 729 |
|
---|
| 730 | return Template("""\
|
---|
| 731 | {{ autogen_header }}
|
---|
[8242] | 732 | search wleiden.net
|
---|
[10468] | 733 |
|
---|
| 734 | # Try local (cache) first
|
---|
[10209] | 735 | nameserver 127.0.0.1
|
---|
[10468] | 736 |
|
---|
[10584] | 737 | {% if service_proxy_normal or service_proxy_ileiden or nodetype == 'Proxy' -%}
|
---|
[10053] | 738 | nameserver 8.8.8.8 # Google Public NameServer
|
---|
| 739 | nameserver 8.8.4.4 # Google Public NameServer
|
---|
[10468] | 740 | {% else -%}
|
---|
| 741 | {{ autogen_edge_nameservers }}
|
---|
| 742 | {% endif -%}
|
---|
| 743 | """).render(datadump)
|
---|
[10209] | 744 |
|
---|
[9283] | 745 |
|
---|
[8242] | 746 |
|
---|
[10069] | 747 | def generate_motd(datadump):
|
---|
| 748 | """ Generate configuration file '/etc/motd' """
|
---|
[10568] | 749 | output = Template("""\
|
---|
[10069] | 750 | FreeBSD 9.0-RELEASE (kernel.wleiden) #0 r230587: Sun Jan 29 17:09:57 CET 2012
|
---|
[8242] | 751 |
|
---|
[10568] | 752 | WWW: {{ autogen_fqdn }} - http://www.wirelessleiden.nl
|
---|
| 753 | Loc: {{ location }}
|
---|
[8257] | 754 |
|
---|
[10568] | 755 | Services:
|
---|
| 756 | {% if board == "ALIX2" -%}
|
---|
| 757 | - Core Node
|
---|
| 758 | {% else -%}
|
---|
| 759 | - Hulp Node
|
---|
| 760 | {% endif -%}
|
---|
[10584] | 761 | {% if service_proxy_normal -%}
|
---|
[10568] | 762 | - Normal Proxy
|
---|
| 763 | {% endif -%}
|
---|
[10584] | 764 | {% if service_proxy_ileiden -%}
|
---|
[10568] | 765 | - iLeiden Proxy
|
---|
| 766 | {% endif %}
|
---|
[10069] | 767 | Interlinks:
|
---|
[10568] | 768 | """).render(datadump)
|
---|
[10069] | 769 |
|
---|
| 770 | # XXX: This is a hacky way to get the required data
|
---|
| 771 | for line in generate_rc_conf_local(datadump).split('\n'):
|
---|
| 772 | if '||' in line and not line[1:].split()[0] in ['lo0', 'ath0'] :
|
---|
| 773 | output += " - %s \n" % line[1:]
|
---|
| 774 | output += """\
|
---|
| 775 | Attached bridges:
|
---|
| 776 | """
|
---|
| 777 | for iface_key in datadump['autogen_iface_keys']:
|
---|
| 778 | ifacedump = datadump[iface_key]
|
---|
| 779 | if ifacedump.has_key('ns_ip'):
|
---|
| 780 | output += " - %(interface)s || %(mode)s || %(ns_ip)s\n" % ifacedump
|
---|
| 781 |
|
---|
| 782 | return output
|
---|
| 783 |
|
---|
| 784 |
|
---|
[8267] | 785 | def format_yaml_value(value):
|
---|
| 786 | """ Get yaml value in right syntax for outputting """
|
---|
| 787 | if isinstance(value,str):
|
---|
[10049] | 788 | output = '"%s"' % value
|
---|
[8267] | 789 | else:
|
---|
| 790 | output = value
|
---|
[9283] | 791 | return output
|
---|
[8267] | 792 |
|
---|
| 793 |
|
---|
| 794 |
|
---|
| 795 | def format_wleiden_yaml(datadump):
|
---|
[8242] | 796 | """ Special formatting to ensure it is editable"""
|
---|
[9283] | 797 | output = "# Genesis config yaml style\n"
|
---|
[8262] | 798 | output += "# vim:ts=2:et:sw=2:ai\n"
|
---|
[8242] | 799 | output += "#\n"
|
---|
| 800 | iface_keys = [elem for elem in datadump.keys() if elem.startswith('iface_')]
|
---|
| 801 | for key in sorted(set(datadump.keys()) - set(iface_keys)):
|
---|
[8267] | 802 | output += "%-10s: %s\n" % (key, format_yaml_value(datadump[key]))
|
---|
[9283] | 803 |
|
---|
[8242] | 804 | output += "\n\n"
|
---|
[9283] | 805 |
|
---|
[8272] | 806 | key_order = [ 'comment', 'interface', 'ip', 'desc', 'sdesc', 'mode', 'type',
|
---|
| 807 | 'extra_type', 'channel', 'ssid', 'dhcp' ]
|
---|
| 808 |
|
---|
[8242] | 809 | for iface_key in sorted(iface_keys):
|
---|
| 810 | output += "%s:\n" % iface_key
|
---|
[8272] | 811 | for key in key_order + list(sorted(set(datadump[iface_key].keys()) - set(key_order))):
|
---|
| 812 | if datadump[iface_key].has_key(key):
|
---|
[9283] | 813 | output += " %-11s: %s\n" % (key, format_yaml_value(datadump[iface_key][key]))
|
---|
[8242] | 814 | output += "\n\n"
|
---|
| 815 |
|
---|
| 816 | return output
|
---|
| 817 |
|
---|
| 818 |
|
---|
[8257] | 819 |
|
---|
[10067] | 820 | def generate_wleiden_yaml(datadump, header=True):
|
---|
[8267] | 821 | """ Generate (petty) version of wleiden.yaml"""
|
---|
[10053] | 822 | for key in datadump.keys():
|
---|
| 823 | if key.startswith('autogen_'):
|
---|
| 824 | del datadump[key]
|
---|
[10054] | 825 | # Interface autogen cleanups
|
---|
| 826 | elif type(datadump[key]) == dict:
|
---|
| 827 | for key2 in datadump[key].keys():
|
---|
| 828 | if key2.startswith('autogen_'):
|
---|
| 829 | del datadump[key][key2]
|
---|
| 830 |
|
---|
[10067] | 831 | output = generate_header("#") if header else ''
|
---|
[8267] | 832 | output += format_wleiden_yaml(datadump)
|
---|
| 833 | return output
|
---|
| 834 |
|
---|
| 835 |
|
---|
[8588] | 836 | def generate_yaml(datadump):
|
---|
| 837 | return generate_config(datadump['nodename'], "wleiden.yaml", datadump)
|
---|
[8267] | 838 |
|
---|
[8588] | 839 |
|
---|
[9283] | 840 |
|
---|
[8298] | 841 | def generate_config(node, config, datadump=None):
|
---|
[8257] | 842 | """ Print configuration file 'config' of 'node' """
|
---|
[8267] | 843 | output = ""
|
---|
[8242] | 844 | try:
|
---|
| 845 | # Load config file
|
---|
[8298] | 846 | if datadump == None:
|
---|
| 847 | datadump = get_yaml(node)
|
---|
[9283] | 848 |
|
---|
[8242] | 849 | if config == 'wleiden.yaml':
|
---|
[8267] | 850 | output += generate_wleiden_yaml(datadump)
|
---|
| 851 | elif config == 'authorized_keys':
|
---|
[10051] | 852 | f = open(os.path.join(NODE_DIR,"global_keys"), 'r')
|
---|
[8267] | 853 | output += f.read()
|
---|
[8242] | 854 | f.close()
|
---|
| 855 | elif config == 'dnsmasq.conf':
|
---|
[10281] | 856 | output += generate_dnsmasq_conf(datadump)
|
---|
[10410] | 857 | elif config == 'dhcpd.conf':
|
---|
| 858 | output += generate_dhcpd_conf(datadump)
|
---|
[8242] | 859 | elif config == 'rc.conf.local':
|
---|
[10281] | 860 | output += generate_rc_conf_local(datadump)
|
---|
[8242] | 861 | elif config == 'resolv.conf':
|
---|
[10281] | 862 | output += generate_resolv_conf(datadump)
|
---|
[10069] | 863 | elif config == 'motd':
|
---|
[10281] | 864 | output += generate_motd(datadump)
|
---|
[8242] | 865 | else:
|
---|
[9283] | 866 | assert False, "Config not found!"
|
---|
[8242] | 867 | except IOError, e:
|
---|
[8267] | 868 | output += "[ERROR] Config file not found"
|
---|
| 869 | return output
|
---|
[8242] | 870 |
|
---|
| 871 |
|
---|
[8257] | 872 |
|
---|
[8258] | 873 | def process_cgi_request():
|
---|
| 874 | """ When calling from CGI """
|
---|
| 875 | # Update repository if requested
|
---|
| 876 | form = cgi.FieldStorage()
|
---|
| 877 | if form.getvalue("action") == "update":
|
---|
[8259] | 878 | print "Refresh: 5; url=."
|
---|
[8258] | 879 | print "Content-type:text/plain\r\n\r\n",
|
---|
| 880 | print "[INFO] Updating subverion, please wait..."
|
---|
[10143] | 881 | print subprocess.Popen(['svn', 'cleanup', "%s/.." % NODE_DIR], stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0],
|
---|
[10071] | 882 | print subprocess.Popen(['svn', 'up', "%s/.." % NODE_DIR], stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0],
|
---|
[8258] | 883 | print "[INFO] All done, redirecting in 5 seconds"
|
---|
| 884 | sys.exit(0)
|
---|
[9283] | 885 |
|
---|
| 886 |
|
---|
[10270] | 887 | base_uri = os.environ['PATH_INFO']
|
---|
| 888 | uri = base_uri.strip('/').split('/')
|
---|
| 889 |
|
---|
[8267] | 890 | output = ""
|
---|
[10378] | 891 | if base_uri.endswith('/create/network.kml'):
|
---|
| 892 | output += "Content-type:application/vnd.google-earth.kml+xml\r\n\r\n"
|
---|
| 893 | output += make_network_kml.make_graph()
|
---|
| 894 | elif not uri[0]:
|
---|
[10070] | 895 | if is_text_request():
|
---|
[10060] | 896 | output += "Content-type:text/plain\r\n\r\n"
|
---|
| 897 | output += '\n'.join(get_hostlist())
|
---|
| 898 | else:
|
---|
| 899 | output += "Content-type:text/html\r\n\r\n"
|
---|
| 900 | output += generate_title(get_hostlist())
|
---|
[8258] | 901 | elif len(uri) == 1:
|
---|
[10270] | 902 | if is_text_request():
|
---|
| 903 | output += "Content-type:text/plain\r\n\r\n"
|
---|
| 904 | output += generate_node(uri[0])
|
---|
| 905 | else:
|
---|
| 906 | output += "Content-type:text/html\r\n\r\n"
|
---|
| 907 | output += generate_node_overview(uri[0])
|
---|
[8258] | 908 | elif len(uri) == 2:
|
---|
[8267] | 909 | output += "Content-type:text/plain\r\n\r\n"
|
---|
| 910 | output += generate_config(uri[0], uri[1])
|
---|
[8258] | 911 | else:
|
---|
| 912 | assert False, "Invalid option"
|
---|
[8267] | 913 | print output
|
---|
[8242] | 914 |
|
---|
[10391] | 915 | def get_realname(datadump):
|
---|
[10365] | 916 | # Proxy naming convention is special, as the proxy name is also included in
|
---|
| 917 | # the nodename, when it comes to the numbered proxies.
|
---|
[8588] | 918 | if datadump['nodetype'] == 'Proxy':
|
---|
[10391] | 919 | realname = datadump['nodetype'] + datadump['nodename'].replace('proxy','')
|
---|
[8588] | 920 | else:
|
---|
| 921 | # By default the full name is listed and also a shortname CNAME for easy use.
|
---|
[10391] | 922 | realname = datadump['nodetype'] + datadump['nodename']
|
---|
| 923 | return(realname)
|
---|
[8259] | 924 |
|
---|
[9283] | 925 |
|
---|
| 926 |
|
---|
[10264] | 927 | def make_dns(output_dir = 'dns', external = False):
|
---|
[8588] | 928 | items = dict()
|
---|
[8598] | 929 |
|
---|
[8588] | 930 | # hostname is key, IP is value
|
---|
| 931 | wleiden_zone = dict()
|
---|
| 932 | wleiden_cname = dict()
|
---|
[8598] | 933 |
|
---|
[8588] | 934 | pool = dict()
|
---|
| 935 | for node in get_hostlist():
|
---|
| 936 | datadump = get_yaml(node)
|
---|
[9283] | 937 |
|
---|
[8588] | 938 | # Proxy naming convention is special
|
---|
[10391] | 939 | fqdn = datadump['autogen_realname']
|
---|
[10461] | 940 | if datadump['nodetype'] in ['CNode', 'Hybrid']:
|
---|
[8588] | 941 | wleiden_cname[datadump['nodename']] = fqdn
|
---|
| 942 |
|
---|
| 943 | wleiden_zone[fqdn] = datadump['masterip']
|
---|
| 944 |
|
---|
[8598] | 945 | # Hacking to get proper DHCP IPs and hostnames
|
---|
[8588] | 946 | for iface_key in get_interface_keys(datadump):
|
---|
[8598] | 947 | iface_name = datadump[iface_key]['interface'].replace(':',"-alias-")
|
---|
[10410] | 948 | (ip, cidr) = datadump[iface_key]['ip'].split('/')
|
---|
[8588] | 949 | try:
|
---|
| 950 | (dhcp_start, dhcp_stop) = datadump[iface_key]['dhcp'].split('-')
|
---|
[10410] | 951 | datadump[iface_key]['netmask'] = cidr2netmask(cidr)
|
---|
[8588] | 952 | dhcp_part = ".".join(ip.split('.')[0:3])
|
---|
| 953 | if ip != datadump['masterip']:
|
---|
| 954 | wleiden_zone["dhcp-gateway-%s.%s" % (iface_name, fqdn)] = ip
|
---|
| 955 | for i in range(int(dhcp_start), int(dhcp_stop) + 1):
|
---|
| 956 | wleiden_zone["dhcp-%s-%s.%s" % (i, iface_name, fqdn)] = "%s.%s" % (dhcp_part, i)
|
---|
| 957 | except (AttributeError, ValueError):
|
---|
| 958 | # First push it into a pool, to indentify the counter-part later on
|
---|
| 959 | addr = parseaddr(ip)
|
---|
[10461] | 960 | cidr = int(cidr)
|
---|
| 961 | addr = addr & ~((1 << (32 - cidr)) - 1)
|
---|
[9283] | 962 | if pool.has_key(addr):
|
---|
[8588] | 963 | pool[addr] += [(iface_name, fqdn, ip)]
|
---|
[9283] | 964 | else:
|
---|
[8588] | 965 | pool[addr] = [(iface_name, fqdn, ip)]
|
---|
| 966 | continue
|
---|
| 967 |
|
---|
[9286] | 968 |
|
---|
| 969 | def pool_to_name(node, pool_members):
|
---|
| 970 | """Convert the joined name to a usable pool name"""
|
---|
| 971 |
|
---|
| 972 | # Get rid of the own entry
|
---|
| 973 | pool_members = list(set(pool_members) - set([fqdn]))
|
---|
| 974 |
|
---|
| 975 | target = oldname = ''
|
---|
| 976 | for node in sorted(pool_members):
|
---|
| 977 | (name, number) = re.match('^([A-Za-z]+)([0-9]*)$',node).group(1,2)
|
---|
| 978 | target += "-" + number if name == oldname else "-" + node if target else node
|
---|
| 979 | oldname = name
|
---|
| 980 |
|
---|
| 981 | return target
|
---|
| 982 |
|
---|
| 983 |
|
---|
[9957] | 984 | # WL uses an /29 to configure an interface. IP's are ordered like this:
|
---|
[9958] | 985 | # MasterA (.1) -- DeviceA (.2) <<>> DeviceB (.3) --- SlaveB (.4)
|
---|
[9957] | 986 |
|
---|
| 987 | sn = lambda x: re.sub(r'(?i)^cnode','',x)
|
---|
| 988 |
|
---|
[8598] | 989 | # Automatic naming convention of interlinks namely 2 + remote.lower()
|
---|
[8588] | 990 | for (key,value) in pool.iteritems():
|
---|
[9958] | 991 | # Make sure they are sorted from low-ip to high-ip
|
---|
| 992 | value = sorted(value, key=lambda x: parseaddr(x[2]))
|
---|
| 993 |
|
---|
[8588] | 994 | if len(value) == 1:
|
---|
| 995 | (iface_name, fqdn, ip) = value[0]
|
---|
| 996 | wleiden_zone["2unused-%s.%s" % (iface_name, fqdn)] = ip
|
---|
[9957] | 997 |
|
---|
| 998 | # Device DNS names
|
---|
| 999 | if 'cnode' in fqdn.lower():
|
---|
| 1000 | wleiden_zone["d-at-%s.%s" % (iface_name, fqdn)] = showaddr(parseaddr(ip) + 1)
|
---|
| 1001 | wleiden_cname["d-at-%s.%s" % (iface_name,sn(fqdn))] = "d-at-%s.%s" % (iface_name, fqdn)
|
---|
| 1002 |
|
---|
[8588] | 1003 | elif len(value) == 2:
|
---|
| 1004 | (a_iface_name, a_fqdn, a_ip) = value[0]
|
---|
| 1005 | (b_iface_name, b_fqdn, b_ip) = value[1]
|
---|
| 1006 | wleiden_zone["2%s.%s" % (b_fqdn,a_fqdn)] = a_ip
|
---|
| 1007 | wleiden_zone["2%s.%s" % (a_fqdn,b_fqdn)] = b_ip
|
---|
[9957] | 1008 |
|
---|
| 1009 | # Device DNS names
|
---|
| 1010 | if 'cnode' in a_fqdn.lower() and 'cnode' in b_fqdn.lower():
|
---|
| 1011 | wleiden_zone["d-at-%s.%s" % (a_iface_name, a_fqdn)] = showaddr(parseaddr(a_ip) + 1)
|
---|
[9958] | 1012 | wleiden_zone["d-at-%s.%s" % (b_iface_name, b_fqdn)] = showaddr(parseaddr(b_ip) - 1)
|
---|
[9957] | 1013 | wleiden_cname["d-at-%s.%s" % (a_iface_name,sn(a_fqdn))] = "d-at-%s.%s" % (a_iface_name, a_fqdn)
|
---|
| 1014 | wleiden_cname["d-at-%s.%s" % (b_iface_name,sn(b_fqdn))] = "d-at-%s.%s" % (b_iface_name, b_fqdn)
|
---|
| 1015 | wleiden_cname["d2%s.%s" % (sn(b_fqdn),sn(a_fqdn))] = "d-at-%s.%s" % (a_iface_name, a_fqdn)
|
---|
| 1016 | wleiden_cname["d2%s.%s" % (sn(a_fqdn),sn(b_fqdn))] = "d-at-%s.%s" % (b_iface_name, b_fqdn)
|
---|
| 1017 |
|
---|
[8588] | 1018 | else:
|
---|
| 1019 | pool_members = [k[1] for k in value]
|
---|
| 1020 | for item in value:
|
---|
[9283] | 1021 | (iface_name, fqdn, ip) = item
|
---|
[9286] | 1022 | pool_name = "2pool-" + showaddr(key).replace('.','-') + "-" + pool_to_name(fqdn,pool_members)
|
---|
[8588] | 1023 | wleiden_zone["%s.%s" % (pool_name, fqdn)] = ip
|
---|
[8598] | 1024 |
|
---|
| 1025 | # Include static DNS entries
|
---|
| 1026 | # XXX: Should they override the autogenerated results?
|
---|
| 1027 | # XXX: Convert input to yaml more useable.
|
---|
| 1028 | # Format:
|
---|
| 1029 | ##; this is a comment
|
---|
| 1030 | ## roomburgh=CNodeRoomburgh1
|
---|
| 1031 | ## apkerk1.CNodeVosko=172.17.176.8 ;this as well
|
---|
[9284] | 1032 | dns = yaml.load(open(os.path.join(NODE_DIR,'../dns/staticDNS.yaml'),'r'))
|
---|
[9938] | 1033 |
|
---|
| 1034 | # Hack to allow special entries, for development
|
---|
| 1035 | wleiden_raw = dns['raw']
|
---|
| 1036 | del dns['raw']
|
---|
| 1037 |
|
---|
[8622] | 1038 | for comment, block in dns.iteritems():
|
---|
| 1039 | for k,v in block.iteritems():
|
---|
[8598] | 1040 | if valid_addr(v):
|
---|
| 1041 | wleiden_zone[k] = v
|
---|
| 1042 | else:
|
---|
| 1043 | wleiden_cname[k] = v
|
---|
[9283] | 1044 |
|
---|
[8598] | 1045 | details = dict()
|
---|
| 1046 | # 24 updates a day allowed
|
---|
| 1047 | details['serial'] = time.strftime('%Y%m%d%H')
|
---|
| 1048 |
|
---|
[10264] | 1049 | if external:
|
---|
| 1050 | dns_masters = ['siteview.wirelessleiden.nl', 'ns1.vanderzwet.net']
|
---|
| 1051 | else:
|
---|
| 1052 | dns_masters = ['sunny.wleiden.net']
|
---|
| 1053 |
|
---|
| 1054 | details['master'] = dns_masters[0]
|
---|
| 1055 | details['ns_servers'] = '\n'.join(['\tNS\t%s.' % x for x in dns_masters])
|
---|
| 1056 |
|
---|
[8598] | 1057 | dns_header = '''
|
---|
| 1058 | $TTL 3h
|
---|
[10264] | 1059 | %(zone)s. SOA %(master)s. beheer.lijst.wirelessleiden.nl. ( %(serial)s 1d 12h 1w 3h )
|
---|
[8598] | 1060 | ; Serial, Refresh, Retry, Expire, Neg. cache TTL
|
---|
| 1061 |
|
---|
[10264] | 1062 | %(ns_servers)s
|
---|
[8598] | 1063 | \n'''
|
---|
| 1064 |
|
---|
[9283] | 1065 |
|
---|
[10264] | 1066 | if not os.path.isdir(output_dir):
|
---|
| 1067 | os.makedirs(output_dir)
|
---|
[8598] | 1068 | details['zone'] = 'wleiden.net'
|
---|
[9284] | 1069 | f = open(os.path.join(output_dir,"db." + details['zone']), "w")
|
---|
[8598] | 1070 | f.write(dns_header % details)
|
---|
| 1071 |
|
---|
[8588] | 1072 | for host,ip in wleiden_zone.iteritems():
|
---|
[8598] | 1073 | if valid_addr(ip):
|
---|
[9283] | 1074 | f.write("%s.wleiden.net. IN A %s \n" % (host.lower(), ip))
|
---|
[8588] | 1075 | for source,dest in wleiden_cname.iteritems():
|
---|
[8636] | 1076 | f.write("%s.wleiden.net. IN CNAME %s.wleiden.net.\n" % (source.lower(), dest.lower()))
|
---|
[9938] | 1077 | for source, dest in wleiden_raw.iteritems():
|
---|
| 1078 | f.write("%s.wleiden.net. %s\n" % (source, dest))
|
---|
[8588] | 1079 | f.close()
|
---|
[9283] | 1080 |
|
---|
[8598] | 1081 | # Create whole bunch of specific sub arpa zones. To keep it compliant
|
---|
| 1082 | for s in range(16,32):
|
---|
| 1083 | details['zone'] = '%i.172.in-addr.arpa' % s
|
---|
[9284] | 1084 | f = open(os.path.join(output_dir,"db." + details['zone']), "w")
|
---|
[8598] | 1085 | f.write(dns_header % details)
|
---|
[8588] | 1086 |
|
---|
[8598] | 1087 | #XXX: Not effient, fix to proper data structure and do checks at other
|
---|
| 1088 | # stages
|
---|
| 1089 | for host,ip in wleiden_zone.iteritems():
|
---|
| 1090 | if valid_addr(ip):
|
---|
| 1091 | if int(ip.split('.')[1]) == s:
|
---|
| 1092 | rev_ip = '.'.join(reversed(ip.split('.')))
|
---|
[9283] | 1093 | f.write("%s.in-addr.arpa. IN PTR %s.wleiden.net.\n" % (rev_ip.lower(), host.lower()))
|
---|
[8598] | 1094 | f.close()
|
---|
[8588] | 1095 |
|
---|
[8598] | 1096 |
|
---|
[8259] | 1097 | def usage():
|
---|
[10567] | 1098 | print """Usage: %(prog)s <argument>
|
---|
| 1099 | Argument:
|
---|
| 1100 | \tstandalone [port] = Run configurator webserver [8000]
|
---|
| 1101 | \tdns [outputdir] = Generate BIND compliant zone files in dns [./dns]
|
---|
[9589] | 1102 | \tfull-export = Generate yaml export script for heatmap.
|
---|
[10567] | 1103 | \tstatic [outputdir] = Generate all config files and store on disk
|
---|
| 1104 | \t with format ./<outputdir>/%%NODE%%/%%FILE%% [./static]
|
---|
| 1105 | \ttest <node> <file> = Receive output of CGI script.
|
---|
| 1106 | \tlist <status> <items> = List systems which have certain status
|
---|
[10563] | 1107 |
|
---|
[10567] | 1108 | Arguments:
|
---|
| 1109 | \t<node> = NodeName (example: HybridRick)
|
---|
| 1110 | \t<file> = %(files)s
|
---|
| 1111 | \t<status> = all|up|down|planned
|
---|
| 1112 | \t<items> = systems|nodes|proxies
|
---|
| 1113 |
|
---|
[10563] | 1114 | NOTE FOR DEVELOPERS; you can test your changes like this:
|
---|
| 1115 | BEFORE any changes in this code:
|
---|
| 1116 | $ ./gformat.py static /tmp/pre
|
---|
| 1117 | AFTER the changes:
|
---|
| 1118 | $ ./gformat.py static /tmp/post
|
---|
| 1119 | VIEW differences and VERIFY all are OK:
|
---|
[10564] | 1120 | $ diff -urI 'Generated' -r /tmp/pre /tmp/post
|
---|
[10567] | 1121 | """ % { 'prog' : sys.argv[0], 'files' : '|'.join(files) }
|
---|
[8259] | 1122 | exit(0)
|
---|
| 1123 |
|
---|
| 1124 |
|
---|
[10070] | 1125 | def is_text_request():
|
---|
[10107] | 1126 | """ Find out whether we are calling from the CLI or any text based CLI utility """
|
---|
| 1127 | try:
|
---|
| 1128 | return os.environ['HTTP_USER_AGENT'].split()[0] in ['curl', 'fetch', 'wget']
|
---|
| 1129 | except KeyError:
|
---|
| 1130 | return True
|
---|
[8259] | 1131 |
|
---|
[10547] | 1132 | def switchFormat(setting):
|
---|
| 1133 | if setting:
|
---|
| 1134 | return "YES"
|
---|
| 1135 | else:
|
---|
| 1136 | return "NO"
|
---|
| 1137 |
|
---|
[8267] | 1138 | def main():
|
---|
| 1139 | """Hard working sub"""
|
---|
| 1140 | # Allow easy hacking using the CLI
|
---|
| 1141 | if not os.environ.has_key('PATH_INFO'):
|
---|
| 1142 | if len(sys.argv) < 2:
|
---|
| 1143 | usage()
|
---|
[9283] | 1144 |
|
---|
[8267] | 1145 | if sys.argv[1] == "standalone":
|
---|
| 1146 | import SocketServer
|
---|
| 1147 | import CGIHTTPServer
|
---|
[10105] | 1148 | # Hop to the right working directory.
|
---|
| 1149 | os.chdir(os.path.dirname(__file__))
|
---|
[8267] | 1150 | try:
|
---|
| 1151 | PORT = int(sys.argv[2])
|
---|
| 1152 | except (IndexError,ValueError):
|
---|
| 1153 | PORT = 8000
|
---|
[9283] | 1154 |
|
---|
[8267] | 1155 | class MyCGIHTTPRequestHandler(CGIHTTPServer.CGIHTTPRequestHandler):
|
---|
| 1156 | """ Serve this CGI from the root of the webserver """
|
---|
| 1157 | def is_cgi(self):
|
---|
| 1158 | if "favicon" in self.path:
|
---|
| 1159 | return False
|
---|
[9283] | 1160 |
|
---|
[10364] | 1161 | self.cgi_info = (os.path.basename(__file__), self.path)
|
---|
[8267] | 1162 | self.path = ''
|
---|
| 1163 | return True
|
---|
| 1164 | handler = MyCGIHTTPRequestHandler
|
---|
[9807] | 1165 | SocketServer.TCPServer.allow_reuse_address = True
|
---|
[8267] | 1166 | httpd = SocketServer.TCPServer(("", PORT), handler)
|
---|
| 1167 | httpd.server_name = 'localhost'
|
---|
| 1168 | httpd.server_port = PORT
|
---|
[9283] | 1169 |
|
---|
[9728] | 1170 | logger.info("serving at port %s", PORT)
|
---|
[8860] | 1171 | try:
|
---|
| 1172 | httpd.serve_forever()
|
---|
| 1173 | except KeyboardInterrupt:
|
---|
| 1174 | httpd.shutdown()
|
---|
[9728] | 1175 | logger.info("All done goodbye")
|
---|
[8267] | 1176 | elif sys.argv[1] == "test":
|
---|
| 1177 | os.environ['PATH_INFO'] = "/".join(sys.argv[2:])
|
---|
| 1178 | os.environ['SCRIPT_NAME'] = __file__
|
---|
| 1179 | process_cgi_request()
|
---|
[8296] | 1180 | elif sys.argv[1] == "static":
|
---|
| 1181 | items = dict()
|
---|
[10563] | 1182 | items['output_dir'] = sys.argv[2] if len(sys.argv) > 2 else "./static"
|
---|
[8296] | 1183 | for node in get_hostlist():
|
---|
| 1184 | items['node'] = node
|
---|
[10563] | 1185 | items['wdir'] = "%(output_dir)s/%(node)s" % items
|
---|
[8296] | 1186 | if not os.path.isdir(items['wdir']):
|
---|
| 1187 | os.makedirs(items['wdir'])
|
---|
[8298] | 1188 | datadump = get_yaml(node)
|
---|
[8296] | 1189 | for config in files:
|
---|
| 1190 | items['config'] = config
|
---|
[9728] | 1191 | logger.info("## Generating %(node)s %(config)s" % items)
|
---|
[8296] | 1192 | f = open("%(wdir)s/%(config)s" % items, "w")
|
---|
[8298] | 1193 | f.write(generate_config(node, config, datadump))
|
---|
[8296] | 1194 | f.close()
|
---|
[9514] | 1195 | elif sys.argv[1] == "wind-export":
|
---|
| 1196 | items = dict()
|
---|
| 1197 | for node in get_hostlist():
|
---|
| 1198 | datadump = get_yaml(node)
|
---|
| 1199 | sql = """INSERT IGNORE INTO nodes (name, name_ns, longitude, latitude)
|
---|
| 1200 | VALUES ('%(nodename)s', '%(nodename)s', %(latitude)s, %(longitude)s);""" % datadump;
|
---|
| 1201 | sql = """INSERT IGNORE INTO users_nodes (user_id, node_id, owner)
|
---|
| 1202 | VALUES (
|
---|
| 1203 | (SELECT id FROM users WHERE username = 'rvdzwet'),
|
---|
| 1204 | (SELECT id FROM nodes WHERE name = '%(nodename)s'),
|
---|
| 1205 | 'Y');""" % datadump
|
---|
| 1206 | #for config in files:
|
---|
| 1207 | # items['config'] = config
|
---|
| 1208 | # print "## Generating %(node)s %(config)s" % items
|
---|
| 1209 | # f = open("%(wdir)s/%(config)s" % items, "w")
|
---|
| 1210 | # f.write(generate_config(node, config, datadump))
|
---|
| 1211 | # f.close()
|
---|
| 1212 | for node in get_hostlist():
|
---|
| 1213 | datadump = get_yaml(node)
|
---|
| 1214 | for iface_key in sorted([elem for elem in datadump.keys() if elem.startswith('iface_')]):
|
---|
| 1215 | ifacedump = datadump[iface_key]
|
---|
| 1216 | if ifacedump.has_key('mode') and ifacedump['mode'] == 'ap-wds':
|
---|
| 1217 | ifacedump['nodename'] = datadump['nodename']
|
---|
| 1218 | if not ifacedump.has_key('channel') or not ifacedump['channel']:
|
---|
| 1219 | ifacedump['channel'] = 0
|
---|
| 1220 | sql = """INSERT INTO links (node_id, type, ssid, protocol, channel, status)
|
---|
| 1221 | VALUES ((SELECT id FROM nodes WHERE name = '%(nodename)s'), 'ap',
|
---|
| 1222 | '%(ssid)s', 'IEEE 802.11b', %(channel)s, 'active');""" % ifacedump
|
---|
[9589] | 1223 | elif sys.argv[1] == "full-export":
|
---|
| 1224 | hosts = {}
|
---|
| 1225 | for node in get_hostlist():
|
---|
| 1226 | datadump = get_yaml(node)
|
---|
| 1227 | hosts[datadump['nodename']] = datadump
|
---|
| 1228 | print yaml.dump(hosts)
|
---|
| 1229 |
|
---|
[8584] | 1230 | elif sys.argv[1] == "dns":
|
---|
[10264] | 1231 | make_dns(sys.argv[2] if len(sys.argv) > 2 else 'dns', 'external' in sys.argv)
|
---|
[9283] | 1232 | elif sys.argv[1] == "cleanup":
|
---|
[8588] | 1233 | # First generate all datadumps
|
---|
| 1234 | datadumps = dict()
|
---|
| 1235 | for host in get_hostlist():
|
---|
[9728] | 1236 | logger.info("# Processing: %s", host)
|
---|
[10436] | 1237 | # Set some boring default values
|
---|
| 1238 | datadump = { 'board' : 'UNKNOWN' }
|
---|
| 1239 | datadump.update(get_yaml(host))
|
---|
[10391] | 1240 | datadumps[datadump['autogen_realname']] = datadump
|
---|
[9283] | 1241 |
|
---|
[10455] | 1242 |
|
---|
[10156] | 1243 | for host,datadump in datadumps.iteritems():
|
---|
[10455] | 1244 | # Convert all yes and no to boolean values
|
---|
| 1245 | def fix_boolean(dump):
|
---|
| 1246 | for key in dump.keys():
|
---|
| 1247 | if type(dump[key]) == dict:
|
---|
| 1248 | dump[key] = fix_boolean(dump[key])
|
---|
[10459] | 1249 | elif str(dump[key]).lower() in ["yes", "true"]:
|
---|
[10455] | 1250 | dump[key] = True
|
---|
[10459] | 1251 | elif str(dump[key]).lower() in ["no", "false"]:
|
---|
[10455] | 1252 | # Compass richting no (Noord Oost) is valid input
|
---|
[10459] | 1253 | if key != "compass": dump[key] = False
|
---|
[10455] | 1254 | return dump
|
---|
| 1255 | datadump = fix_boolean(datadump)
|
---|
| 1256 |
|
---|
[10400] | 1257 | if datadump['rdnap_x'] and datadump['rdnap_y']:
|
---|
| 1258 | datadump['latitude'], datadump['longitude'] = rdnap.rd2etrs(datadump['rdnap_x'], datadump['rdnap_y'])
|
---|
| 1259 | elif datadump['latitude'] and datadump['longitude']:
|
---|
| 1260 | datadump['rdnap_x'], datadump['rdnap_y'] = rdnap.etrs2rd(datadump['latitude'], datadump['longitude'])
|
---|
| 1261 |
|
---|
[10319] | 1262 | if datadump['nodename'].startswith('Proxy'):
|
---|
| 1263 | datadump['nodename'] = datadump['nodename'].lower()
|
---|
| 1264 |
|
---|
[10156] | 1265 | for iface_key in datadump['autogen_iface_keys']:
|
---|
| 1266 | # Wireless Leiden SSID have an consistent lowercase/uppercase
|
---|
| 1267 | if datadump[iface_key].has_key('ssid'):
|
---|
| 1268 | ssid = datadump[iface_key]['ssid']
|
---|
| 1269 | prefix = 'ap-WirelessLeiden-'
|
---|
| 1270 | if ssid.lower().startswith(prefix.lower()):
|
---|
| 1271 | datadump[iface_key]['ssid'] = prefix + ssid[len(prefix)].upper() + ssid[len(prefix) + 1:]
|
---|
[10162] | 1272 | if datadump[iface_key].has_key('ns_ip') and not datadump[iface_key].has_key('mode'):
|
---|
| 1273 | datadump[iface_key]['mode'] = 'autogen-FIXME'
|
---|
| 1274 | if not datadump[iface_key].has_key('desc'):
|
---|
| 1275 | datadump[iface_key]['desc'] = 'autogen-FIXME'
|
---|
[10074] | 1276 | store_yaml(datadump)
|
---|
[9971] | 1277 | elif sys.argv[1] == "list":
|
---|
[10567] | 1278 | if len(sys.argv) < 4 or not sys.argv[2] in ["up", "down", "planned", "all"]:
|
---|
| 1279 | usage()
|
---|
| 1280 | if sys.argv[3] == "nodes":
|
---|
[9971] | 1281 | systems = get_nodelist()
|
---|
[10567] | 1282 | elif sys.argv[3] == "proxies":
|
---|
[9971] | 1283 | systems = get_proxylist()
|
---|
[10567] | 1284 | elif sys.argv[3] == "systems":
|
---|
[10270] | 1285 | systems = get_hostlist()
|
---|
[9971] | 1286 | else:
|
---|
| 1287 | usage()
|
---|
| 1288 | for system in systems:
|
---|
| 1289 | datadump = get_yaml(system)
|
---|
[10567] | 1290 | if sys.argv[2] == "all":
|
---|
[9971] | 1291 | print system
|
---|
[10567] | 1292 | elif datadump['status'] == sys.argv[2]:
|
---|
| 1293 | print system
|
---|
[10378] | 1294 | elif sys.argv[1] == "create":
|
---|
| 1295 | if sys.argv[2] == "network.kml":
|
---|
| 1296 | print make_network_kml.make_graph()
|
---|
| 1297 | else:
|
---|
| 1298 | usage()
|
---|
[9283] | 1299 | usage()
|
---|
| 1300 | else:
|
---|
[10070] | 1301 | # Do not enable debugging for config requests as it highly clutters the output
|
---|
| 1302 | if not is_text_request():
|
---|
| 1303 | cgitb.enable()
|
---|
[9283] | 1304 | process_cgi_request()
|
---|
| 1305 |
|
---|
| 1306 |
|
---|
| 1307 | if __name__ == "__main__":
|
---|
| 1308 | main()
|
---|