| #! /usr/bin/python |
| |
| # Copyright 2015 Linaro Limited |
| # |
| # This program is free software; you can redistribute it and/or modify |
| # it under the terms of the GNU General Public License as published by |
| # the Free Software Foundation; either version 2 of the License, or |
| # (at your option) any later version. |
| # |
| # This program is distributed in the hope that it will be useful, |
| # but WITHOUT ANY WARRANTY; without even the implied warranty of |
| # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| # GNU General Public License for more details. |
| # |
| # You should have received a copy of the GNU General Public License |
| # along with this program; if not, write to the Free Software |
| # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, |
| # MA 02110-1301, USA. |
| # |
| # Visualisation module for VLANd. Fork a trivial webserver |
| # implementation on an extra, and generate a simple set of pages and |
| # graphics on demand. |
| # |
| |
| import os, sys, logging, time, datetime, re |
| from multiprocessing import Process |
| from BaseHTTPServer import BaseHTTPRequestHandler |
| from BaseHTTPServer import HTTPServer |
| import urlparse |
| |
| if __name__ == '__main__': |
| vlandpath = os.path.abspath(os.path.normpath(os.path.dirname(sys.argv[0]))) |
| sys.path.insert(0, vlandpath) |
| sys.path.insert(0, "%s/.." % vlandpath) |
| |
| from errors import InputError |
| from db.db import VlanDB |
| from config.config import VlanConfig |
| from graphics import Graphics,Switch |
| from util import VlanUtil |
| class VlandHTTPServer(HTTPServer): |
| """ Trivial wrapper for HTTPServer so we can include our own state. """ |
| def __init__(self, server_address, handler, state): |
| HTTPServer.__init__(self, server_address, handler) |
| self.state = state |
| |
| class Visualisation(object): |
| """ Code and config for the visualisation graphics module. """ |
| |
| state = None |
| p = None |
| |
| # Fork a new process for the visualisation webserver |
| def __init__(self, state): |
| self.state = state |
| self.p = Process(target=self.visloop, args=()) |
| self.p.start() |
| |
| # The main loop for the visualisation webserver |
| def visloop(self): |
| self.state.db = VlanDB(db_name=self.state.config.database.dbname, |
| username=self.state.config.database.username) |
| |
| loglevel = VlanUtil().set_logging_level(self.state.config.logging.level) |
| |
| # Should we log to stderr? |
| if self.state.config.logging.filename is None: |
| logging.basicConfig(level = loglevel, |
| format = '%(asctime)s %(levelname)-8s %(message)s') |
| else: |
| logging.basicConfig(level = loglevel, |
| format = '%(asctime)s %(levelname)-8s VIS %(message)s', |
| datefmt = '%Y-%m-%d %H:%M:%S %Z', |
| filename = self.state.config.logging.filename, |
| filemode = 'a') |
| logging.info('%s visualisation starting up', self.state.banner) |
| |
| server = VlandHTTPServer(('localhost', self.state.config.visualisation.port), |
| GetHandler, self.state) |
| server.serve_forever() |
| |
| # Kill the webserver |
| def shutdown(self): |
| self.p.terminate() |
| |
| class GetHandler(BaseHTTPRequestHandler): |
| """ Methods to generate and serve the pages """ |
| |
| parsed_path = None |
| |
| # Trivial top-level page. Link to images for each of the VLANs we |
| # know about. |
| def send_index(self): |
| self.send_response(200) |
| self.wfile.write('Content-type: text/html\r\n') |
| self.end_headers() |
| page = [] |
| page.append('<html>') |
| page.append('<head>') |
| page.append('<TITLE>VLANd visualisation</TITLE>') |
| page.append('</HEAD>') |
| page.append('<body>') |
| page.append('<h1>VLANd visualisation, version %s</h1>' % self.server.state.version) |
| |
| switches = self.server.state.db.all_switches() |
| if len(switches) == 0: |
| page.append('<p>No switches found in the database, nothing to show...</p>') |
| else: |
| vlans = self.server.state.db.all_vlans() |
| page.append('<h2>VLANs currently in use: %d</h2>' % len(vlans)) |
| for vlan in vlans: |
| page.append('<h3>VLAN id %d, tag %d, name %s</h3>' % (vlan.vlan_id, vlan.tag, vlan.name)) |
| page.append('<p><a href="/images/vlan/%d.png"><img src="/images/vlan/%d.png" alt="VLAN %d diagram"></a></p>' % (vlan.vlan_id,vlan.vlan_id,vlan.vlan_id)) |
| |
| page.append('Current time: %s' % datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S UTC")) |
| page.append('</body>') |
| self.wfile.write('\r\n'.join(page)) |
| |
| # Trivial style sheet, TODO! |
| def send_style(self): |
| self.send_response(200) |
| self.wfile.write('Content-type: text/css\r\n') |
| self.end_headers() |
| self.wfile.write('style.css') |
| |
| # Generate a PNG showing the layout of switches/port/trunks for a |
| # specific VLAN |
| def send_graphic(self): |
| vlan_id = 0 |
| vlan_re = re.compile(r'^/images/vlan/(\d+).png$') |
| match = vlan_re.match(self.parsed_path.path) |
| if match: |
| vlan_id = match.group(1) |
| db = self.server.state.db |
| vlan = db.get_vlan_by_id(vlan_id) |
| # We've been asked for a VLAN that doesn't exist |
| if vlan is None: |
| self.send_response(404) |
| self.wfile.write('Content-type: text/html\r\n') |
| self.end_headers() |
| self.wfile.write('404 Not Found') |
| return |
| |
| gim = Graphics() |
| |
| print "Looking at vlan_id %d, tag %d" % (int(vlan_id), int(vlan.tag)) |
| |
| # Pick fonts. TODO: Make these configurable? |
| gim.set_font(['/usr/share/fonts/truetype/inconsolata/Inconsolata.otf', |
| '/usr/share/fonts/truetype/freefont/FreeMono.ttf']) |
| try: |
| gim.font |
| # If we can't get the font we need, fail |
| except NameError: |
| self.send_response(500) |
| self.wfile.write('Content-type: text/html\r\n') |
| self.end_headers() |
| self.wfile.write('500 Internal Server Error') |
| return |
| |
| switch = {} |
| size_x = {} |
| size_y = {} |
| |
| switches = db.all_switches() |
| |
| # Need to set gaps big enough for the number of trunks, at least. |
| trunks = db.all_trunks() |
| y_gap = max(20, 15 * len(trunks)) |
| x_gap = max(20, 15 * len(trunks)) |
| |
| x = 0 |
| y = y_gap |
| |
| # Work out how much space we need for the switches |
| for i in range(0, len(switches)): |
| ports = db.get_ports_by_switch(switches[i].switch_id) |
| switch[i] = Switch(gim, len(ports), switches[i].name) |
| (size_x[i], size_y[i]) = switch[i].get_dimensions() |
| x = max(x, size_x[i]) |
| y += size_y[i] + y_gap |
| |
| # Add space for the legend and the label |
| label = "VLAN %d - %s" % (vlan.tag, vlan.name) |
| (legend_width, legend_height) = gim.get_legend_dimensions() |
| (label_width, label_height) = gim.get_label_size(label, gim.label_font_size) |
| x = max(x, legend_width + 2*x_gap + label_width) |
| x = x_gap + x + x_gap |
| y = y + max(legend_height + y_gap, label_height) |
| |
| # Create a canvas of the right size |
| gim.create_canvas(x, y) |
| |
| # Draw the switches and ports in it |
| curr_y = y_gap |
| for i in range(0, len(switches)): |
| switch[i].draw_switch(gim, x_gap, curr_y) |
| ports = db.get_ports_by_switch(switches[i].switch_id) |
| for port_id in ports: |
| port = db.get_port_by_id(port_id) |
| if port.is_locked: |
| switch[i].draw_port(gim, port.number, 'locked') |
| elif port.is_trunk: |
| switch[i].draw_port(gim, port.number, 'trunk') |
| elif port.current_vlan_id == int(vlan_id): |
| switch[i].draw_port(gim, port.number, 'VLAN') |
| else: |
| switch[i].draw_port(gim, port.number, 'normal') |
| curr_y += size_y[i] + y_gap |
| |
| # Now add the trunks |
| for i in range(0, len(trunks)): |
| ports = db.get_ports_by_trunk(trunks[i].trunk_id) |
| port1 = db.get_port_by_id(ports[0]) |
| port2 = db.get_port_by_id(ports[1]) |
| for s in range(0, len(switches)): |
| if switches[s].switch_id == port1.switch_id: |
| switch1 = s |
| if switches[s].switch_id == port2.switch_id: |
| switch2 = s |
| gim.draw_trunk(i, |
| switch[switch1].get_port_location(port1.number), |
| switch[switch2].get_port_location(port2.number), |
| gim.port_pallette['trunk']['trace']) |
| |
| # And the legend and label |
| gim.draw_legend(x_gap, curr_y) |
| gim.draw_label(x - label_width - 2*x_gap, curr_y, label, int(x_gap / 2)) |
| |
| # All done - send it down the http socket |
| self.send_response(200) |
| self.wfile.write('Content-type: image/png\r\n') |
| self.end_headers() |
| gim.im.writePng(self.wfile) |
| |
| # Implement an HTTP GET handler for the HTTPServer instance |
| def do_GET(self): |
| # Compare the URL path to any of the names we recognise and |
| # call the right generator function if we get a match |
| self.parsed_path = urlparse.urlparse(self.path) |
| for url in self.functionMap: |
| match = re.match(url['re'], self.parsed_path.path) |
| if match: |
| return url['fn'](self) |
| |
| # Fall-through for any files we don't recognise |
| self.send_response(404) |
| self.wfile.write('Content-type: text/html\r\n') |
| self.end_headers() |
| self.wfile.write('404 Not Found') |
| return |
| |
| # Override the BaseHTTPRequestHandler log_message() method so we |
| # can log requests properly |
| def log_message(self, format, *args): |
| """Log an arbitrary message. """ |
| logging.info('%s %s', self.client_address[0], format%args) |
| |
| functionMap = ( |
| {'re': '^/$', 'fn': send_index}, |
| {'re': '^/style.css$', 'fn': send_style}, |
| {'re': '^/images/vlan/(\d+).png$', 'fn': send_graphic} |
| ) |