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