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