[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 | #
|
---|
[11426] | 15 | # MUCH FASTER WILL IT BE with mod_wsgi, due to caches and avoiding loading all
|
---|
| 16 | # the heavy template lifting all the time.
|
---|
| 17 | #
|
---|
[11503] | 18 | # WSGIDaemonProcess gformat threads=25
|
---|
[11426] | 19 | # WSGISocketPrefix run/wsgi
|
---|
| 20 | #
|
---|
| 21 | # <Directory /var/www/cgi-bin>
|
---|
| 22 | # WSGIProcessGroup gformat
|
---|
| 23 | # </Directory>
|
---|
| 24 | # WSGIScriptAlias /hello /var/www/cgi-bin/genesis/tools/gformat.py
|
---|
| 25 | #
|
---|
[12473] | 26 | # Package dependencies list:
|
---|
| 27 | # yum install python-yaml pyproj proj-epsg python-jinja2
|
---|
[11426] | 28 | #
|
---|
[8242] | 29 | # Rick van der Zwet <info@rickvanderzwet.nl>
|
---|
[9957] | 30 | #
|
---|
[8622] | 31 |
|
---|
| 32 | # Hack to make the script directory is also threated as a module search path.
|
---|
| 33 | import sys
|
---|
| 34 | import os
|
---|
| 35 | sys.path.append(os.path.dirname(__file__))
|
---|
| 36 |
|
---|
[12246] | 37 | SVN = filter(os.path.isfile, ('/usr/local/bin/svn', '/usr/bin/svn'))[0]
|
---|
[12245] | 38 |
|
---|
[8242] | 39 | import cgi
|
---|
[8267] | 40 | import cgitb
|
---|
| 41 | import copy
|
---|
[8242] | 42 | import glob
|
---|
[11426] | 43 | import make_network_kml
|
---|
| 44 | import math
|
---|
[11738] | 45 | import random
|
---|
| 46 | import re
|
---|
[8242] | 47 | import socket
|
---|
| 48 | import string
|
---|
| 49 | import subprocess
|
---|
| 50 | import time
|
---|
[11426] | 51 | import urlparse
|
---|
[12473] | 52 | import pyproj
|
---|
[11738] | 53 |
|
---|
[8584] | 54 | from pprint import pprint
|
---|
[10281] | 55 | from collections import defaultdict
|
---|
[8575] | 56 | try:
|
---|
| 57 | import yaml
|
---|
| 58 | except ImportError, e:
|
---|
| 59 | print e
|
---|
| 60 | print "[ERROR] Please install the python-yaml or devel/py-yaml package"
|
---|
| 61 | exit(1)
|
---|
[8588] | 62 |
|
---|
| 63 | try:
|
---|
| 64 | from yaml import CLoader as Loader
|
---|
| 65 | from yaml import CDumper as Dumper
|
---|
| 66 | except ImportError:
|
---|
| 67 | from yaml import Loader, Dumper
|
---|
| 68 |
|
---|
[10584] | 69 | from jinja2 import Environment, Template
|
---|
| 70 | def yesorno(value):
|
---|
| 71 | return "YES" if bool(value) else "NO"
|
---|
| 72 | env = Environment()
|
---|
| 73 | env.filters['yesorno'] = yesorno
|
---|
| 74 | def render_template(datadump, template):
|
---|
| 75 | result = env.from_string(template).render(datadump)
|
---|
| 76 | # Make it look pretty to the naked eye, as jinja templates are not so
|
---|
| 77 | # friendly when it comes to whitespace formatting
|
---|
| 78 | ## Remove extra whitespace at end of line lstrip() style.
|
---|
| 79 | result = re.sub(r'\n[\ ]+','\n', result)
|
---|
| 80 | ## Include only a single newline between an definition and a comment
|
---|
| 81 | result = re.sub(r'(["\'])\n+([a-z]|\n#\n)',r'\1\n\2', result)
|
---|
| 82 | ## Remove extra newlines after single comment
|
---|
| 83 | result = re.sub(r'(#\n)\n+([a-z])',r'\1\2', result)
|
---|
| 84 | return result
|
---|
[10110] | 85 |
|
---|
[9697] | 86 | import logging
|
---|
| 87 | logging.basicConfig(format='# %(levelname)s: %(message)s' )
|
---|
| 88 | logger = logging.getLogger()
|
---|
| 89 | logger.setLevel(logging.DEBUG)
|
---|
[8242] | 90 |
|
---|
[9283] | 91 |
|
---|
[8948] | 92 | if os.environ.has_key('CONFIGROOT'):
|
---|
| 93 | NODE_DIR = os.environ['CONFIGROOT']
|
---|
| 94 | else:
|
---|
[9283] | 95 | NODE_DIR = os.path.abspath(os.path.dirname(__file__)) + '/../nodes'
|
---|
[8242] | 96 | __version__ = '$Id: gformat.py 12475 2013-10-17 21:31:37Z rick $'
|
---|
| 97 |
|
---|
[9283] | 98 | files = [
|
---|
[8242] | 99 | 'authorized_keys',
|
---|
| 100 | 'dnsmasq.conf',
|
---|
[10410] | 101 | 'dhcpd.conf',
|
---|
[8242] | 102 | 'rc.conf.local',
|
---|
| 103 | 'resolv.conf',
|
---|
[10069] | 104 | 'motd',
|
---|
[10654] | 105 | 'ntp.conf',
|
---|
[10705] | 106 | 'pf.hybrid.conf.local',
|
---|
[10054] | 107 | 'wleiden.yaml',
|
---|
[8242] | 108 | ]
|
---|
| 109 |
|
---|
[8319] | 110 | # Global variables uses
|
---|
[8323] | 111 | OK = 10
|
---|
| 112 | DOWN = 20
|
---|
| 113 | UNKNOWN = 90
|
---|
[8257] | 114 |
|
---|
[11426] | 115 |
|
---|
[11503] | 116 | ileiden_proxies = []
|
---|
| 117 | normal_proxies = []
|
---|
[10860] | 118 | datadump_cache = {}
|
---|
[11426] | 119 | interface_list_cache = {}
|
---|
| 120 | rc_conf_local_cache = {}
|
---|
[11503] | 121 | nameservers_cache = []
|
---|
[11426] | 122 | def clear_cache():
|
---|
| 123 | ''' Poor mans cache implementation '''
|
---|
[11503] | 124 | global datadump_cache, interface_list_cache, rc_conf_local_cache, ileiden_proxies, normal_proxies, nameservers_cache
|
---|
[11426] | 125 | datadump_cache = {}
|
---|
| 126 | interface_list_cache = {}
|
---|
| 127 | rc_conf_local_cache = {}
|
---|
[11503] | 128 | ileiden_proxies = []
|
---|
| 129 | normal_proxies = []
|
---|
| 130 | nameservers_cache = []
|
---|
[11533] | 131 |
|
---|
[10887] | 132 | NO_DHCP = 0
|
---|
| 133 | DHCP_CLIENT = 10
|
---|
| 134 | DHCP_SERVER = 20
|
---|
| 135 | def dhcp_type(item):
|
---|
| 136 | if not item.has_key('dhcp'):
|
---|
| 137 | return NO_DHCP
|
---|
| 138 | elif not item['dhcp']:
|
---|
| 139 | return NO_DHCP
|
---|
| 140 | elif item['dhcp'].lower() == 'client':
|
---|
| 141 | return DHCP_CLIENT
|
---|
| 142 | else:
|
---|
[10889] | 143 | # Validation Checks
|
---|
| 144 | begin,end = map(int,item['dhcp'].split('-'))
|
---|
| 145 | if begin >= end:
|
---|
| 146 | raise ValueError("DHCP Start >= DHCP End")
|
---|
[10887] | 147 | return DHCP_SERVER
|
---|
| 148 |
|
---|
[12473] | 149 | def etrs2rd(lat, lon):
|
---|
| 150 | p1 = pyproj.Proj(proj='latlon',datum='WGS84')
|
---|
| 151 | p2 = pyproj.Proj(init='EPSG:28992')
|
---|
| 152 | RDx, RDy = pyproj.transform(p1,p2,lon, lat)
|
---|
| 153 | return (RDx, RDy)
|
---|
[10904] | 154 |
|
---|
[12473] | 155 | def rd2etrs(RDx, RDy):
|
---|
| 156 | p1 = pyproj.Proj(init='EPSG:28992')
|
---|
| 157 | p2 = pyproj.Proj(proj='latlon',datum='WGS84')
|
---|
| 158 | lon, lat = pyproj.transform(p1,p2, RDx, RDy)
|
---|
| 159 | return (lat, lon)
|
---|
[10904] | 160 |
|
---|
| 161 | def get_yaml(item,add_version_info=True):
|
---|
[10872] | 162 | try:
|
---|
| 163 | """ Get configuration yaml for 'item'"""
|
---|
| 164 | if datadump_cache.has_key(item):
|
---|
| 165 | return datadump_cache[item].copy()
|
---|
[10860] | 166 |
|
---|
[10872] | 167 | gfile = os.path.join(NODE_DIR,item,'wleiden.yaml')
|
---|
[8257] | 168 |
|
---|
[10904] | 169 | # Default values
|
---|
| 170 | datadump = {
|
---|
| 171 | 'autogen_revision' : 'NOTFOUND',
|
---|
| 172 | 'autogen_gfile' : gfile,
|
---|
| 173 | }
|
---|
[10872] | 174 | f = open(gfile, 'r')
|
---|
| 175 | datadump.update(yaml.load(f,Loader=Loader))
|
---|
| 176 | if datadump['nodetype'] == 'Hybrid':
|
---|
| 177 | # Some values are defined implicitly
|
---|
| 178 | if datadump.has_key('rdr_rules') and datadump['rdr_rules'] and not datadump.has_key('service_incoming_rdr'):
|
---|
| 179 | datadump['service_incoming_rdr'] = True
|
---|
| 180 | # Use some boring defaults
|
---|
| 181 | defaults = {
|
---|
| 182 | 'service_proxy_normal' : False,
|
---|
| 183 | 'service_proxy_ileiden' : False,
|
---|
| 184 | 'service_accesspoint' : True,
|
---|
[11326] | 185 | 'service_incoming_rdr' : False,
|
---|
[11538] | 186 | 'service_concentrator' : False,
|
---|
[11326] | 187 | 'monitoring_group' : 'wleiden',
|
---|
[10872] | 188 | }
|
---|
| 189 | for (key,value) in defaults.iteritems():
|
---|
| 190 | if not datadump.has_key(key):
|
---|
| 191 | datadump[key] = value
|
---|
| 192 | f.close()
|
---|
[10391] | 193 |
|
---|
[10904] | 194 | # Sometimes getting version information is useless or harmfull, like in the pre-commit hooks
|
---|
| 195 | if add_version_info:
|
---|
[12245] | 196 | p = subprocess.Popen([SVN, 'info', datadump['autogen_gfile']], stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
|
---|
[11624] | 197 | lines = p.communicate()[0].split('\n')
|
---|
| 198 | if p.returncode == 0:
|
---|
| 199 | for line in lines:
|
---|
| 200 | if line:
|
---|
| 201 | (key, value) = line.split(': ')
|
---|
| 202 | datadump["autogen_" + key.lower().replace(' ','_')] = value
|
---|
[10904] | 203 |
|
---|
[10872] | 204 | # Preformat certain needed variables for formatting and push those into special object
|
---|
| 205 | datadump['autogen_iface_keys'] = get_interface_keys(datadump)
|
---|
[10391] | 206 |
|
---|
[10872] | 207 | wlan_count=0
|
---|
| 208 | try:
|
---|
| 209 | for key in datadump['autogen_iface_keys']:
|
---|
[10890] | 210 | datadump[key]['autogen_ifbase'] = key.split('_')[1]
|
---|
[12349] | 211 | datadump[key]['autogen_gateway'] = datadump[key]['ip'].split('/')[0]
|
---|
[10872] | 212 | if datadump[key]['type'] in ['11a', '11b', '11g', 'wireless']:
|
---|
| 213 | datadump[key]['autogen_ifname'] = 'wlan%i' % wlan_count
|
---|
| 214 | wlan_count += 1
|
---|
| 215 | else:
|
---|
[10890] | 216 | datadump[key]['autogen_ifname'] = datadump[key]['autogen_ifbase']
|
---|
[10872] | 217 | except Exception as e:
|
---|
| 218 | print "# Error while processing interface %s" % key
|
---|
| 219 | raise
|
---|
[10391] | 220 |
|
---|
[10887] | 221 | dhcp_interfaces = [datadump[key]['autogen_ifname'] for key in datadump['autogen_iface_keys'] \
|
---|
| 222 | if dhcp_type(datadump[key]) == DHCP_SERVER]
|
---|
| 223 |
|
---|
[10872] | 224 | datadump['autogen_dhcp_interfaces'] = dhcp_interfaces
|
---|
| 225 | datadump['autogen_item'] = item
|
---|
[10391] | 226 |
|
---|
[10872] | 227 | datadump['autogen_realname'] = get_realname(datadump)
|
---|
| 228 | datadump['autogen_domain'] = datadump['domain'] if datadump.has_key('domain') else 'wleiden.net.'
|
---|
| 229 | datadump['autogen_fqdn'] = datadump['autogen_realname'] + '.' + datadump['autogen_domain']
|
---|
| 230 | datadump_cache[item] = datadump.copy()
|
---|
| 231 | except Exception as e:
|
---|
| 232 | print "# Error while processing %s" % item
|
---|
| 233 | raise
|
---|
[10391] | 234 | return datadump
|
---|
| 235 |
|
---|
| 236 |
|
---|
| 237 | def store_yaml(datadump, header=False):
|
---|
| 238 | """ Store configuration yaml for 'item'"""
|
---|
| 239 | item = datadump['autogen_item']
|
---|
| 240 | gfile = os.path.join(NODE_DIR,item,'wleiden.yaml')
|
---|
| 241 |
|
---|
[10881] | 242 | output = generate_wleiden_yaml(datadump, header)
|
---|
| 243 |
|
---|
[10391] | 244 | f = open(gfile, 'w')
|
---|
[10881] | 245 | f.write(output)
|
---|
[10391] | 246 | f.close()
|
---|
| 247 |
|
---|
| 248 |
|
---|
[10729] | 249 | def network(ip):
|
---|
| 250 | addr, mask = ip.split('/')
|
---|
| 251 | # Not parsing of these folks please
|
---|
| 252 | addr = parseaddr(addr)
|
---|
| 253 | mask = int(mask)
|
---|
| 254 | network = addr & ~((1 << (32 - mask)) - 1)
|
---|
| 255 | return network
|
---|
| 256 |
|
---|
[10391] | 257 |
|
---|
[10729] | 258 |
|
---|
[10932] | 259 | def make_relations(datadumps=dict()):
|
---|
[10270] | 260 | """ Process _ALL_ yaml files to get connection relations """
|
---|
[10729] | 261 | errors = []
|
---|
[10281] | 262 | poel = defaultdict(list)
|
---|
[10729] | 263 |
|
---|
| 264 | if not datadumps:
|
---|
| 265 | for host in get_hostlist():
|
---|
| 266 | datadumps[host] = get_yaml(host)
|
---|
| 267 |
|
---|
| 268 | for host, datadump in datadumps.iteritems():
|
---|
[10270] | 269 | try:
|
---|
| 270 | for iface_key in datadump['autogen_iface_keys']:
|
---|
[10729] | 271 | net_addr = network(datadump[iface_key]['ip'])
|
---|
| 272 | poel[net_addr] += [(host,datadump[iface_key])]
|
---|
[10270] | 273 | except (KeyError, ValueError), e:
|
---|
[10729] | 274 | errors.append("[FOUT] in '%s' interface '%s' (%s)" % (host,iface_key, e))
|
---|
[10270] | 275 | continue
|
---|
| 276 | return (poel, errors)
|
---|
| 277 |
|
---|
| 278 |
|
---|
[8267] | 279 |
|
---|
[8321] | 280 | def valid_addr(addr):
|
---|
| 281 | """ Show which address is valid in which are not """
|
---|
| 282 | return str(addr).startswith('172.')
|
---|
| 283 |
|
---|
[10692] | 284 | def get_system_list(prefix):
|
---|
| 285 | return sorted([os.path.basename(os.path.dirname(x)) for x in glob.glob("%s/%s*/wleiden.yaml" % (NODE_DIR, prefix))])
|
---|
[8321] | 286 |
|
---|
[10692] | 287 | get_hybridlist = lambda: get_system_list("Hybrid")
|
---|
| 288 | get_nodelist = lambda: get_system_list("CNode")
|
---|
| 289 | get_proxylist = lambda: get_system_list("Proxy")
|
---|
[8267] | 290 |
|
---|
[8296] | 291 | def get_hostlist():
|
---|
| 292 | """ Combined hosts and proxy list"""
|
---|
[10192] | 293 | return get_nodelist() + get_proxylist() + get_hybridlist()
|
---|
[8267] | 294 |
|
---|
[8588] | 295 | def angle_between_points(lat1,lat2,long1,long2):
|
---|
[9283] | 296 | """
|
---|
[8588] | 297 | Return Angle in radians between two GPS coordinates
|
---|
| 298 | See: http://stackoverflow.com/questions/3809179/angle-between-2-gps-coordinates
|
---|
| 299 | """
|
---|
| 300 | dy = lat2 - lat1
|
---|
[10729] | 301 | dx = math.cos(lat1)*(long2 - long1)
|
---|
[8588] | 302 | angle = math.atan2(dy,dx)
|
---|
| 303 | return angle
|
---|
[8267] | 304 |
|
---|
[10729] | 305 |
|
---|
| 306 |
|
---|
[8588] | 307 | def angle_to_cd(angle):
|
---|
| 308 | """ Return Dutch Cardinal Direction estimation in 'one digit' of radian angle """
|
---|
| 309 |
|
---|
| 310 | # For easy conversion get positive degree
|
---|
| 311 | degrees = math.degrees(angle)
|
---|
[10729] | 312 | abs_degrees = 360 + degrees if degrees < 0 else degrees
|
---|
[8588] | 313 |
|
---|
| 314 | # Numbers can be confusing calculate from the 4 main directions
|
---|
| 315 | p = 22.5
|
---|
[10729] | 316 | if abs_degrees < p:
|
---|
| 317 | cd = "n"
|
---|
| 318 | elif abs_degrees < (90 - p):
|
---|
| 319 | cd = "no"
|
---|
| 320 | elif abs_degrees < (90 + p):
|
---|
| 321 | cd = "o"
|
---|
| 322 | elif abs_degrees < (180 - p):
|
---|
| 323 | cd = "zo"
|
---|
| 324 | elif abs_degrees < (180 + p):
|
---|
| 325 | cd = "z"
|
---|
| 326 | elif abs_degrees < (270 - p):
|
---|
| 327 | cd = "zw"
|
---|
| 328 | elif abs_degrees < (270 + p):
|
---|
| 329 | cd = "w"
|
---|
| 330 | elif abs_degrees < (360 - p):
|
---|
| 331 | cd = "nw"
|
---|
[8588] | 332 | else:
|
---|
[10729] | 333 | cd = "n"
|
---|
| 334 | return cd
|
---|
[8588] | 335 |
|
---|
| 336 |
|
---|
[10729] | 337 |
|
---|
| 338 | def cd_between_hosts(hostA, hostB, datadumps):
|
---|
| 339 | # Using RDNAP coordinates
|
---|
| 340 | dx = float(int(datadumps[hostA]['rdnap_x']) - int(datadumps[hostB]['rdnap_x'])) * -1
|
---|
| 341 | dy = float(int(datadumps[hostA]['rdnap_y']) - int(datadumps[hostB]['rdnap_y'])) * -1
|
---|
| 342 | return angle_to_cd(math.atan2(dx,dy))
|
---|
| 343 |
|
---|
| 344 | # GPS coordinates seems to fail somehow
|
---|
| 345 | #latA = float(datadumps[hostA]['latitude'])
|
---|
| 346 | #latB = float(datadumps[hostB]['latitude'])
|
---|
| 347 | #lonA = float(datadumps[hostA]['longitude'])
|
---|
| 348 | #lonB = float(datadumps[hostB]['longitude'])
|
---|
| 349 | #return angle_to_cd(angle_between_points(latA, latB, lonA, lonB))
|
---|
| 350 |
|
---|
| 351 |
|
---|
[8267] | 352 | def generate_title(nodelist):
|
---|
[8257] | 353 | """ Main overview page """
|
---|
[9283] | 354 | items = {'root' : "." }
|
---|
[10682] | 355 | def fl(spaces, line):
|
---|
| 356 | return (' ' * spaces) + line + '\n'
|
---|
| 357 |
|
---|
[8267] | 358 | output = """
|
---|
[8257] | 359 | <html>
|
---|
| 360 | <head>
|
---|
| 361 | <title>Wireless leiden Configurator - GFormat</title>
|
---|
| 362 | <style type="text/css">
|
---|
| 363 | th {background-color: #999999}
|
---|
| 364 | tr:nth-child(odd) {background-color: #cccccc}
|
---|
| 365 | tr:nth-child(even) {background-color: #ffffff}
|
---|
| 366 | th, td {padding: 0.1em 1em}
|
---|
| 367 | </style>
|
---|
| 368 | </head>
|
---|
| 369 | <body>
|
---|
| 370 | <center>
|
---|
[8259] | 371 | <form type="GET" action="%(root)s">
|
---|
[8257] | 372 | <input type="hidden" name="action" value="update">
|
---|
| 373 | <input type="submit" value="Update Configuration Database (SVN)">
|
---|
| 374 | </form>
|
---|
| 375 | <table>
|
---|
[10682] | 376 | <caption><h3>Wireless Leiden Configurator</h3></caption>
|
---|
[8257] | 377 | """ % items
|
---|
[8242] | 378 |
|
---|
[8296] | 379 | for node in nodelist:
|
---|
[8257] | 380 | items['node'] = node
|
---|
[10682] | 381 | output += fl(5, '<tr>') + fl(7,'<td><a href="%(root)s/%(node)s">%(node)s</a></td>' % items)
|
---|
[8257] | 382 | for config in files:
|
---|
| 383 | items['config'] = config
|
---|
[10682] | 384 | output += fl(7,'<td><a href="%(root)s/%(node)s/%(config)s">%(config)s</a></td>' % items)
|
---|
| 385 | output += fl(5, "</tr>")
|
---|
[8267] | 386 | output += """
|
---|
[8257] | 387 | </table>
|
---|
| 388 | <hr />
|
---|
| 389 | <em>%s</em>
|
---|
| 390 | </center>
|
---|
| 391 | </body>
|
---|
| 392 | </html>
|
---|
| 393 | """ % __version__
|
---|
[8242] | 394 |
|
---|
[8267] | 395 | return output
|
---|
[8257] | 396 |
|
---|
| 397 |
|
---|
[8267] | 398 |
|
---|
| 399 | def generate_node(node):
|
---|
[8257] | 400 | """ Print overview of all files available for node """
|
---|
[8267] | 401 | return "\n".join(files)
|
---|
[8242] | 402 |
|
---|
[10270] | 403 | def generate_node_overview(host):
|
---|
| 404 | """ Print overview of all files available for node """
|
---|
| 405 | datadump = get_yaml(host)
|
---|
| 406 | params = { 'host' : host }
|
---|
| 407 | output = "<em><a href='..'>Back to overview</a></em><hr />"
|
---|
| 408 | output += "<h2>Available files:</h2><ul>"
|
---|
| 409 | for cf in files:
|
---|
| 410 | params['cf'] = cf
|
---|
| 411 | output += '<li><a href="%(host)s/%(cf)s">%(cf)s</a></li>\n' % params
|
---|
| 412 | output += "</ul>"
|
---|
[8257] | 413 |
|
---|
[10270] | 414 | # Generate and connection listing
|
---|
| 415 | output += "<h2>Connected To:</h2><ul>"
|
---|
[10281] | 416 | (poel, errors) = make_relations()
|
---|
| 417 | for network, hosts in poel.iteritems():
|
---|
| 418 | if host in [x[0] for x in hosts]:
|
---|
| 419 | if len(hosts) == 1:
|
---|
| 420 | # Single not connected interface
|
---|
| 421 | continue
|
---|
| 422 | for remote,ifacedump in hosts:
|
---|
| 423 | if remote == host:
|
---|
| 424 | # This side of the interface
|
---|
| 425 | continue
|
---|
| 426 | params = { 'remote': remote, 'remote_ip' : ifacedump['ip'] }
|
---|
| 427 | output += '<li><a href="%(remote)s">%(remote)s</a> -- %(remote_ip)s</li>\n' % params
|
---|
[10270] | 428 | output += "</ul>"
|
---|
[10281] | 429 | output += "<h2>MOTD details:</h2><pre>" + generate_motd(datadump) + "</pre>"
|
---|
[8257] | 430 |
|
---|
[10270] | 431 | output += "<hr /><em><a href='..'>Back to overview</a></em>"
|
---|
| 432 | return output
|
---|
| 433 |
|
---|
| 434 |
|
---|
[10904] | 435 | def generate_header(datadump, ctag="#"):
|
---|
[8242] | 436 | return """\
|
---|
[9283] | 437 | %(ctag)s
|
---|
[8242] | 438 | %(ctag)s DO NOT EDIT - Automatically generated by 'gformat'
|
---|
[10904] | 439 | %(ctag)s Generated at %(date)s by %(host)s from r%(revision)s
|
---|
[9283] | 440 | %(ctag)s
|
---|
[10904] | 441 | """ % { 'ctag' : ctag, 'date' : time.ctime(), 'host' : socket.gethostname(), 'revision' : datadump['autogen_revision'] }
|
---|
[8242] | 442 |
|
---|
[8257] | 443 |
|
---|
| 444 |
|
---|
[8242] | 445 | def parseaddr(s):
|
---|
[8257] | 446 | """ Process IPv4 CIDR notation addr to a (binary) number """
|
---|
[8242] | 447 | f = s.split('.')
|
---|
| 448 | return (long(f[0]) << 24L) + \
|
---|
| 449 | (long(f[1]) << 16L) + \
|
---|
| 450 | (long(f[2]) << 8L) + \
|
---|
| 451 | long(f[3])
|
---|
| 452 |
|
---|
[8257] | 453 |
|
---|
| 454 |
|
---|
[8242] | 455 | def showaddr(a):
|
---|
[8257] | 456 | """ Display IPv4 addr in (dotted) CIDR notation """
|
---|
[8242] | 457 | return "%d.%d.%d.%d" % ((a >> 24) & 0xff, (a >> 16) & 0xff, (a >> 8) & 0xff, a & 0xff)
|
---|
| 458 |
|
---|
[8257] | 459 |
|
---|
[8584] | 460 | def is_member(ip, mask, canidate):
|
---|
| 461 | """ Return True if canidate is part of ip/mask block"""
|
---|
[10729] | 462 | ip_addr = parseaddr(ip)
|
---|
| 463 | ip_canidate = parseaddr(canidate)
|
---|
[8584] | 464 | mask = int(mask)
|
---|
| 465 | ip_addr = ip_addr & ~((1 << (32 - mask)) - 1)
|
---|
| 466 | ip_canidate = ip_canidate & ~((1 << (32 - mask)) - 1)
|
---|
| 467 | return ip_addr == ip_canidate
|
---|
[8257] | 468 |
|
---|
[8584] | 469 |
|
---|
| 470 |
|
---|
[10410] | 471 | def cidr2netmask(netmask):
|
---|
[8257] | 472 | """ Given a 'netmask' return corresponding CIDR """
|
---|
[8242] | 473 | return showaddr(0xffffffff & (0xffffffff << (32 - int(netmask))))
|
---|
| 474 |
|
---|
[10410] | 475 | def get_network(addr, mask):
|
---|
| 476 | return showaddr(parseaddr(addr) & ~((1 << (32 - int(mask))) - 1))
|
---|
[8257] | 477 |
|
---|
| 478 |
|
---|
[10410] | 479 | def generate_dhcpd_conf(datadump):
|
---|
| 480 | """ Generate config file '/usr/local/etc/dhcpd.conf """
|
---|
[10904] | 481 | output = generate_header(datadump)
|
---|
[10410] | 482 | output += Template("""\
|
---|
| 483 | # option definitions common to all supported networks...
|
---|
| 484 | option domain-name "dhcp.{{ autogen_fqdn }}";
|
---|
| 485 |
|
---|
| 486 | default-lease-time 600;
|
---|
| 487 | max-lease-time 7200;
|
---|
| 488 |
|
---|
| 489 | # Use this to enble / disable dynamic dns updates globally.
|
---|
| 490 | #ddns-update-style none;
|
---|
| 491 |
|
---|
| 492 | # If this DHCP server is the official DHCP server for the local
|
---|
| 493 | # network, the authoritative directive should be uncommented.
|
---|
| 494 | authoritative;
|
---|
| 495 |
|
---|
| 496 | # Use this to send dhcp log messages to a different log file (you also
|
---|
| 497 | # have to hack syslog.conf to complete the redirection).
|
---|
| 498 | log-facility local7;
|
---|
| 499 |
|
---|
| 500 | #
|
---|
| 501 | # Interface definitions
|
---|
| 502 | #
|
---|
| 503 | \n""").render(datadump)
|
---|
| 504 |
|
---|
[10734] | 505 | dhcp_out = defaultdict(list)
|
---|
[10410] | 506 | for iface_key in datadump['autogen_iface_keys']:
|
---|
[10734] | 507 | ifname = datadump[iface_key]['autogen_ifname']
|
---|
[10410] | 508 | if not datadump[iface_key].has_key('comment'):
|
---|
[10455] | 509 | datadump[iface_key]['comment'] = None
|
---|
[10890] | 510 | dhcp_out[ifname].append(" ## %(autogen_ifname)s - %(comment)s\n" % datadump[iface_key])
|
---|
[10410] | 511 |
|
---|
| 512 | (addr, mask) = datadump[iface_key]['ip'].split('/')
|
---|
[10882] | 513 | datadump[iface_key]['autogen_addr'] = addr
|
---|
| 514 | datadump[iface_key]['autogen_netmask'] = cidr2netmask(mask)
|
---|
| 515 | datadump[iface_key]['autogen_subnet'] = get_network(addr, mask)
|
---|
[10889] | 516 | if dhcp_type(datadump[iface_key]) != DHCP_SERVER:
|
---|
| 517 | dhcp_out[ifname].append(" subnet %(autogen_subnet)s netmask %(autogen_netmask)s {\n ### not autoritive\n }\n" % \
|
---|
| 518 | datadump[iface_key])
|
---|
[10410] | 519 | continue
|
---|
| 520 |
|
---|
[10889] | 521 | (dhcp_start, dhcp_stop) = datadump[iface_key]['dhcp'].split('-')
|
---|
[10410] | 522 | dhcp_part = ".".join(addr.split('.')[0:3])
|
---|
[10882] | 523 | datadump[iface_key]['autogen_dhcp_start'] = dhcp_part + "." + dhcp_start
|
---|
| 524 | datadump[iface_key]['autogen_dhcp_stop'] = dhcp_part + "." + dhcp_stop
|
---|
[10734] | 525 | dhcp_out[ifname].append("""\
|
---|
[10882] | 526 | subnet %(autogen_subnet)s netmask %(autogen_netmask)s {
|
---|
| 527 | range %(autogen_dhcp_start)s %(autogen_dhcp_stop)s;
|
---|
| 528 | option routers %(autogen_addr)s;
|
---|
| 529 | option domain-name-servers %(autogen_addr)s;
|
---|
[10734] | 530 | }
|
---|
| 531 | """ % datadump[iface_key])
|
---|
[10410] | 532 |
|
---|
[10734] | 533 | for ifname,value in dhcp_out.iteritems():
|
---|
| 534 | output += ("shared-network %s {\n" % ifname) + ''.join(value) + '}\n\n'
|
---|
[10410] | 535 | return output
|
---|
| 536 |
|
---|
| 537 |
|
---|
| 538 |
|
---|
[8242] | 539 | def generate_dnsmasq_conf(datadump):
|
---|
[8257] | 540 | """ Generate configuration file '/usr/local/etc/dnsmasq.conf' """
|
---|
[10904] | 541 | output = generate_header(datadump)
|
---|
[10368] | 542 | output += Template("""\
|
---|
[9283] | 543 | # DHCP server options
|
---|
[8242] | 544 | dhcp-authoritative
|
---|
| 545 | dhcp-fqdn
|
---|
[10391] | 546 | domain=dhcp.{{ autogen_fqdn }}
|
---|
[8242] | 547 | domain-needed
|
---|
| 548 | expand-hosts
|
---|
[10120] | 549 | log-async=100
|
---|
[8242] | 550 |
|
---|
| 551 | # Low memory footprint
|
---|
| 552 | cache-size=10000
|
---|
| 553 |
|
---|
[10368] | 554 | \n""").render(datadump)
|
---|
| 555 |
|
---|
[10281] | 556 | for iface_key in datadump['autogen_iface_keys']:
|
---|
[8262] | 557 | if not datadump[iface_key].has_key('comment'):
|
---|
[10455] | 558 | datadump[iface_key]['comment'] = None
|
---|
[10890] | 559 | output += "## %(autogen_ifname)s - %(comment)s\n" % datadump[iface_key]
|
---|
[8242] | 560 |
|
---|
[10889] | 561 | if dhcp_type(datadump[iface_key]) != DHCP_SERVER:
|
---|
[8242] | 562 | output += "# not autoritive\n\n"
|
---|
| 563 | continue
|
---|
| 564 |
|
---|
[10889] | 565 | (dhcp_start, dhcp_stop) = datadump[iface_key]['dhcp'].split('-')
|
---|
| 566 | (ip, cidr) = datadump[iface_key]['ip'].split('/')
|
---|
| 567 | datadump[iface_key]['autogen_netmask'] = cidr2netmask(cidr)
|
---|
| 568 |
|
---|
[8242] | 569 | dhcp_part = ".".join(ip.split('.')[0:3])
|
---|
[10882] | 570 | datadump[iface_key]['autogen_dhcp_start'] = dhcp_part + "." + dhcp_start
|
---|
| 571 | datadump[iface_key]['autogen_dhcp_stop'] = dhcp_part + "." + dhcp_stop
|
---|
[10890] | 572 | output += "dhcp-range=%(autogen_ifname)s,%(autogen_dhcp_start)s,%(autogen_dhcp_stop)s,%(autogen_netmask)s,24h\n\n" % datadump[iface_key]
|
---|
[9283] | 573 |
|
---|
[8242] | 574 | return output
|
---|
| 575 |
|
---|
[8257] | 576 |
|
---|
[10907] | 577 | def make_interface_list(datadump):
|
---|
| 578 | if interface_list_cache.has_key(datadump['autogen_item']):
|
---|
| 579 | return (interface_list_cache[datadump['autogen_item']])
|
---|
| 580 | # lo0 configuration:
|
---|
| 581 | # - 172.32.255.1/32 is the proxy.wleiden.net deflector
|
---|
| 582 | # - masterip is special as it needs to be assigned to at
|
---|
| 583 | # least one interface, so if not used assign to lo0
|
---|
| 584 | addrs_list = { 'lo0' : [("127.0.0.1/8", "LocalHost"), ("172.31.255.1/32","Proxy IP")] }
|
---|
| 585 | dhclient_if = {'lo0' : False}
|
---|
| 586 |
|
---|
| 587 | # XXX: Find some way of send this output nicely
|
---|
| 588 | output = ''
|
---|
| 589 |
|
---|
| 590 | masterip_used = False
|
---|
| 591 | for iface_key in datadump['autogen_iface_keys']:
|
---|
| 592 | if datadump[iface_key]['ip'].startswith(datadump['masterip']):
|
---|
| 593 | masterip_used = True
|
---|
| 594 | break
|
---|
| 595 | if not masterip_used:
|
---|
| 596 | addrs_list['lo0'].append((datadump['masterip'] + "/32", 'Master IP Not used in interface'))
|
---|
| 597 |
|
---|
| 598 | for iface_key in datadump['autogen_iface_keys']:
|
---|
| 599 | ifacedump = datadump[iface_key]
|
---|
| 600 | ifname = ifacedump['autogen_ifname']
|
---|
| 601 |
|
---|
| 602 | # Flag dhclient is possible
|
---|
[11739] | 603 | if not dhclient_if.has_key(ifname) or dhclient_if[ifname] == False:
|
---|
[11736] | 604 | dhclient_if[ifname] = dhcp_type(ifacedump) == DHCP_CLIENT
|
---|
[10907] | 605 |
|
---|
| 606 | # Add interface IP to list
|
---|
| 607 | item = (ifacedump['ip'], ifacedump['comment'])
|
---|
| 608 | if addrs_list.has_key(ifname):
|
---|
| 609 | addrs_list[ifname].append(item)
|
---|
| 610 | else:
|
---|
| 611 | addrs_list[ifname] = [item]
|
---|
| 612 |
|
---|
| 613 | # Alias only needs IP assignment for now, this might change if we
|
---|
| 614 | # are going to use virtual accesspoints
|
---|
| 615 | if "alias" in iface_key:
|
---|
| 616 | continue
|
---|
| 617 |
|
---|
| 618 | # XXX: Might want to deduct type directly from interface name
|
---|
| 619 | if ifacedump['type'] in ['11a', '11b', '11g', 'wireless']:
|
---|
| 620 | # Default to station (client) mode
|
---|
| 621 | ifacedump['autogen_wlanmode'] = "sta"
|
---|
| 622 | if ifacedump['mode'] in ['master', 'master-wds', 'ap', 'ap-wds']:
|
---|
| 623 | ifacedump['autogen_wlanmode'] = "ap"
|
---|
| 624 |
|
---|
| 625 | if not ifacedump.has_key('channel'):
|
---|
| 626 | if ifacedump['type'] == '11a':
|
---|
| 627 | ifacedump['channel'] = 36
|
---|
| 628 | else:
|
---|
| 629 | ifacedump['channel'] = 1
|
---|
| 630 |
|
---|
| 631 | # Allow special hacks at the back like wds and stuff
|
---|
| 632 | if not ifacedump.has_key('extra'):
|
---|
| 633 | ifacedump['autogen_extra'] = 'regdomain ETSI country NL'
|
---|
| 634 | else:
|
---|
| 635 | ifacedump['autogen_extra'] = ifacedump['extra']
|
---|
| 636 |
|
---|
| 637 | output += "wlans_%(autogen_ifbase)s='%(autogen_ifname)s'\n" % ifacedump
|
---|
| 638 | output += ("create_args_%(autogen_ifname)s='wlanmode %(autogen_wlanmode)s mode " +\
|
---|
[11740] | 639 | "%(type)s ssid %(ssid)s %(autogen_extra)s channel %(channel)s'\n") % ifacedump
|
---|
[10907] | 640 |
|
---|
| 641 | elif ifacedump['type'] in ['ethernet', 'eth']:
|
---|
| 642 | # No special config needed besides IP
|
---|
| 643 | pass
|
---|
| 644 | else:
|
---|
| 645 | assert False, "Unknown type " + ifacedump['type']
|
---|
| 646 |
|
---|
| 647 | store = (addrs_list, dhclient_if, output)
|
---|
| 648 | interface_list_cache[datadump['autogen_item']] = store
|
---|
| 649 | return(store)
|
---|
| 650 |
|
---|
| 651 |
|
---|
| 652 |
|
---|
[8242] | 653 | def generate_rc_conf_local(datadump):
|
---|
[8257] | 654 | """ Generate configuration file '/etc/rc.conf.local' """
|
---|
[10860] | 655 | item = datadump['autogen_item']
|
---|
| 656 | if rc_conf_local_cache.has_key(item):
|
---|
| 657 | return rc_conf_local_cache[item]
|
---|
| 658 |
|
---|
[10455] | 659 | if not datadump.has_key('ileiden'):
|
---|
| 660 | datadump['autogen_ileiden_enable'] = False
|
---|
| 661 | else:
|
---|
| 662 | datadump['autogen_ileiden_enable'] = datadump['ileiden']
|
---|
[10110] | 663 |
|
---|
[10547] | 664 | datadump['autogen_ileiden_enable'] = switchFormat(datadump['autogen_ileiden_enable'])
|
---|
| 665 |
|
---|
[10860] | 666 | if not ileiden_proxies or not normal_proxies:
|
---|
| 667 | for proxy in get_proxylist():
|
---|
| 668 | proxydump = get_yaml(proxy)
|
---|
| 669 | if proxydump['ileiden']:
|
---|
| 670 | ileiden_proxies.append(proxydump)
|
---|
| 671 | else:
|
---|
| 672 | normal_proxies.append(proxydump)
|
---|
| 673 | for host in get_hybridlist():
|
---|
| 674 | hostdump = get_yaml(host)
|
---|
| 675 | if hostdump['service_proxy_ileiden']:
|
---|
| 676 | ileiden_proxies.append(hostdump)
|
---|
| 677 | if hostdump['service_proxy_normal']:
|
---|
| 678 | normal_proxies.append(hostdump)
|
---|
[10461] | 679 |
|
---|
[10585] | 680 | datadump['autogen_ileiden_proxies'] = ileiden_proxies
|
---|
| 681 | datadump['autogen_normal_proxies'] = normal_proxies
|
---|
| 682 | datadump['autogen_ileiden_proxies_ips'] = ','.join([x['masterip'] for x in ileiden_proxies])
|
---|
[10112] | 683 | datadump['autogen_ileiden_proxies_names'] = ','.join([x['autogen_item'] for x in ileiden_proxies])
|
---|
[10585] | 684 | datadump['autogen_normal_proxies_ips'] = ','.join([x['masterip'] for x in normal_proxies])
|
---|
[10367] | 685 | datadump['autogen_normal_proxies_names'] = ','.join([x['autogen_item'] for x in normal_proxies])
|
---|
[10112] | 686 |
|
---|
[10904] | 687 | output = generate_header(datadump, "#");
|
---|
[10584] | 688 | output += render_template(datadump, """\
|
---|
[10391] | 689 | hostname='{{ autogen_fqdn }}'
|
---|
[10110] | 690 | location='{{ location }}'
|
---|
| 691 | nodetype="{{ nodetype }}"
|
---|
[9283] | 692 |
|
---|
[10459] | 693 | #
|
---|
| 694 | # Configured listings
|
---|
| 695 | #
|
---|
| 696 | captive_portal_whitelist=""
|
---|
| 697 | {% if nodetype == "Proxy" %}
|
---|
[10054] | 698 | #
|
---|
[10459] | 699 | # Proxy Configuration
|
---|
[10054] | 700 | #
|
---|
[10110] | 701 | {% if gateway -%}
|
---|
| 702 | defaultrouter="{{ gateway }}"
|
---|
| 703 | {% else -%}
|
---|
| 704 | #defaultrouter="NOTSET"
|
---|
| 705 | {% endif -%}
|
---|
| 706 | internalif="{{ internalif }}"
|
---|
[10112] | 707 | ileiden_enable="{{ autogen_ileiden_enable }}"
|
---|
| 708 | gateway_enable="{{ autogen_ileiden_enable }}"
|
---|
[10238] | 709 | pf_enable="yes"
|
---|
[10302] | 710 | pf_rules="/etc/pf.conf"
|
---|
[10455] | 711 | {% if autogen_ileiden_enable -%}
|
---|
[10234] | 712 | pf_flags="-D ext_if={{ externalif }} -D int_if={{ internalif }} -D publicnat={80,443}"
|
---|
[10238] | 713 | lvrouted_enable="{{ autogen_ileiden_enable }}"
|
---|
| 714 | lvrouted_flags="-u -s s00p3rs3kr3t -m 28"
|
---|
| 715 | {% else -%}
|
---|
| 716 | pf_flags="-D ext_if={{ externalif }} -D int_if={{ internalif }} -D publicnat={0}"
|
---|
[10310] | 717 | {% endif -%}
|
---|
[10238] | 718 | {% if internalroute -%}
|
---|
| 719 | static_routes="wleiden"
|
---|
| 720 | route_wleiden="-net 172.16.0.0/12 {{ internalroute }}"
|
---|
[10110] | 721 | {% endif -%}
|
---|
[10054] | 722 |
|
---|
[10584] | 723 | {% elif nodetype == "Hybrid" %}
|
---|
| 724 | #
|
---|
| 725 | # Hybrid Configuration
|
---|
| 726 | #
|
---|
[10599] | 727 | list_ileiden_proxies="
|
---|
[10585] | 728 | {% for item in autogen_ileiden_proxies -%}
|
---|
| 729 | {{ "%-16s"|format(item.masterip) }} # {{ item.autogen_realname }}
|
---|
| 730 | {% endfor -%}
|
---|
[10599] | 731 | "
|
---|
| 732 | list_normal_proxies="
|
---|
[10585] | 733 | {% for item in autogen_normal_proxies -%}
|
---|
| 734 | {{ "%-16s"|format(item.masterip) }} # {{ item.autogen_realname }}
|
---|
| 735 | {% endfor -%}
|
---|
[10599] | 736 | "
|
---|
[10585] | 737 |
|
---|
[10733] | 738 | captive_portal_interfaces="{{ autogen_dhcp_interfaces|join(',')|default('none', true) }}"
|
---|
[10584] | 739 | externalif="{{ externalif|default('vr0', true) }}"
|
---|
| 740 | masterip="{{ masterip }}"
|
---|
| 741 |
|
---|
| 742 | # Defined services
|
---|
| 743 | service_proxy_ileiden="{{ service_proxy_ileiden|yesorno }}"
|
---|
| 744 | service_proxy_normal="{{ service_proxy_normal|yesorno }}"
|
---|
| 745 | service_accesspoint="{{ service_accesspoint|yesorno }}"
|
---|
[10748] | 746 | service_incoming_rdr="{{ service_incoming_rdr|yesorno }}"
|
---|
[11538] | 747 | service_concentrator="{{ service_concentrator|yesorno }}"
|
---|
[10584] | 748 | #
|
---|
[10459] | 749 |
|
---|
[11540] | 750 | {% if service_proxy_ileiden %}
|
---|
[10584] | 751 | pf_rules="/etc/pf.hybrid.conf"
|
---|
[11540] | 752 | {% if service_concentrator %}
|
---|
[11541] | 753 | pf_flags="-D ext_if=$externalif -D ext_if_net=$externalif:network -D inet_if=tun0 -D inet_ip='(tun0)' -D masterip=$masterip"
|
---|
[11540] | 754 | {% else %}
|
---|
| 755 | pf_flags="-D ext_if=$externalif -D ext_if_net=$externalif:network -D inet_if=$externalif -D inet_ip='($externalif:0)' -D masterip=$masterip"
|
---|
| 756 | {% endif %}
|
---|
[10587] | 757 | pf_flags="$pf_flags -D publicnat=80,443"
|
---|
[12247] | 758 | lvrouted_flags="$lvrouted_flags -g"
|
---|
[10748] | 759 | {% elif service_proxy_normal or service_incoming_rdr %}
|
---|
[10649] | 760 | pf_rules="/etc/pf.hybrid.conf"
|
---|
[10587] | 761 | pf_flags="-D ext_if=$externalif -D ext_if_net=$externalif:network -D masterip=$masterip"
|
---|
[10649] | 762 | pf_flags="$pf_flags -D publicnat=0"
|
---|
[10599] | 763 | lvrouted_flags="$lvrouted_flags -z `make_list "$list_ileiden_proxies" ","`"
|
---|
[10649] | 764 | named_setfib="1"
|
---|
| 765 | tinyproxy_setfib="1"
|
---|
| 766 | dnsmasq_setfib="1"
|
---|
[10698] | 767 | sshd_setfib="1"
|
---|
[10584] | 768 | {% else %}
|
---|
[10983] | 769 | named_auto_forward_only="YES"
|
---|
[10584] | 770 | pf_rules="/etc/pf.node.conf"
|
---|
[10587] | 771 | pf_flags=""
|
---|
[10731] | 772 | lvrouted_flags="$lvrouted_flags -z `make_list "$list_ileiden_proxies" ","`"
|
---|
[10584] | 773 | {% endif %}
|
---|
[11539] | 774 | {% if service_concentrator %}
|
---|
| 775 | # Do mind installing certificates is NOT done automatically for security reasons
|
---|
| 776 | openvpn_enable="YES"
|
---|
| 777 | openvpn_configfile="/usr/local/etc/openvpn/client.conf"
|
---|
| 778 | {% endif %}
|
---|
[10459] | 779 |
|
---|
[10584] | 780 | {% if service_proxy_normal %}
|
---|
| 781 | tinyproxy_enable="yes"
|
---|
| 782 | {% else %}
|
---|
| 783 | pen_wrapper_enable="yes"
|
---|
| 784 | {% endif %}
|
---|
[10460] | 785 |
|
---|
[10584] | 786 | {% if service_accesspoint %}
|
---|
| 787 | pf_flags="$pf_flags -D captive_portal_interfaces=$captive_portal_interfaces"
|
---|
| 788 | {% endif %}
|
---|
[10459] | 789 |
|
---|
[10584] | 790 | {% if board == "ALIX2" %}
|
---|
| 791 | #
|
---|
| 792 | # ''Fat'' configuration, board has 256MB RAM
|
---|
| 793 | #
|
---|
| 794 | dnsmasq_enable="NO"
|
---|
| 795 | named_enable="YES"
|
---|
[10732] | 796 | {% if autogen_dhcp_interfaces -%}
|
---|
[10584] | 797 | dhcpd_enable="YES"
|
---|
[10732] | 798 | dhcpd_flags="$dhcpd_flags {{ autogen_dhcp_interfaces|join(' ') }}"
|
---|
| 799 | {% endif -%}
|
---|
[10584] | 800 | {% endif -%}
|
---|
[10459] | 801 |
|
---|
[10823] | 802 | {% if gateway %}
|
---|
[10584] | 803 | defaultrouter="{{ gateway }}"
|
---|
| 804 | {% endif %}
|
---|
| 805 | {% elif nodetype == "CNode" %}
|
---|
[10459] | 806 | #
|
---|
[10054] | 807 | # NODE iLeiden Configuration
|
---|
[10112] | 808 | #
|
---|
[10585] | 809 |
|
---|
| 810 | # iLeiden Proxies {{ autogen_ileiden_proxies_names }}
|
---|
| 811 | list_ileiden_proxies="{{ autogen_ileiden_proxies_ips }}"
|
---|
| 812 | # normal Proxies {{ autogen_normal_proxies_names }}
|
---|
| 813 | list_normal_proxies="{{ autogen_normal_proxies_ips }}"
|
---|
| 814 |
|
---|
[10732] | 815 | captive_portal_interfaces="{{ autogen_dhcp_interfaces|join(',') }}"
|
---|
[10367] | 816 |
|
---|
| 817 | lvrouted_flags="-u -s s00p3rs3kr3t -m 28 -z $list_ileiden_proxies"
|
---|
[10110] | 818 | {% endif %}
|
---|
| 819 |
|
---|
[10584] | 820 | #
|
---|
| 821 | # Interface definitions
|
---|
| 822 | #\n
|
---|
| 823 | """)
|
---|
| 824 |
|
---|
[10907] | 825 | (addrs_list, dhclient_if, extra_ouput) = make_interface_list(datadump)
|
---|
| 826 | output += extra_ouput
|
---|
[8242] | 827 |
|
---|
[9283] | 828 | # Print IP address which needs to be assigned over here
|
---|
[8242] | 829 | output += "\n"
|
---|
| 830 | for iface,addrs in sorted(addrs_list.iteritems()):
|
---|
[10079] | 831 | for addr, comment in sorted(addrs,key=lambda x: parseaddr(x[0].split('/')[0])):
|
---|
[9808] | 832 | output += "# %s || %s || %s\n" % (iface, addr, comment)
|
---|
[8242] | 833 |
|
---|
[10366] | 834 | # Write DHCLIENT entry
|
---|
| 835 | if dhclient_if[iface]:
|
---|
| 836 | output += "ifconfig_%s='SYNCDHCP'\n\n" % (iface)
|
---|
[11739] | 837 |
|
---|
| 838 | # Make sure the external address is always first as this is needed in the
|
---|
| 839 | # firewall setup
|
---|
| 840 | addrs = sorted(
|
---|
| 841 | [x for x in addrs if not '0.0.0.0' in x[0]],
|
---|
| 842 | key=lambda x: x[0].split('.')[0],
|
---|
| 843 | cmp=lambda x,y: cmp(1 if x == '172' else 0, 1 if y == '172' else 0)
|
---|
| 844 | )
|
---|
| 845 | addr_str = " ".join([x[0] for x in addrs])
|
---|
| 846 | output += "ipv4_addrs_%s='%s'\n\n" % (iface, addr_str)
|
---|
[10366] | 847 |
|
---|
[10860] | 848 | rc_conf_local_cache[datadump['autogen_item']] = output
|
---|
[8242] | 849 | return output
|
---|
| 850 |
|
---|
[8257] | 851 |
|
---|
| 852 |
|
---|
[8242] | 853 |
|
---|
[8317] | 854 | def get_all_configs():
|
---|
| 855 | """ Get dict with key 'host' with all configs present """
|
---|
| 856 | configs = dict()
|
---|
| 857 | for host in get_hostlist():
|
---|
| 858 | datadump = get_yaml(host)
|
---|
| 859 | configs[host] = datadump
|
---|
| 860 | return configs
|
---|
| 861 |
|
---|
| 862 |
|
---|
[8319] | 863 | def get_interface_keys(config):
|
---|
| 864 | """ Quick hack to get all interface keys, later stage convert this to a iterator """
|
---|
[10054] | 865 | return sorted([elem for elem in config.keys() if (elem.startswith('iface_') and not "lo0" in elem)])
|
---|
[8317] | 866 |
|
---|
[8319] | 867 |
|
---|
[8317] | 868 | def get_used_ips(configs):
|
---|
| 869 | """ Return array of all IPs used in config files"""
|
---|
| 870 | ip_list = []
|
---|
[8319] | 871 | for config in configs:
|
---|
[8317] | 872 | ip_list.append(config['masterip'])
|
---|
[8319] | 873 | for iface_key in get_interface_keys(config):
|
---|
[8317] | 874 | l = config[iface_key]['ip']
|
---|
| 875 | addr, mask = l.split('/')
|
---|
| 876 | # Special case do not process
|
---|
[8332] | 877 | if valid_addr(addr):
|
---|
| 878 | ip_list.append(addr)
|
---|
| 879 | else:
|
---|
[9728] | 880 | logger.error("## IP '%s' in '%s' not valid" % (addr, config['nodename']))
|
---|
[8317] | 881 | return sorted(ip_list)
|
---|
| 882 |
|
---|
| 883 |
|
---|
| 884 |
|
---|
[10980] | 885 | def get_nameservers(max_servers=None):
|
---|
[10934] | 886 | if nameservers_cache:
|
---|
[10980] | 887 | return nameservers_cache[0:max_servers]
|
---|
[10934] | 888 |
|
---|
[10935] | 889 | for host in get_hybridlist():
|
---|
| 890 | hostdump = get_yaml(host)
|
---|
[10937] | 891 | if hostdump['status'] == 'up' and (hostdump['service_proxy_ileiden'] or hostdump['service_proxy_normal']):
|
---|
[10936] | 892 | nameservers_cache.append((hostdump['masterip'], hostdump['autogen_realname']))
|
---|
| 893 | for host in get_proxylist():
|
---|
| 894 | hostdump = get_yaml(host)
|
---|
[10937] | 895 | if hostdump['status'] == 'up':
|
---|
| 896 | nameservers_cache.append((hostdump['masterip'], hostdump['autogen_realname']))
|
---|
[10934] | 897 |
|
---|
[10980] | 898 | return nameservers_cache[0:max_servers]
|
---|
[10934] | 899 |
|
---|
| 900 |
|
---|
[8242] | 901 | def generate_resolv_conf(datadump):
|
---|
[8257] | 902 | """ Generate configuration file '/etc/resolv.conf' """
|
---|
[10468] | 903 | # XXX: This should properly going to be an datastructure soon
|
---|
[10904] | 904 | datadump['autogen_header'] = generate_header(datadump, "#")
|
---|
[10468] | 905 | datadump['autogen_edge_nameservers'] = ''
|
---|
| 906 |
|
---|
[10934] | 907 |
|
---|
[10936] | 908 | for masterip,realname in get_nameservers():
|
---|
[10934] | 909 | datadump['autogen_edge_nameservers'] += "nameserver %-15s # %s\n" % (masterip, realname)
|
---|
| 910 |
|
---|
[10468] | 911 | return Template("""\
|
---|
| 912 | {{ autogen_header }}
|
---|
[8242] | 913 | search wleiden.net
|
---|
[10468] | 914 |
|
---|
| 915 | # Try local (cache) first
|
---|
[10209] | 916 | nameserver 127.0.0.1
|
---|
[10468] | 917 |
|
---|
[10584] | 918 | {% if service_proxy_normal or service_proxy_ileiden or nodetype == 'Proxy' -%}
|
---|
[10053] | 919 | nameserver 8.8.8.8 # Google Public NameServer
|
---|
| 920 | nameserver 8.8.4.4 # Google Public NameServer
|
---|
[10468] | 921 | {% else -%}
|
---|
[10646] | 922 | # START DYNAMIC LIST - updated by /tools/nameserver-shuffle
|
---|
[10468] | 923 | {{ autogen_edge_nameservers }}
|
---|
| 924 | {% endif -%}
|
---|
| 925 | """).render(datadump)
|
---|
[10209] | 926 |
|
---|
[9283] | 927 |
|
---|
[8242] | 928 |
|
---|
[10654] | 929 | def generate_ntp_conf(datadump):
|
---|
| 930 | """ Generate configuration file '/etc/ntp.conf' """
|
---|
| 931 | # XXX: This should properly going to be an datastructure soon
|
---|
| 932 |
|
---|
[10904] | 933 | datadump['autogen_header'] = generate_header(datadump, "#")
|
---|
[10654] | 934 | datadump['autogen_ntp_servers'] = ''
|
---|
| 935 | for host in get_proxylist():
|
---|
| 936 | hostdump = get_yaml(host)
|
---|
| 937 | datadump['autogen_ntp_servers'] += "server %(masterip)-15s iburst maxpoll 9 # %(autogen_realname)s\n" % hostdump
|
---|
| 938 | for host in get_hybridlist():
|
---|
| 939 | hostdump = get_yaml(host)
|
---|
| 940 | if hostdump['service_proxy_ileiden'] or hostdump['service_proxy_normal']:
|
---|
| 941 | datadump['autogen_ntp_servers'] += "server %(masterip)-15s iburst maxpoll 9 # %(autogen_realname)s\n" % hostdump
|
---|
| 942 |
|
---|
| 943 | return Template("""\
|
---|
| 944 | {{ autogen_header }}
|
---|
| 945 |
|
---|
| 946 | {% if service_proxy_normal or service_proxy_ileiden or nodetype == 'Proxy' -%}
|
---|
| 947 | # Machine hooked to internet.
|
---|
| 948 | server 0.nl.pool.ntp.org iburst maxpoll 9
|
---|
| 949 | server 1.nl.pool.ntp.org iburst maxpoll 9
|
---|
| 950 | server 2.nl.pool.ntp.org iburst maxpoll 9
|
---|
| 951 | server 3.nl.pool.ntp.org iburst maxpoll 9
|
---|
| 952 | {% else -%}
|
---|
| 953 | # Local Wireless Leiden NTP Servers.
|
---|
| 954 | server 0.pool.ntp.wleiden.net iburst maxpoll 9
|
---|
| 955 | server 1.pool.ntp.wleiden.net iburst maxpoll 9
|
---|
| 956 | server 2.pool.ntp.wleiden.net iburst maxpoll 9
|
---|
| 957 | server 3.pool.ntp.wleiden.net iburst maxpoll 9
|
---|
| 958 |
|
---|
| 959 | # All the configured NTP servers
|
---|
| 960 | {{ autogen_ntp_servers }}
|
---|
| 961 | {% endif %}
|
---|
| 962 |
|
---|
| 963 | # If a server loses sync with all upstream servers, NTP clients
|
---|
| 964 | # no longer follow that server. The local clock can be configured
|
---|
| 965 | # to provide a time source when this happens, but it should usually
|
---|
| 966 | # be configured on just one server on a network. For more details see
|
---|
| 967 | # http://support.ntp.org/bin/view/Support/UndisciplinedLocalClock
|
---|
| 968 | # The use of Orphan Mode may be preferable.
|
---|
| 969 | #
|
---|
| 970 | server 127.127.1.0
|
---|
| 971 | fudge 127.127.1.0 stratum 10
|
---|
| 972 | """).render(datadump)
|
---|
| 973 |
|
---|
| 974 |
|
---|
[10705] | 975 | def generate_pf_hybrid_conf_local(datadump):
|
---|
| 976 | """ Generate configuration file '/etc/pf.hybrid.conf.local' """
|
---|
[10904] | 977 | datadump['autogen_header'] = generate_header(datadump, "#")
|
---|
[10705] | 978 | return Template("""\
|
---|
| 979 | {{ autogen_header }}
|
---|
[10654] | 980 |
|
---|
[10705] | 981 | # Redirect some internal facing services outside (7)
|
---|
[10714] | 982 | # INFO: {{ rdr_rules|count }} rdr_rules (outside to internal redirect rules) defined.
|
---|
[10715] | 983 | {% for protocol, src_port,dest_ip,dest_port in rdr_rules -%}
|
---|
| 984 | rdr on $ext_if inet proto {{ protocol }} from any to $ext_if port {{ src_port }} tag SRV -> {{ dest_ip }} port {{ dest_port }}
|
---|
[10714] | 985 | {% endfor -%}
|
---|
[10705] | 986 | """).render(datadump)
|
---|
| 987 |
|
---|
[10069] | 988 | def generate_motd(datadump):
|
---|
| 989 | """ Generate configuration file '/etc/motd' """
|
---|
[10568] | 990 | output = Template("""\
|
---|
[10627] | 991 | FreeBSD run ``service motd onestart'' to make me look normal
|
---|
[8242] | 992 |
|
---|
[10568] | 993 | WWW: {{ autogen_fqdn }} - http://www.wirelessleiden.nl
|
---|
| 994 | Loc: {{ location }}
|
---|
[8257] | 995 |
|
---|
[10568] | 996 | Services:
|
---|
| 997 | {% if board == "ALIX2" -%}
|
---|
[10906] | 998 | {{" -"}} Core Node ({{ board }})
|
---|
[10568] | 999 | {% else -%}
|
---|
[10906] | 1000 | {{" -"}} Hulp Node ({{ board }})
|
---|
[10568] | 1001 | {% endif -%}
|
---|
[10584] | 1002 | {% if service_proxy_normal -%}
|
---|
[10906] | 1003 | {{" -"}} Normal Proxy
|
---|
[10568] | 1004 | {% endif -%}
|
---|
[10584] | 1005 | {% if service_proxy_ileiden -%}
|
---|
[10906] | 1006 | {{" -"}} iLeiden Proxy
|
---|
[10748] | 1007 | {% endif -%}
|
---|
| 1008 | {% if service_incoming_rdr -%}
|
---|
[10906] | 1009 | {{" -"}} Incoming port redirects
|
---|
[10568] | 1010 | {% endif %}
|
---|
[10626] | 1011 | Interlinks:\n
|
---|
[10568] | 1012 | """).render(datadump)
|
---|
[10069] | 1013 |
|
---|
[10907] | 1014 | (addrs_list, dhclient_if, extra_ouput) = make_interface_list(datadump)
|
---|
| 1015 | # Just nasty hack to make the formatting looks nice
|
---|
| 1016 | iface_len = max(map(len,addrs_list.keys()))
|
---|
| 1017 | addr_len = max(map(len,[x[0] for x in [x[0] for x in addrs_list.values()]]))
|
---|
| 1018 | for iface,addrs in sorted(addrs_list.iteritems()):
|
---|
| 1019 | if iface in ['lo0']:
|
---|
| 1020 | continue
|
---|
| 1021 | for addr, comment in sorted(addrs,key=lambda x: parseaddr(x[0].split('/')[0])):
|
---|
| 1022 | output += " - %s || %s || %s\n" % (iface.ljust(iface_len), addr.ljust(addr_len), comment)
|
---|
| 1023 |
|
---|
| 1024 | output += '\n'
|
---|
[10069] | 1025 | output += """\
|
---|
| 1026 | Attached bridges:
|
---|
| 1027 | """
|
---|
[10907] | 1028 | has_item = False
|
---|
[10069] | 1029 | for iface_key in datadump['autogen_iface_keys']:
|
---|
| 1030 | ifacedump = datadump[iface_key]
|
---|
| 1031 | if ifacedump.has_key('ns_ip'):
|
---|
[10907] | 1032 | has_item = True
|
---|
[10890] | 1033 | output += " - %(autogen_ifname)s || %(mode)s || %(ns_ip)s\n" % ifacedump
|
---|
[10907] | 1034 | if not has_item:
|
---|
| 1035 | output += " - none\n"
|
---|
[10069] | 1036 |
|
---|
| 1037 | return output
|
---|
| 1038 |
|
---|
| 1039 |
|
---|
[8267] | 1040 | def format_yaml_value(value):
|
---|
| 1041 | """ Get yaml value in right syntax for outputting """
|
---|
| 1042 | if isinstance(value,str):
|
---|
[10049] | 1043 | output = '"%s"' % value
|
---|
[8267] | 1044 | else:
|
---|
| 1045 | output = value
|
---|
[9283] | 1046 | return output
|
---|
[8267] | 1047 |
|
---|
| 1048 |
|
---|
| 1049 |
|
---|
| 1050 | def format_wleiden_yaml(datadump):
|
---|
[8242] | 1051 | """ Special formatting to ensure it is editable"""
|
---|
[9283] | 1052 | output = "# Genesis config yaml style\n"
|
---|
[8262] | 1053 | output += "# vim:ts=2:et:sw=2:ai\n"
|
---|
[8242] | 1054 | output += "#\n"
|
---|
| 1055 | iface_keys = [elem for elem in datadump.keys() if elem.startswith('iface_')]
|
---|
| 1056 | for key in sorted(set(datadump.keys()) - set(iface_keys)):
|
---|
[10714] | 1057 | if key == 'rdr_rules':
|
---|
| 1058 | output += '%-10s:\n' % 'rdr_rules'
|
---|
| 1059 | for rdr_rule in datadump[key]:
|
---|
| 1060 | output += '- %s\n' % rdr_rule
|
---|
| 1061 | else:
|
---|
| 1062 | output += "%-10s: %s\n" % (key, format_yaml_value(datadump[key]))
|
---|
[9283] | 1063 |
|
---|
[8242] | 1064 | output += "\n\n"
|
---|
[9283] | 1065 |
|
---|
[10881] | 1066 | # Format (key, required)
|
---|
| 1067 | key_order = (
|
---|
| 1068 | ('comment', True),
|
---|
| 1069 | ('ip', True),
|
---|
| 1070 | ('desc', True),
|
---|
| 1071 | ('sdesc', True),
|
---|
| 1072 | ('mode', True),
|
---|
| 1073 | ('type', True),
|
---|
| 1074 | ('extra_type', False),
|
---|
| 1075 | ('channel', False),
|
---|
| 1076 | ('ssid', False),
|
---|
| 1077 | ('dhcp', True),
|
---|
| 1078 | ('compass', False),
|
---|
| 1079 | ('distance', False),
|
---|
| 1080 | ('ns_ip', False),
|
---|
| 1081 | ('bullet2_ip', False),
|
---|
| 1082 | ('ns_mac', False),
|
---|
| 1083 | ('bullet2_mac', False),
|
---|
| 1084 | ('ns_type', False),
|
---|
[10892] | 1085 | ('bridge_type', False),
|
---|
[10881] | 1086 | ('status', True),
|
---|
| 1087 | )
|
---|
[8272] | 1088 |
|
---|
[8242] | 1089 | for iface_key in sorted(iface_keys):
|
---|
[10881] | 1090 | try:
|
---|
| 1091 | remainder = set(datadump[iface_key].keys()) - set([x[0] for x in key_order])
|
---|
| 1092 | if remainder:
|
---|
| 1093 | raise KeyError("invalid keys: %s" % remainder)
|
---|
[8242] | 1094 |
|
---|
[10881] | 1095 | output += "%s:\n" % iface_key
|
---|
| 1096 | for key,required in key_order:
|
---|
| 1097 | if datadump[iface_key].has_key(key):
|
---|
| 1098 | output += " %-11s: %s\n" % (key, format_yaml_value(datadump[iface_key][key]))
|
---|
| 1099 | output += "\n\n"
|
---|
| 1100 | except Exception as e:
|
---|
| 1101 | print "# Error while processing interface %s" % iface_key
|
---|
| 1102 | raise
|
---|
| 1103 |
|
---|
[8242] | 1104 | return output
|
---|
| 1105 |
|
---|
| 1106 |
|
---|
[8257] | 1107 |
|
---|
[10067] | 1108 | def generate_wleiden_yaml(datadump, header=True):
|
---|
[8267] | 1109 | """ Generate (petty) version of wleiden.yaml"""
|
---|
[10904] | 1110 | output = generate_header(datadump, "#") if header else ''
|
---|
| 1111 |
|
---|
[10053] | 1112 | for key in datadump.keys():
|
---|
| 1113 | if key.startswith('autogen_'):
|
---|
| 1114 | del datadump[key]
|
---|
[10054] | 1115 | # Interface autogen cleanups
|
---|
| 1116 | elif type(datadump[key]) == dict:
|
---|
| 1117 | for key2 in datadump[key].keys():
|
---|
| 1118 | if key2.startswith('autogen_'):
|
---|
| 1119 | del datadump[key][key2]
|
---|
| 1120 |
|
---|
[8267] | 1121 | output += format_wleiden_yaml(datadump)
|
---|
| 1122 | return output
|
---|
| 1123 |
|
---|
[12349] | 1124 | def generate_nanostation_config(datadump, iface, ns_type):
|
---|
[12441] | 1125 | #TODO(rvdz): Make sure the proper nanostation IP and subnet is set
|
---|
| 1126 | datadump['iface_%s' % iface]['ns_ip'] = datadump['iface_%s' % iface]['ns_ip'].split('/')[0]
|
---|
| 1127 |
|
---|
[12349] | 1128 | datadump.update(datadump['iface_%s' % iface])
|
---|
[8267] | 1129 |
|
---|
[12349] | 1130 | return open(os.path.join(os.path.dirname(__file__), 'ns5m.cfg.tmpl'),'r').read() % datadump
|
---|
| 1131 |
|
---|
[8588] | 1132 | def generate_yaml(datadump):
|
---|
| 1133 | return generate_config(datadump['nodename'], "wleiden.yaml", datadump)
|
---|
[8267] | 1134 |
|
---|
[8588] | 1135 |
|
---|
[9283] | 1136 |
|
---|
[8298] | 1137 | def generate_config(node, config, datadump=None):
|
---|
[8257] | 1138 | """ Print configuration file 'config' of 'node' """
|
---|
[8267] | 1139 | output = ""
|
---|
[8242] | 1140 | try:
|
---|
| 1141 | # Load config file
|
---|
[8298] | 1142 | if datadump == None:
|
---|
| 1143 | datadump = get_yaml(node)
|
---|
[9283] | 1144 |
|
---|
[8242] | 1145 | if config == 'wleiden.yaml':
|
---|
[8267] | 1146 | output += generate_wleiden_yaml(datadump)
|
---|
| 1147 | elif config == 'authorized_keys':
|
---|
[10051] | 1148 | f = open(os.path.join(NODE_DIR,"global_keys"), 'r')
|
---|
[8267] | 1149 | output += f.read()
|
---|
[12433] | 1150 | node_keys = os.path.join(NODE_DIR,node,'authorized_keys')
|
---|
| 1151 | # Fetch local keys if existing
|
---|
| 1152 | if os.path.exists(node_keys):
|
---|
| 1153 | output += open(node_keys, 'r').read()
|
---|
[8242] | 1154 | f.close()
|
---|
| 1155 | elif config == 'dnsmasq.conf':
|
---|
[10281] | 1156 | output += generate_dnsmasq_conf(datadump)
|
---|
[10410] | 1157 | elif config == 'dhcpd.conf':
|
---|
| 1158 | output += generate_dhcpd_conf(datadump)
|
---|
[8242] | 1159 | elif config == 'rc.conf.local':
|
---|
[10281] | 1160 | output += generate_rc_conf_local(datadump)
|
---|
[8242] | 1161 | elif config == 'resolv.conf':
|
---|
[10281] | 1162 | output += generate_resolv_conf(datadump)
|
---|
[10654] | 1163 | elif config == 'ntp.conf':
|
---|
| 1164 | output += generate_ntp_conf(datadump)
|
---|
[10069] | 1165 | elif config == 'motd':
|
---|
[10281] | 1166 | output += generate_motd(datadump)
|
---|
[10705] | 1167 | elif config == 'pf.hybrid.conf.local':
|
---|
| 1168 | output += generate_pf_hybrid_conf_local(datadump)
|
---|
[12349] | 1169 | elif config.startswith('vr'):
|
---|
| 1170 | interface, ns_type = config.strip('.yaml').split('-')
|
---|
| 1171 | output += generate_nanostation_config(datadump, interface, ns_type)
|
---|
[8242] | 1172 | else:
|
---|
[9283] | 1173 | assert False, "Config not found!"
|
---|
[8242] | 1174 | except IOError, e:
|
---|
[8267] | 1175 | output += "[ERROR] Config file not found"
|
---|
| 1176 | return output
|
---|
[8242] | 1177 |
|
---|
| 1178 |
|
---|
[8257] | 1179 |
|
---|
[11426] | 1180 | def process_cgi_request(environ=os.environ):
|
---|
[8258] | 1181 | """ When calling from CGI """
|
---|
[11426] | 1182 | response_headers = []
|
---|
| 1183 | content_type = 'text/plain'
|
---|
| 1184 |
|
---|
[8258] | 1185 | # Update repository if requested
|
---|
[11427] | 1186 | form = urlparse.parse_qs(environ['QUERY_STRING']) if environ.has_key('QUERY_STRING') else None
|
---|
| 1187 | if form and form.has_key("action") and "update" in form["action"]:
|
---|
[11426] | 1188 | output = "[INFO] Updating subverion, please wait...\n"
|
---|
[12245] | 1189 | output += subprocess.Popen([SVN, 'cleanup', "%s/.." % NODE_DIR], stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0]
|
---|
| 1190 | output += subprocess.Popen([SVN, 'up', "%s/.." % NODE_DIR], stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0]
|
---|
[11426] | 1191 | output += "[INFO] All done, redirecting in 5 seconds"
|
---|
| 1192 | response_headers += [
|
---|
| 1193 | ('Refresh', '5; url=.'),
|
---|
| 1194 | ]
|
---|
[11533] | 1195 | reload_cache()
|
---|
[11426] | 1196 | else:
|
---|
| 1197 | base_uri = environ['PATH_INFO']
|
---|
| 1198 | uri = base_uri.strip('/').split('/')
|
---|
[9283] | 1199 |
|
---|
[11426] | 1200 | output = "Template Holder"
|
---|
| 1201 | if base_uri.endswith('/create/network.kml'):
|
---|
| 1202 | content_type='application/vnd.google-earth.kml+xml'
|
---|
| 1203 | output = make_network_kml.make_graph()
|
---|
[11444] | 1204 | elif base_uri.endswith('/api/get/nodeplanner.json'):
|
---|
| 1205 | content_type='application/json'
|
---|
| 1206 | output = make_network_kml.make_nodeplanner_json()
|
---|
[11426] | 1207 | elif not uri[0]:
|
---|
| 1208 | if is_text_request(environ):
|
---|
| 1209 | output = '\n'.join(get_hostlist())
|
---|
| 1210 | else:
|
---|
| 1211 | content_type = 'text/html'
|
---|
| 1212 | output = generate_title(get_hostlist())
|
---|
| 1213 | elif len(uri) == 1:
|
---|
| 1214 | if is_text_request(environ):
|
---|
| 1215 | output = generate_node(uri[0])
|
---|
| 1216 | else:
|
---|
| 1217 | content_type = 'text/html'
|
---|
| 1218 | output = generate_node_overview(uri[0])
|
---|
| 1219 | elif len(uri) == 2:
|
---|
| 1220 | output = generate_config(uri[0], uri[1])
|
---|
| 1221 | else:
|
---|
| 1222 | assert False, "Invalid option"
|
---|
[9283] | 1223 |
|
---|
[11426] | 1224 | # Return response
|
---|
| 1225 | response_headers += [
|
---|
| 1226 | ('Content-type', content_type),
|
---|
| 1227 | ('Content-Length', str(len(output))),
|
---|
| 1228 | ]
|
---|
| 1229 | return(response_headers, str(output))
|
---|
[10270] | 1230 |
|
---|
[10681] | 1231 |
|
---|
[10391] | 1232 | def get_realname(datadump):
|
---|
[10365] | 1233 | # Proxy naming convention is special, as the proxy name is also included in
|
---|
| 1234 | # the nodename, when it comes to the numbered proxies.
|
---|
[8588] | 1235 | if datadump['nodetype'] == 'Proxy':
|
---|
[10391] | 1236 | realname = datadump['nodetype'] + datadump['nodename'].replace('proxy','')
|
---|
[8588] | 1237 | else:
|
---|
| 1238 | # By default the full name is listed and also a shortname CNAME for easy use.
|
---|
[10391] | 1239 | realname = datadump['nodetype'] + datadump['nodename']
|
---|
| 1240 | return(realname)
|
---|
[8259] | 1241 |
|
---|
[9283] | 1242 |
|
---|
| 1243 |
|
---|
[10264] | 1244 | def make_dns(output_dir = 'dns', external = False):
|
---|
[8588] | 1245 | items = dict()
|
---|
[8598] | 1246 |
|
---|
[8588] | 1247 | # hostname is key, IP is value
|
---|
[10642] | 1248 | wleiden_zone = defaultdict(list)
|
---|
[8588] | 1249 | wleiden_cname = dict()
|
---|
[8598] | 1250 |
|
---|
[8588] | 1251 | pool = dict()
|
---|
| 1252 | for node in get_hostlist():
|
---|
| 1253 | datadump = get_yaml(node)
|
---|
[9283] | 1254 |
|
---|
[8588] | 1255 | # Proxy naming convention is special
|
---|
[10391] | 1256 | fqdn = datadump['autogen_realname']
|
---|
[10461] | 1257 | if datadump['nodetype'] in ['CNode', 'Hybrid']:
|
---|
[8588] | 1258 | wleiden_cname[datadump['nodename']] = fqdn
|
---|
[10730] | 1259 |
|
---|
| 1260 | if datadump.has_key('rdr_host'):
|
---|
| 1261 | remote_target = datadump['rdr_host']
|
---|
| 1262 | elif datadump.has_key('remote_access') and datadump['remote_access']:
|
---|
| 1263 | remote_target = datadump['remote_access'].split(':')[0]
|
---|
| 1264 | else:
|
---|
| 1265 | remote_target = None
|
---|
[8588] | 1266 |
|
---|
[10730] | 1267 | if remote_target:
|
---|
| 1268 | try:
|
---|
| 1269 | parseaddr(remote_target)
|
---|
| 1270 | wleiden_zone[datadump['nodename'] + '.gw'].append((remote_target, False))
|
---|
| 1271 | except (IndexError, ValueError):
|
---|
| 1272 | wleiden_cname[datadump['nodename'] + '.gw'] = remote_target + '.'
|
---|
| 1273 |
|
---|
| 1274 |
|
---|
[10655] | 1275 | wleiden_zone[fqdn].append((datadump['masterip'], True))
|
---|
[8588] | 1276 |
|
---|
[8598] | 1277 | # Hacking to get proper DHCP IPs and hostnames
|
---|
[8588] | 1278 | for iface_key in get_interface_keys(datadump):
|
---|
[10890] | 1279 | iface_name = iface_key.replace('_','-')
|
---|
[10410] | 1280 | (ip, cidr) = datadump[iface_key]['ip'].split('/')
|
---|
[8588] | 1281 | try:
|
---|
| 1282 | (dhcp_start, dhcp_stop) = datadump[iface_key]['dhcp'].split('-')
|
---|
[10882] | 1283 | datadump[iface_key]['autogen_netmask'] = cidr2netmask(cidr)
|
---|
[8588] | 1284 | dhcp_part = ".".join(ip.split('.')[0:3])
|
---|
| 1285 | if ip != datadump['masterip']:
|
---|
[10655] | 1286 | wleiden_zone["dhcp-gateway-%s.%s" % (iface_name, fqdn)].append((ip, False))
|
---|
[8588] | 1287 | for i in range(int(dhcp_start), int(dhcp_stop) + 1):
|
---|
[10655] | 1288 | wleiden_zone["dhcp-%s-%s.%s" % (i, iface_name, fqdn)].append(("%s.%s" % (dhcp_part, i), True))
|
---|
[10825] | 1289 | except (AttributeError, ValueError, KeyError):
|
---|
[8588] | 1290 | # First push it into a pool, to indentify the counter-part later on
|
---|
| 1291 | addr = parseaddr(ip)
|
---|
[10461] | 1292 | cidr = int(cidr)
|
---|
| 1293 | addr = addr & ~((1 << (32 - cidr)) - 1)
|
---|
[9283] | 1294 | if pool.has_key(addr):
|
---|
[8588] | 1295 | pool[addr] += [(iface_name, fqdn, ip)]
|
---|
[9283] | 1296 | else:
|
---|
[8588] | 1297 | pool[addr] = [(iface_name, fqdn, ip)]
|
---|
| 1298 | continue
|
---|
| 1299 |
|
---|
[9286] | 1300 |
|
---|
| 1301 |
|
---|
[9957] | 1302 | # WL uses an /29 to configure an interface. IP's are ordered like this:
|
---|
[9958] | 1303 | # MasterA (.1) -- DeviceA (.2) <<>> DeviceB (.3) --- SlaveB (.4)
|
---|
[9957] | 1304 |
|
---|
| 1305 | sn = lambda x: re.sub(r'(?i)^cnode','',x)
|
---|
| 1306 |
|
---|
[8598] | 1307 | # Automatic naming convention of interlinks namely 2 + remote.lower()
|
---|
[8588] | 1308 | for (key,value) in pool.iteritems():
|
---|
[9958] | 1309 | # Make sure they are sorted from low-ip to high-ip
|
---|
| 1310 | value = sorted(value, key=lambda x: parseaddr(x[2]))
|
---|
| 1311 |
|
---|
[8588] | 1312 | if len(value) == 1:
|
---|
| 1313 | (iface_name, fqdn, ip) = value[0]
|
---|
[10655] | 1314 | wleiden_zone["2unused-%s.%s" % (iface_name, fqdn)].append((ip, True))
|
---|
[9957] | 1315 |
|
---|
| 1316 | # Device DNS names
|
---|
| 1317 | if 'cnode' in fqdn.lower():
|
---|
[10655] | 1318 | wleiden_zone["d-at-%s.%s" % (iface_name, fqdn)].append((showaddr(parseaddr(ip) + 1), False))
|
---|
| 1319 | wleiden_cname["d-at-%s.%s" % (iface_name,sn(fqdn))] = "d-at-%s.%s" % ((iface_name, fqdn))
|
---|
[9957] | 1320 |
|
---|
[8588] | 1321 | elif len(value) == 2:
|
---|
| 1322 | (a_iface_name, a_fqdn, a_ip) = value[0]
|
---|
| 1323 | (b_iface_name, b_fqdn, b_ip) = value[1]
|
---|
[10655] | 1324 | wleiden_zone["2%s.%s" % (b_fqdn,a_fqdn)].append((a_ip, True))
|
---|
| 1325 | wleiden_zone["2%s.%s" % (a_fqdn,b_fqdn)].append((b_ip, True))
|
---|
[9957] | 1326 |
|
---|
| 1327 | # Device DNS names
|
---|
| 1328 | if 'cnode' in a_fqdn.lower() and 'cnode' in b_fqdn.lower():
|
---|
[10655] | 1329 | wleiden_zone["d-at-%s.%s" % (a_iface_name, a_fqdn)].append((showaddr(parseaddr(a_ip) + 1), False))
|
---|
| 1330 | wleiden_zone["d-at-%s.%s" % (b_iface_name, b_fqdn)].append((showaddr(parseaddr(b_ip) - 1), False))
|
---|
[9957] | 1331 | wleiden_cname["d-at-%s.%s" % (a_iface_name,sn(a_fqdn))] = "d-at-%s.%s" % (a_iface_name, a_fqdn)
|
---|
| 1332 | wleiden_cname["d-at-%s.%s" % (b_iface_name,sn(b_fqdn))] = "d-at-%s.%s" % (b_iface_name, b_fqdn)
|
---|
| 1333 | wleiden_cname["d2%s.%s" % (sn(b_fqdn),sn(a_fqdn))] = "d-at-%s.%s" % (a_iface_name, a_fqdn)
|
---|
| 1334 | wleiden_cname["d2%s.%s" % (sn(a_fqdn),sn(b_fqdn))] = "d-at-%s.%s" % (b_iface_name, b_fqdn)
|
---|
| 1335 |
|
---|
[8588] | 1336 | else:
|
---|
| 1337 | pool_members = [k[1] for k in value]
|
---|
| 1338 | for item in value:
|
---|
[9283] | 1339 | (iface_name, fqdn, ip) = item
|
---|
[10919] | 1340 | wleiden_zone["2ring.%s" % (fqdn)].append((ip, True))
|
---|
[8598] | 1341 |
|
---|
| 1342 | # Include static DNS entries
|
---|
| 1343 | # XXX: Should they override the autogenerated results?
|
---|
| 1344 | # XXX: Convert input to yaml more useable.
|
---|
| 1345 | # Format:
|
---|
| 1346 | ##; this is a comment
|
---|
| 1347 | ## roomburgh=CNodeRoomburgh1
|
---|
| 1348 | ## apkerk1.CNodeVosko=172.17.176.8 ;this as well
|
---|
[10642] | 1349 | dns_list = yaml.load(open(os.path.join(NODE_DIR,'../dns/staticDNS.yaml'),'r'))
|
---|
[9938] | 1350 |
|
---|
| 1351 | # Hack to allow special entries, for development
|
---|
[10642] | 1352 | wleiden_raw = {}
|
---|
[9938] | 1353 |
|
---|
[10642] | 1354 | for line in dns_list:
|
---|
[10660] | 1355 | reverse = False
|
---|
[10642] | 1356 | k, items = line.items()[0]
|
---|
[10660] | 1357 | if type(items) == dict:
|
---|
| 1358 | if items.has_key('reverse'):
|
---|
| 1359 | reverse = items['reverse']
|
---|
| 1360 | items = items['a']
|
---|
| 1361 | else:
|
---|
| 1362 | items = items['cname']
|
---|
| 1363 | items = [items] if type(items) != list else items
|
---|
[10642] | 1364 | for item in items:
|
---|
| 1365 | if item.startswith('IN '):
|
---|
| 1366 | wleiden_raw[k] = item
|
---|
| 1367 | elif valid_addr(item):
|
---|
[10660] | 1368 | wleiden_zone[k].append((item, reverse))
|
---|
[8598] | 1369 | else:
|
---|
[10642] | 1370 | wleiden_cname[k] = item
|
---|
[9283] | 1371 |
|
---|
[10986] | 1372 | # Hack to get dynamic pool listing
|
---|
| 1373 | def chunks(l, n):
|
---|
| 1374 | return [l[i:i+n] for i in range(0, len(l), n)]
|
---|
| 1375 |
|
---|
| 1376 | ntp_servers = [x[0] for x in get_nameservers()]
|
---|
| 1377 | for id, chunk in enumerate(chunks(ntp_servers,(len(ntp_servers)/4))):
|
---|
| 1378 | for ntp_server in chunk:
|
---|
| 1379 | wleiden_zone['%i.pool.ntp' % id].append((ntp_server, False))
|
---|
| 1380 |
|
---|
[8598] | 1381 | details = dict()
|
---|
| 1382 | # 24 updates a day allowed
|
---|
| 1383 | details['serial'] = time.strftime('%Y%m%d%H')
|
---|
| 1384 |
|
---|
[10264] | 1385 | if external:
|
---|
| 1386 | dns_masters = ['siteview.wirelessleiden.nl', 'ns1.vanderzwet.net']
|
---|
| 1387 | else:
|
---|
[10980] | 1388 | dns_masters = ['sunny.wleiden.net'] + ["%s.wleiden.net" % x[1] for x in get_nameservers(max_servers=3)]
|
---|
[10264] | 1389 |
|
---|
| 1390 | details['master'] = dns_masters[0]
|
---|
| 1391 | details['ns_servers'] = '\n'.join(['\tNS\t%s.' % x for x in dns_masters])
|
---|
| 1392 |
|
---|
[8598] | 1393 | dns_header = '''
|
---|
| 1394 | $TTL 3h
|
---|
[11725] | 1395 | %(zone)s. SOA %(master)s. beheer.lijst.wirelessleiden.nl. ( %(serial)s 15m 15m 1w 60s )
|
---|
[8598] | 1396 | ; Serial, Refresh, Retry, Expire, Neg. cache TTL
|
---|
| 1397 |
|
---|
[10264] | 1398 | %(ns_servers)s
|
---|
[8598] | 1399 | \n'''
|
---|
| 1400 |
|
---|
[9283] | 1401 |
|
---|
[10264] | 1402 | if not os.path.isdir(output_dir):
|
---|
| 1403 | os.makedirs(output_dir)
|
---|
[8598] | 1404 | details['zone'] = 'wleiden.net'
|
---|
[9284] | 1405 | f = open(os.path.join(output_dir,"db." + details['zone']), "w")
|
---|
[8598] | 1406 | f.write(dns_header % details)
|
---|
| 1407 |
|
---|
[10655] | 1408 | for host,items in wleiden_zone.iteritems():
|
---|
| 1409 | for ip,reverse in items:
|
---|
[10730] | 1410 | if ip not in ['0.0.0.0']:
|
---|
[10642] | 1411 | f.write("%s.wleiden.net. IN A %s \n" % (host.lower(), ip))
|
---|
[8588] | 1412 | for source,dest in wleiden_cname.iteritems():
|
---|
[10730] | 1413 | dest = dest if dest.endswith('.') else dest + ".wleiden.net."
|
---|
| 1414 | f.write("%s.wleiden.net. IN CNAME %s\n" % (source.lower(), dest.lower()))
|
---|
[9938] | 1415 | for source, dest in wleiden_raw.iteritems():
|
---|
| 1416 | f.write("%s.wleiden.net. %s\n" % (source, dest))
|
---|
[8588] | 1417 | f.close()
|
---|
[9283] | 1418 |
|
---|
[8598] | 1419 | # Create whole bunch of specific sub arpa zones. To keep it compliant
|
---|
| 1420 | for s in range(16,32):
|
---|
| 1421 | details['zone'] = '%i.172.in-addr.arpa' % s
|
---|
[9284] | 1422 | f = open(os.path.join(output_dir,"db." + details['zone']), "w")
|
---|
[8598] | 1423 | f.write(dns_header % details)
|
---|
[8588] | 1424 |
|
---|
[8598] | 1425 | #XXX: Not effient, fix to proper data structure and do checks at other
|
---|
| 1426 | # stages
|
---|
[10655] | 1427 | for host,items in wleiden_zone.iteritems():
|
---|
| 1428 | for ip,reverse in items:
|
---|
| 1429 | if not reverse:
|
---|
| 1430 | continue
|
---|
[10642] | 1431 | if valid_addr(ip):
|
---|
[10655] | 1432 | if valid_addr(ip):
|
---|
| 1433 | if int(ip.split('.')[1]) == s:
|
---|
| 1434 | rev_ip = '.'.join(reversed(ip.split('.')))
|
---|
| 1435 | f.write("%s.in-addr.arpa. IN PTR %s.wleiden.net.\n" % (rev_ip.lower(), host.lower()))
|
---|
[8598] | 1436 | f.close()
|
---|
[8588] | 1437 |
|
---|
[8598] | 1438 |
|
---|
[8259] | 1439 | def usage():
|
---|
[10567] | 1440 | print """Usage: %(prog)s <argument>
|
---|
| 1441 | Argument:
|
---|
| 1442 | \tstandalone [port] = Run configurator webserver [8000]
|
---|
| 1443 | \tdns [outputdir] = Generate BIND compliant zone files in dns [./dns]
|
---|
[11326] | 1444 | \tnagios-export [--heavy-load] = Generate basic nagios configuration file.
|
---|
[9589] | 1445 | \tfull-export = Generate yaml export script for heatmap.
|
---|
[10567] | 1446 | \tstatic [outputdir] = Generate all config files and store on disk
|
---|
| 1447 | \t with format ./<outputdir>/%%NODE%%/%%FILE%% [./static]
|
---|
[10872] | 1448 | \ttest <node> [<file>] = Receive output for certain node [all files].
|
---|
| 1449 | \ttest-cgi <node> <file> = Receive output of CGI script [all files].
|
---|
[10567] | 1450 | \tlist <status> <items> = List systems which have certain status
|
---|
[10563] | 1451 |
|
---|
[10567] | 1452 | Arguments:
|
---|
| 1453 | \t<node> = NodeName (example: HybridRick)
|
---|
| 1454 | \t<file> = %(files)s
|
---|
| 1455 | \t<status> = all|up|down|planned
|
---|
| 1456 | \t<items> = systems|nodes|proxies
|
---|
| 1457 |
|
---|
[10563] | 1458 | NOTE FOR DEVELOPERS; you can test your changes like this:
|
---|
| 1459 | BEFORE any changes in this code:
|
---|
| 1460 | $ ./gformat.py static /tmp/pre
|
---|
| 1461 | AFTER the changes:
|
---|
| 1462 | $ ./gformat.py static /tmp/post
|
---|
| 1463 | VIEW differences and VERIFY all are OK:
|
---|
[10564] | 1464 | $ diff -urI 'Generated' -r /tmp/pre /tmp/post
|
---|
[10567] | 1465 | """ % { 'prog' : sys.argv[0], 'files' : '|'.join(files) }
|
---|
[8259] | 1466 | exit(0)
|
---|
| 1467 |
|
---|
| 1468 |
|
---|
[11426] | 1469 | def is_text_request(environ=os.environ):
|
---|
[10107] | 1470 | """ Find out whether we are calling from the CLI or any text based CLI utility """
|
---|
| 1471 | try:
|
---|
[11426] | 1472 | return environ['HTTP_USER_AGENT'].split()[0] in ['curl', 'fetch', 'wget']
|
---|
[10107] | 1473 | except KeyError:
|
---|
| 1474 | return True
|
---|
[8259] | 1475 |
|
---|
[10547] | 1476 | def switchFormat(setting):
|
---|
| 1477 | if setting:
|
---|
| 1478 | return "YES"
|
---|
| 1479 | else:
|
---|
| 1480 | return "NO"
|
---|
| 1481 |
|
---|
[10885] | 1482 | def rlinput(prompt, prefill=''):
|
---|
| 1483 | import readline
|
---|
| 1484 | readline.set_startup_hook(lambda: readline.insert_text(prefill))
|
---|
| 1485 | try:
|
---|
| 1486 | return raw_input(prompt)
|
---|
| 1487 | finally:
|
---|
| 1488 | readline.set_startup_hook()
|
---|
| 1489 |
|
---|
| 1490 | def fix_conflict(left, right, default='i'):
|
---|
| 1491 | while True:
|
---|
| 1492 | print "## %-30s | %-30s" % (left, right)
|
---|
| 1493 | c = raw_input("## Solve Conflict (h for help) <l|r|e|i|> [%s]: " % default)
|
---|
| 1494 | if not c:
|
---|
| 1495 | c = default
|
---|
| 1496 |
|
---|
| 1497 | if c in ['l','1']:
|
---|
| 1498 | return left
|
---|
| 1499 | elif c in ['r','2']:
|
---|
| 1500 | return right
|
---|
| 1501 | elif c in ['e', '3']:
|
---|
| 1502 | return rlinput("Edit: ", "%30s | %30s" % (left, right))
|
---|
| 1503 | elif c in ['i', '4']:
|
---|
| 1504 | return None
|
---|
| 1505 | else:
|
---|
| 1506 | print "#ERROR: '%s' is invalid input (left, right, edit or ignore)!" % c
|
---|
| 1507 |
|
---|
[11427] | 1508 |
|
---|
| 1509 |
|
---|
| 1510 | def print_cgi_response(response_headers, output):
|
---|
| 1511 | """Could we not use some kind of wsgi wrapper to make this output?"""
|
---|
| 1512 | for header in response_headers:
|
---|
| 1513 | print "%s: %s" % header
|
---|
[11444] | 1514 | print
|
---|
[11427] | 1515 | print output
|
---|
| 1516 |
|
---|
| 1517 |
|
---|
[11534] | 1518 | def fill_cache():
|
---|
| 1519 | ''' Poor man re-loading of few cache items (the slow ones) '''
|
---|
| 1520 | for host in get_hostlist():
|
---|
[11535] | 1521 | get_yaml(host)
|
---|
[11427] | 1522 |
|
---|
[11534] | 1523 |
|
---|
| 1524 | def reload_cache():
|
---|
| 1525 | clear_cache()
|
---|
| 1526 | fill_cache()
|
---|
| 1527 |
|
---|
| 1528 |
|
---|
[8267] | 1529 | def main():
|
---|
| 1530 | """Hard working sub"""
|
---|
| 1531 | # Allow easy hacking using the CLI
|
---|
| 1532 | if not os.environ.has_key('PATH_INFO'):
|
---|
| 1533 | if len(sys.argv) < 2:
|
---|
| 1534 | usage()
|
---|
[9283] | 1535 |
|
---|
[8267] | 1536 | if sys.argv[1] == "standalone":
|
---|
| 1537 | import SocketServer
|
---|
| 1538 | import CGIHTTPServer
|
---|
[10105] | 1539 | # Hop to the right working directory.
|
---|
| 1540 | os.chdir(os.path.dirname(__file__))
|
---|
[8267] | 1541 | try:
|
---|
| 1542 | PORT = int(sys.argv[2])
|
---|
| 1543 | except (IndexError,ValueError):
|
---|
| 1544 | PORT = 8000
|
---|
[9283] | 1545 |
|
---|
[8267] | 1546 | class MyCGIHTTPRequestHandler(CGIHTTPServer.CGIHTTPRequestHandler):
|
---|
| 1547 | """ Serve this CGI from the root of the webserver """
|
---|
| 1548 | def is_cgi(self):
|
---|
| 1549 | if "favicon" in self.path:
|
---|
| 1550 | return False
|
---|
[9283] | 1551 |
|
---|
[10364] | 1552 | self.cgi_info = (os.path.basename(__file__), self.path)
|
---|
[8267] | 1553 | self.path = ''
|
---|
| 1554 | return True
|
---|
| 1555 | handler = MyCGIHTTPRequestHandler
|
---|
[9807] | 1556 | SocketServer.TCPServer.allow_reuse_address = True
|
---|
[8267] | 1557 | httpd = SocketServer.TCPServer(("", PORT), handler)
|
---|
| 1558 | httpd.server_name = 'localhost'
|
---|
| 1559 | httpd.server_port = PORT
|
---|
[9283] | 1560 |
|
---|
[9728] | 1561 | logger.info("serving at port %s", PORT)
|
---|
[8860] | 1562 | try:
|
---|
| 1563 | httpd.serve_forever()
|
---|
| 1564 | except KeyboardInterrupt:
|
---|
| 1565 | httpd.shutdown()
|
---|
[9728] | 1566 | logger.info("All done goodbye")
|
---|
[8267] | 1567 | elif sys.argv[1] == "test":
|
---|
[10872] | 1568 | # Basic argument validation
|
---|
| 1569 | try:
|
---|
| 1570 | node = sys.argv[2]
|
---|
| 1571 | datadump = get_yaml(node)
|
---|
| 1572 | except IndexError:
|
---|
| 1573 | print "Invalid argument"
|
---|
| 1574 | exit(1)
|
---|
| 1575 | except IOError as e:
|
---|
| 1576 | print e
|
---|
| 1577 | exit(1)
|
---|
| 1578 |
|
---|
| 1579 |
|
---|
| 1580 | # Get files to generate
|
---|
| 1581 | gen_files = sys.argv[3:] if len(sys.argv) > 3 else files
|
---|
| 1582 |
|
---|
| 1583 | # Actual config generation
|
---|
| 1584 | for config in gen_files:
|
---|
| 1585 | logger.info("## Generating %s %s", node, config)
|
---|
| 1586 | print generate_config(node, config, datadump)
|
---|
| 1587 | elif sys.argv[1] == "test-cgi":
|
---|
[8267] | 1588 | os.environ['PATH_INFO'] = "/".join(sys.argv[2:])
|
---|
| 1589 | os.environ['SCRIPT_NAME'] = __file__
|
---|
[11427] | 1590 | response_headers, output = process_cgi_request()
|
---|
| 1591 | print_cgi_response(response_headers, output)
|
---|
[8296] | 1592 | elif sys.argv[1] == "static":
|
---|
| 1593 | items = dict()
|
---|
[10563] | 1594 | items['output_dir'] = sys.argv[2] if len(sys.argv) > 2 else "./static"
|
---|
[8296] | 1595 | for node in get_hostlist():
|
---|
| 1596 | items['node'] = node
|
---|
[10563] | 1597 | items['wdir'] = "%(output_dir)s/%(node)s" % items
|
---|
[8296] | 1598 | if not os.path.isdir(items['wdir']):
|
---|
| 1599 | os.makedirs(items['wdir'])
|
---|
[8298] | 1600 | datadump = get_yaml(node)
|
---|
[8296] | 1601 | for config in files:
|
---|
| 1602 | items['config'] = config
|
---|
[9728] | 1603 | logger.info("## Generating %(node)s %(config)s" % items)
|
---|
[8296] | 1604 | f = open("%(wdir)s/%(config)s" % items, "w")
|
---|
[8298] | 1605 | f.write(generate_config(node, config, datadump))
|
---|
[8296] | 1606 | f.close()
|
---|
[9514] | 1607 | elif sys.argv[1] == "wind-export":
|
---|
| 1608 | items = dict()
|
---|
| 1609 | for node in get_hostlist():
|
---|
| 1610 | datadump = get_yaml(node)
|
---|
| 1611 | sql = """INSERT IGNORE INTO nodes (name, name_ns, longitude, latitude)
|
---|
| 1612 | VALUES ('%(nodename)s', '%(nodename)s', %(latitude)s, %(longitude)s);""" % datadump;
|
---|
| 1613 | sql = """INSERT IGNORE INTO users_nodes (user_id, node_id, owner)
|
---|
| 1614 | VALUES (
|
---|
| 1615 | (SELECT id FROM users WHERE username = 'rvdzwet'),
|
---|
| 1616 | (SELECT id FROM nodes WHERE name = '%(nodename)s'),
|
---|
| 1617 | 'Y');""" % datadump
|
---|
| 1618 | #for config in files:
|
---|
| 1619 | # items['config'] = config
|
---|
| 1620 | # print "## Generating %(node)s %(config)s" % items
|
---|
| 1621 | # f = open("%(wdir)s/%(config)s" % items, "w")
|
---|
| 1622 | # f.write(generate_config(node, config, datadump))
|
---|
| 1623 | # f.close()
|
---|
| 1624 | for node in get_hostlist():
|
---|
| 1625 | datadump = get_yaml(node)
|
---|
| 1626 | for iface_key in sorted([elem for elem in datadump.keys() if elem.startswith('iface_')]):
|
---|
| 1627 | ifacedump = datadump[iface_key]
|
---|
| 1628 | if ifacedump.has_key('mode') and ifacedump['mode'] == 'ap-wds':
|
---|
| 1629 | ifacedump['nodename'] = datadump['nodename']
|
---|
| 1630 | if not ifacedump.has_key('channel') or not ifacedump['channel']:
|
---|
| 1631 | ifacedump['channel'] = 0
|
---|
| 1632 | sql = """INSERT INTO links (node_id, type, ssid, protocol, channel, status)
|
---|
| 1633 | VALUES ((SELECT id FROM nodes WHERE name = '%(nodename)s'), 'ap',
|
---|
| 1634 | '%(ssid)s', 'IEEE 802.11b', %(channel)s, 'active');""" % ifacedump
|
---|
[11326] | 1635 | elif sys.argv[1] == "nagios-export":
|
---|
| 1636 | try:
|
---|
| 1637 | heavy_load = (sys.argv[2] == "--heavy-load")
|
---|
| 1638 | except IndexError:
|
---|
| 1639 | heavy_load = False
|
---|
| 1640 |
|
---|
| 1641 | hostgroup_details = {
|
---|
| 1642 | 'wleiden' : 'Stichting Wireless Leiden - FreeBSD Nodes',
|
---|
| 1643 | 'wzoeterwoude' : 'Stichting Wireless Leiden - Afdeling Zoeterwoude - Free-WiFi Project',
|
---|
| 1644 | 'walphen' : 'Stichting Wireless Alphen',
|
---|
| 1645 | 'westeinder' : 'WestEinder Plassen',
|
---|
| 1646 | }
|
---|
| 1647 |
|
---|
| 1648 | params = {
|
---|
| 1649 | 'check_interval' : 5 if heavy_load else 60,
|
---|
| 1650 | 'retry_interval' : 1 if heavy_load else 5,
|
---|
| 1651 | 'max_check_attempts' : 10 if heavy_load else 3,
|
---|
| 1652 | }
|
---|
| 1653 |
|
---|
| 1654 | print '''\
|
---|
| 1655 | define host {
|
---|
| 1656 | name wleiden-node ; Default Node Template
|
---|
| 1657 | use generic-host ; Use the standard template as initial starting point
|
---|
| 1658 | check_period 24x7 ; By default, FreeBSD hosts are checked round the clock
|
---|
| 1659 | check_interval %(check_interval)s ; Actively check the host every 5 minutes
|
---|
| 1660 | retry_interval %(retry_interval)s ; Schedule host check retries at 1 minute intervals
|
---|
| 1661 | max_check_attempts %(max_check_attempts)s ; Check each FreeBSD host 10 times (max)
|
---|
| 1662 | register 0 ; DONT REGISTER THIS DEFINITION - ITS NOT A REAL HOST, JUST A TEMPLATE!
|
---|
| 1663 | }
|
---|
| 1664 |
|
---|
| 1665 | define service {
|
---|
| 1666 | name wleiden-service ; Default Service Template
|
---|
| 1667 | use generic-service ; Use the standard template as initial starting point
|
---|
| 1668 | check_period 24x7 ; By default, FreeBSD hosts are checked round the clock
|
---|
| 1669 | check_interval %(check_interval)s ; Actively check the host every 5 minutes
|
---|
| 1670 | retry_interval %(retry_interval)s ; Schedule host check retries at 1 minute intervals
|
---|
| 1671 | max_check_attempts %(max_check_attempts)s ; Check each FreeBSD host 10 times (max)
|
---|
| 1672 | register 0 ; DONT REGISTER THIS DEFINITION - ITS NOT A REAL HOST, JUST A TEMPLATE!
|
---|
| 1673 | }
|
---|
| 1674 |
|
---|
| 1675 | # Please make sure to install:
|
---|
| 1676 | # make -C /usr/ports/net-mgmt/nagios-check_netsnmp install clean
|
---|
| 1677 | #
|
---|
| 1678 | define command{
|
---|
| 1679 | command_name check_netsnmp_disk
|
---|
| 1680 | command_line $USER1$/check_netsnmp -H $HOSTADDRESS$ -o disk
|
---|
| 1681 | }
|
---|
| 1682 |
|
---|
| 1683 | define command{
|
---|
| 1684 | command_name check_netsnmp_load
|
---|
| 1685 | command_line $USER1$/check_netsnmp -H $HOSTADDRESS$ -o load
|
---|
| 1686 | }
|
---|
| 1687 |
|
---|
| 1688 | define command{
|
---|
| 1689 | command_name check_netsnmp_proc
|
---|
| 1690 | command_line $USER1$/check_netsnmp -H $HOSTADDRESS$ -o proc
|
---|
| 1691 | }
|
---|
| 1692 |
|
---|
| 1693 | # TDB: dhcp leases
|
---|
| 1694 | # /usr/local/libexec/nagios/check_netsnmp -H 192.168.178.47 --oid 1 exec
|
---|
| 1695 |
|
---|
| 1696 | # TDB: internet status
|
---|
| 1697 | # /usr/local/libexec/nagios/check_netsnmp -H 192.168.178.47 --oid 1 file
|
---|
| 1698 |
|
---|
| 1699 | # TDB: Advanced local passive checks
|
---|
| 1700 | # /usr/local/libexec/nagios/check_by_ssh
|
---|
| 1701 | ''' % params
|
---|
| 1702 |
|
---|
| 1703 | print '''\
|
---|
| 1704 | # Service Group, not displayed by default
|
---|
| 1705 | define hostgroup {
|
---|
| 1706 | hostgroup_name srv_hybrid
|
---|
| 1707 | alias All Hybrid Nodes
|
---|
| 1708 | register 0
|
---|
| 1709 | }
|
---|
| 1710 |
|
---|
| 1711 | define service {
|
---|
| 1712 | use wleiden-service
|
---|
| 1713 | hostgroup_name srv_hybrid
|
---|
| 1714 | service_description SSH
|
---|
| 1715 | check_command check_ssh
|
---|
| 1716 | }
|
---|
| 1717 |
|
---|
| 1718 | define service {
|
---|
| 1719 | use wleiden-service
|
---|
| 1720 | hostgroup_name srv_hybrid
|
---|
| 1721 | service_description HTTP
|
---|
| 1722 | check_command check_http
|
---|
| 1723 | }
|
---|
| 1724 |
|
---|
| 1725 | define service {
|
---|
| 1726 | use wleiden-service
|
---|
| 1727 | hostgroup_name srv_hybrid
|
---|
| 1728 | service_description DNS
|
---|
| 1729 | check_command check_dns
|
---|
| 1730 | }
|
---|
| 1731 |
|
---|
| 1732 | # TDB: Can only test this if we have the proxy listening to all addresses.
|
---|
| 1733 | # define service {
|
---|
| 1734 | # use wleiden-service
|
---|
| 1735 | # hostgroup_name srv_hybrid
|
---|
| 1736 | # service_description PROXY
|
---|
| 1737 | # check_command check_tcp!3128
|
---|
| 1738 | # }
|
---|
| 1739 | '''
|
---|
| 1740 |
|
---|
| 1741 | if heavy_load:
|
---|
| 1742 | print '''\
|
---|
| 1743 | define service {
|
---|
| 1744 | use wleiden-service
|
---|
| 1745 | hostgroup_name srv_hybrid
|
---|
| 1746 | service_description SNMP
|
---|
| 1747 | check_command check_snmp
|
---|
| 1748 | }
|
---|
| 1749 |
|
---|
| 1750 | define service {
|
---|
| 1751 | use wleiden-service
|
---|
| 1752 | hostgroup_name srv_hybrid
|
---|
| 1753 | service_description NTP
|
---|
| 1754 | check_command check_ntp_peer
|
---|
| 1755 | }
|
---|
| 1756 |
|
---|
| 1757 | define service {
|
---|
| 1758 | use wleiden-service
|
---|
| 1759 | hostgroup_name srv_hybrid
|
---|
| 1760 | service_description LOAD
|
---|
| 1761 | check_command check_netsnmp_load
|
---|
| 1762 | }
|
---|
| 1763 |
|
---|
| 1764 | define service {
|
---|
| 1765 | use wleiden-service
|
---|
| 1766 | hostgroup_name srv_hybrid
|
---|
| 1767 | service_description PROC
|
---|
| 1768 | check_command check_netsnmp_proc
|
---|
| 1769 | }
|
---|
| 1770 |
|
---|
| 1771 | define service {
|
---|
| 1772 | use wleiden-service
|
---|
| 1773 | hostgroup_name srv_hybrid
|
---|
| 1774 | service_description DISK
|
---|
| 1775 | check_command check_netsnmp_disk
|
---|
| 1776 | }
|
---|
| 1777 | '''
|
---|
| 1778 | for node in get_hostlist():
|
---|
| 1779 | datadump = get_yaml(node)
|
---|
| 1780 | if not datadump['status'] == 'up':
|
---|
| 1781 | continue
|
---|
| 1782 | if not hostgroup_details.has_key(datadump['monitoring_group']):
|
---|
| 1783 | hostgroup_details[datadump['monitoring_group']] = datadump['monitoring_group']
|
---|
| 1784 | print '''\
|
---|
| 1785 | define host {
|
---|
| 1786 | use wleiden-node
|
---|
| 1787 | host_name %(autogen_fqdn)s
|
---|
| 1788 | address %(masterip)s
|
---|
| 1789 | hostgroups srv_hybrid,%(monitoring_group)s
|
---|
| 1790 | }
|
---|
| 1791 | ''' % datadump
|
---|
| 1792 |
|
---|
| 1793 | for name,alias in hostgroup_details.iteritems():
|
---|
| 1794 | print '''\
|
---|
| 1795 | define hostgroup {
|
---|
| 1796 | hostgroup_name %s
|
---|
| 1797 | alias %s
|
---|
| 1798 | } ''' % (name, alias)
|
---|
| 1799 |
|
---|
| 1800 |
|
---|
[9589] | 1801 | elif sys.argv[1] == "full-export":
|
---|
| 1802 | hosts = {}
|
---|
| 1803 | for node in get_hostlist():
|
---|
| 1804 | datadump = get_yaml(node)
|
---|
| 1805 | hosts[datadump['nodename']] = datadump
|
---|
| 1806 | print yaml.dump(hosts)
|
---|
| 1807 |
|
---|
[8584] | 1808 | elif sys.argv[1] == "dns":
|
---|
[10264] | 1809 | make_dns(sys.argv[2] if len(sys.argv) > 2 else 'dns', 'external' in sys.argv)
|
---|
[9283] | 1810 | elif sys.argv[1] == "cleanup":
|
---|
[8588] | 1811 | # First generate all datadumps
|
---|
| 1812 | datadumps = dict()
|
---|
[10729] | 1813 | ssid_to_node = dict()
|
---|
[8588] | 1814 | for host in get_hostlist():
|
---|
[9728] | 1815 | logger.info("# Processing: %s", host)
|
---|
[10436] | 1816 | # Set some boring default values
|
---|
| 1817 | datadump = { 'board' : 'UNKNOWN' }
|
---|
| 1818 | datadump.update(get_yaml(host))
|
---|
[10391] | 1819 | datadumps[datadump['autogen_realname']] = datadump
|
---|
[9283] | 1820 |
|
---|
[10729] | 1821 | (poel, errors) = make_relations(datadumps)
|
---|
| 1822 | print "\n".join(["# WARNING: %s" % x for x in errors])
|
---|
[10455] | 1823 |
|
---|
[10156] | 1824 | for host,datadump in datadumps.iteritems():
|
---|
[10881] | 1825 | try:
|
---|
| 1826 | # Convert all yes and no to boolean values
|
---|
| 1827 | def fix_boolean(dump):
|
---|
| 1828 | for key in dump.keys():
|
---|
| 1829 | if type(dump[key]) == dict:
|
---|
| 1830 | dump[key] = fix_boolean(dump[key])
|
---|
| 1831 | elif str(dump[key]).lower() in ["yes", "true"]:
|
---|
| 1832 | dump[key] = True
|
---|
| 1833 | elif str(dump[key]).lower() in ["no", "false"]:
|
---|
| 1834 | # Compass richting no (Noord Oost) is valid input
|
---|
| 1835 | if key != "compass": dump[key] = False
|
---|
| 1836 | return dump
|
---|
| 1837 | datadump = fix_boolean(datadump)
|
---|
[10455] | 1838 |
|
---|
[10881] | 1839 | if datadump['rdnap_x'] and datadump['rdnap_y']:
|
---|
[12473] | 1840 | datadump['latitude'], datadump['longitude'] = map(lambda x: "%.5f" % x, rd2etrs(datadump['rdnap_x'], datadump['rdnap_y']))
|
---|
[10881] | 1841 | elif datadump['latitude'] and datadump['longitude']:
|
---|
[12473] | 1842 | datadump['rdnap_x'], datadump['rdnap_y'] = etrs2rd(datadump['latitude'], datadump['longitude'])
|
---|
[10400] | 1843 |
|
---|
[10881] | 1844 | if datadump['nodename'].startswith('Proxy'):
|
---|
| 1845 | datadump['nodename'] = datadump['nodename'].lower()
|
---|
[10319] | 1846 |
|
---|
[10881] | 1847 | for iface_key in datadump['autogen_iface_keys']:
|
---|
[10889] | 1848 | try:
|
---|
| 1849 | # All our normal wireless cards are normal APs now
|
---|
| 1850 | if datadump[iface_key]['type'] in ['11a', '11b', '11g', 'wireless']:
|
---|
| 1851 | datadump[iface_key]['mode'] = 'ap'
|
---|
| 1852 | # Wireless Leiden SSID have an consistent lowercase/uppercase
|
---|
| 1853 | if datadump[iface_key].has_key('ssid'):
|
---|
| 1854 | ssid = datadump[iface_key]['ssid']
|
---|
| 1855 | prefix = 'ap-WirelessLeiden-'
|
---|
| 1856 | if ssid.lower().startswith(prefix.lower()):
|
---|
| 1857 | datadump[iface_key]['ssid'] = prefix + ssid[len(prefix)].upper() + ssid[len(prefix) + 1:]
|
---|
| 1858 | if datadump[iface_key].has_key('ns_ip') and not datadump[iface_key].has_key('mode'):
|
---|
| 1859 | datadump[iface_key]['mode'] = 'autogen-FIXME'
|
---|
| 1860 | if not datadump[iface_key].has_key('comment'):
|
---|
| 1861 | datadump[iface_key]['comment'] = 'autogen-FIXME'
|
---|
[10882] | 1862 |
|
---|
[11732] | 1863 | if datadump[iface_key].has_key('ns_mac'):
|
---|
| 1864 | datadump[iface_key]['ns_mac'] = datadump[iface_key]['ns_mac'].lower()
|
---|
| 1865 |
|
---|
[10889] | 1866 | if datadump[iface_key]['comment'].startswith('autogen-') and datadump[iface_key].has_key('comment'):
|
---|
| 1867 | datadump[iface_key] = datadump[iface_key]['desc']
|
---|
[10882] | 1868 |
|
---|
[11738] | 1869 | # We are not using 802.11b anymore. OFDM is preferred over DSSS
|
---|
| 1870 | # due to better collision avoidance.
|
---|
| 1871 | if datadump[iface_key]['type'] == '11b':
|
---|
| 1872 | datadump[iface_key]['type'] = '11g'
|
---|
| 1873 |
|
---|
| 1874 | # Setting 802.11g channels to de-facto standards, to avoid
|
---|
| 1875 | # un-detected sharing with other overlapping channels
|
---|
| 1876 | #
|
---|
| 1877 | # Technically we could also use channel 13 in NL, but this is not
|
---|
| 1878 | # recommended as foreign devices might not be able to select this
|
---|
| 1879 | # channel. Secondly using 1,5,9,13 instead is going to clash with
|
---|
| 1880 | # the de-facto usage of 1,6,11.
|
---|
| 1881 | #
|
---|
| 1882 | # See: https://en.wikipedia.org/wiki/List_of_WLAN_channels
|
---|
| 1883 | channels_at_2400Mhz = (1,6,11)
|
---|
| 1884 | if datadump[iface_key]['type'] == '11g' and datadump[iface_key].has_key('channel'):
|
---|
| 1885 | datadump[iface_key]['channel'] = int(datadump[iface_key]['channel'])
|
---|
| 1886 | if datadump[iface_key]['channel'] not in channels_at_2400Mhz:
|
---|
| 1887 | datadump[iface_key]['channel'] = random.choice(channels_at_2400Mhz)
|
---|
| 1888 |
|
---|
[11555] | 1889 | # Mandatory interface keys
|
---|
| 1890 | if not datadump[iface_key].has_key('status'):
|
---|
| 1891 | datadump[iface_key]['status'] = 'planned'
|
---|
| 1892 |
|
---|
[10889] | 1893 | x = datadump[iface_key]['comment']
|
---|
| 1894 | datadump[iface_key]['comment'] = x[0].upper() + x[1:]
|
---|
| 1895 |
|
---|
[10884] | 1896 |
|
---|
[10889] | 1897 | if datadump[iface_key].has_key('desc'):
|
---|
| 1898 | if datadump[iface_key]['comment'].lower() == datadump[iface_key]['desc'].lower():
|
---|
[10885] | 1899 | del datadump[iface_key]['desc']
|
---|
[10889] | 1900 | else:
|
---|
| 1901 | print "# ERROR: At %s - %s" % (datadump['nodename'], iface_key)
|
---|
| 1902 | response = fix_conflict(datadump[iface_key]['comment'], datadump[iface_key]['desc'])
|
---|
| 1903 | if response:
|
---|
| 1904 | datadump[iface_key]['comment'] = response
|
---|
| 1905 | del datadump[iface_key]['desc']
|
---|
[10882] | 1906 |
|
---|
[10889] | 1907 | # Check DHCP configuration
|
---|
| 1908 | dhcp_type(datadump[iface_key])
|
---|
| 1909 |
|
---|
| 1910 | # Set the compass value based on the angle between the poels
|
---|
| 1911 | if datadump[iface_key].has_key('ns_ip'):
|
---|
| 1912 | my_pool = poel[network(datadump[iface_key]['ip'])]
|
---|
| 1913 | remote_hosts = list(set([x[0] for x in my_pool]) - set([host]))
|
---|
| 1914 | if remote_hosts:
|
---|
| 1915 | compass_target = remote_hosts[0]
|
---|
| 1916 | datadump[iface_key]['compass'] = cd_between_hosts(host, compass_target, datadumps)
|
---|
[12475] | 1917 |
|
---|
| 1918 | # Monitoring Group default
|
---|
| 1919 | if not 'monitoring_group' in datadump:
|
---|
| 1920 | datadump['monitoring_group'] = 'wleiden'
|
---|
| 1921 |
|
---|
[10889] | 1922 | except Exception as e:
|
---|
| 1923 | print "# Error while processing interface %s" % iface_key
|
---|
| 1924 | raise
|
---|
[10881] | 1925 | store_yaml(datadump)
|
---|
| 1926 | except Exception as e:
|
---|
| 1927 | print "# Error while processing %s" % host
|
---|
| 1928 | raise
|
---|
[9971] | 1929 | elif sys.argv[1] == "list":
|
---|
[10611] | 1930 | use_fqdn = False
|
---|
[10567] | 1931 | if len(sys.argv) < 4 or not sys.argv[2] in ["up", "down", "planned", "all"]:
|
---|
| 1932 | usage()
|
---|
| 1933 | if sys.argv[3] == "nodes":
|
---|
[9971] | 1934 | systems = get_nodelist()
|
---|
[10567] | 1935 | elif sys.argv[3] == "proxies":
|
---|
[9971] | 1936 | systems = get_proxylist()
|
---|
[10567] | 1937 | elif sys.argv[3] == "systems":
|
---|
[10270] | 1938 | systems = get_hostlist()
|
---|
[9971] | 1939 | else:
|
---|
| 1940 | usage()
|
---|
[10611] | 1941 | if len(sys.argv) > 4:
|
---|
| 1942 | if sys.argv[4] == "fqdn":
|
---|
| 1943 | use_fqdn = True
|
---|
| 1944 | else:
|
---|
| 1945 | usage()
|
---|
| 1946 |
|
---|
[9971] | 1947 | for system in systems:
|
---|
| 1948 | datadump = get_yaml(system)
|
---|
[10611] | 1949 |
|
---|
| 1950 | output = datadump['autogen_fqdn'] if use_fqdn else system
|
---|
[10567] | 1951 | if sys.argv[2] == "all":
|
---|
[10611] | 1952 | print output
|
---|
[10567] | 1953 | elif datadump['status'] == sys.argv[2]:
|
---|
[10611] | 1954 | print output
|
---|
[10378] | 1955 | elif sys.argv[1] == "create":
|
---|
| 1956 | if sys.argv[2] == "network.kml":
|
---|
| 1957 | print make_network_kml.make_graph()
|
---|
[10998] | 1958 | elif sys.argv[2] == "host-ips.txt":
|
---|
| 1959 | for system in get_hostlist():
|
---|
| 1960 | datadump = get_yaml(system)
|
---|
| 1961 | ips = [datadump['masterip']]
|
---|
| 1962 | for ifkey in datadump['autogen_iface_keys']:
|
---|
| 1963 | ips.append(datadump[ifkey]['ip'].split('/')[0])
|
---|
| 1964 | print system, ' '.join(ips)
|
---|
[10999] | 1965 | elif sys.argv[2] == "host-pos.txt":
|
---|
| 1966 | for system in get_hostlist():
|
---|
| 1967 | datadump = get_yaml(system)
|
---|
| 1968 | print system, datadump['rdnap_x'], datadump['rdnap_y']
|
---|
[12233] | 1969 | elif sys.argv[2] == 'ssh_config':
|
---|
| 1970 | print '''
|
---|
| 1971 | Host *.wleiden.net
|
---|
| 1972 | User root
|
---|
| 1973 |
|
---|
| 1974 | Host 172.16.*.*
|
---|
| 1975 | User root
|
---|
| 1976 | '''
|
---|
| 1977 | for system in get_hostlist():
|
---|
| 1978 | datadump = get_yaml(system)
|
---|
| 1979 | print '''\
|
---|
| 1980 | Host %s
|
---|
| 1981 | User root
|
---|
| 1982 |
|
---|
| 1983 | Host %s
|
---|
| 1984 | User root
|
---|
| 1985 |
|
---|
| 1986 | Host %s
|
---|
| 1987 | User root
|
---|
| 1988 |
|
---|
| 1989 | Host %s
|
---|
| 1990 | User root
|
---|
| 1991 | ''' % (system, system.lower(), datadump['nodename'], datadump['nodename'].lower())
|
---|
[10378] | 1992 | else:
|
---|
[10998] | 1993 | usage()
|
---|
| 1994 | else:
|
---|
[9283] | 1995 | usage()
|
---|
| 1996 | else:
|
---|
[10070] | 1997 | # Do not enable debugging for config requests as it highly clutters the output
|
---|
| 1998 | if not is_text_request():
|
---|
| 1999 | cgitb.enable()
|
---|
[11427] | 2000 | response_headers, output = process_cgi_request()
|
---|
| 2001 | print_cgi_response(response_headers, output)
|
---|
[9283] | 2002 |
|
---|
[11426] | 2003 | def application(environ, start_response):
|
---|
| 2004 | status = '200 OK'
|
---|
| 2005 | response_headers, output = process_cgi_request(environ)
|
---|
| 2006 | start_response(status, response_headers)
|
---|
[9283] | 2007 |
|
---|
[11426] | 2008 | # Debugging only
|
---|
| 2009 | # output = 'wsgi.multithread = %s' % repr(environ['wsgi.multithread'])
|
---|
| 2010 | # soutput += '\nwsgi.multiprocess = %s' % repr(environ['wsgi.multiprocess'])
|
---|
| 2011 | return [output]
|
---|
| 2012 |
|
---|
[9283] | 2013 | if __name__ == "__main__":
|
---|
| 2014 | main()
|
---|