blob: 3f3462b090095e48e7b1c6bfdadc941aad0476e4 [file] [log] [blame]
Steve McIntyre2454bf02015-09-23 18:33:02 +01001#! /usr/bin/python
2
3# Copyright 2015 Linaro Limited
4#
5# This program is free software; you can redistribute it and/or modify
6# it under the terms of the GNU General Public License as published by
7# the Free Software Foundation; either version 2 of the License, or
8# (at your option) any later version.
9#
10# This program is distributed in the hope that it will be useful,
11# but WITHOUT ANY WARRANTY; without even the implied warranty of
12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13# GNU General Public License for more details.
14#
15# You should have received a copy of the GNU General Public License
16# along with this program; if not, write to the Free Software
17# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
18# MA 02110-1301, USA.
19#
20# Visualisation module for VLANd. Fork a trivial webserver
21# implementation on an extra, and generate a simple set of pages and
22# graphics on demand.
23#
24
25import os, sys, logging, time, datetime, re
26from multiprocessing import Process
27from BaseHTTPServer import BaseHTTPRequestHandler
28from BaseHTTPServer import HTTPServer
29import urlparse
Steve McIntyre57a9d0a2015-10-28 18:22:31 +000030import cStringIO
Steve McIntyre2454bf02015-09-23 18:33:02 +010031
32if __name__ == '__main__':
33 vlandpath = os.path.abspath(os.path.normpath(os.path.dirname(sys.argv[0])))
34 sys.path.insert(0, vlandpath)
35 sys.path.insert(0, "%s/.." % vlandpath)
36
37from errors import InputError
38from db.db import VlanDB
39from config.config import VlanConfig
40from graphics import Graphics,Switch
41from util import VlanUtil
42class VlandHTTPServer(HTTPServer):
43 """ Trivial wrapper for HTTPServer so we can include our own state. """
44 def __init__(self, server_address, handler, state):
45 HTTPServer.__init__(self, server_address, handler)
46 self.state = state
47
Steve McIntyre57a9d0a2015-10-28 18:22:31 +000048class GraphicsCache(object):
49 """ Cache for graphics state, to avoid having to recalculate every
50 query too many times. """
51 last_update = None
52 max_width = 0
53 graphics = {}
54
55 def __init__(self):
56 # Pick an epoch older than any sensible use
57 self.last_update = datetime.datetime(2000, 01, 01)
58
Steve McIntyre2454bf02015-09-23 18:33:02 +010059class Visualisation(object):
60 """ Code and config for the visualisation graphics module. """
61
62 state = None
63 p = None
64
65 # Fork a new process for the visualisation webserver
66 def __init__(self, state):
67 self.state = state
68 self.p = Process(target=self.visloop, args=())
69 self.p.start()
70
71 # The main loop for the visualisation webserver
72 def visloop(self):
Steve McIntyre57a9d0a2015-10-28 18:22:31 +000073 self.state.cache = GraphicsCache()
Steve McIntyre2454bf02015-09-23 18:33:02 +010074 self.state.db = VlanDB(db_name=self.state.config.database.dbname,
Steve McIntyreea343aa2015-10-23 17:46:17 +010075 username=self.state.config.database.username,
76 readonly=True)
Steve McIntyre2454bf02015-09-23 18:33:02 +010077
78 loglevel = VlanUtil().set_logging_level(self.state.config.logging.level)
79
80 # Should we log to stderr?
81 if self.state.config.logging.filename is None:
82 logging.basicConfig(level = loglevel,
83 format = '%(asctime)s %(levelname)-8s %(message)s')
84 else:
85 logging.basicConfig(level = loglevel,
86 format = '%(asctime)s %(levelname)-8s VIS %(message)s',
87 datefmt = '%Y-%m-%d %H:%M:%S %Z',
88 filename = self.state.config.logging.filename,
89 filemode = 'a')
90 logging.info('%s visualisation starting up', self.state.banner)
91
Steve McIntyre86916e42015-09-28 02:39:32 +010092 server = VlandHTTPServer(('', self.state.config.visualisation.port),
Steve McIntyre2454bf02015-09-23 18:33:02 +010093 GetHandler, self.state)
94 server.serve_forever()
95
96 # Kill the webserver
97 def shutdown(self):
98 self.p.terminate()
99
100class GetHandler(BaseHTTPRequestHandler):
101 """ Methods to generate and serve the pages """
102
103 parsed_path = None
104
105 # Trivial top-level page. Link to images for each of the VLANs we
106 # know about.
107 def send_index(self):
108 self.send_response(200)
109 self.wfile.write('Content-type: text/html\r\n')
110 self.end_headers()
Steve McIntyreb0aa4602015-10-08 15:33:28 +0100111 config = self.server.state.config.visualisation
Steve McIntyre57a9d0a2015-10-28 18:22:31 +0000112 cache = self.server.state.cache
113 db = self.server.state.db
114 switches = db.all_switches()
115 vlans = db.all_vlans()
116 vlan_tags = {}
117
118 for vlan in vlans:
119 vlan_tags[vlan.vlan_id] = vlan.tag
120
121 if cache.last_update < self.server.state.db.get_last_modified_time():
122 logging.debug('Cache is out of date')
123 # Fill the cache with all the information we need:
124 # * the graphics themselves
125 # * the data to match each graphic, so we can generate imagemap/tooltips
126 cache.graphics = {}
127 if len(switches) > 0:
128 for vlan in vlans:
129 cache.graphics[vlan.vlan_id] = self.generate_graphic(vlan.vlan_id)
130 cache.last_update = datetime.datetime.utcnow()
131
Steve McIntyre2454bf02015-09-23 18:33:02 +0100132 page = []
Steve McIntyrede1ee972015-10-28 18:23:05 +0000133 page.append('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">')
Steve McIntyre2454bf02015-09-23 18:33:02 +0100134 page.append('<html>')
135 page.append('<head>')
Steve McIntyrede1ee972015-10-28 18:23:05 +0000136 page.append('<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">')
Steve McIntyre2454bf02015-09-23 18:33:02 +0100137 page.append('<TITLE>VLANd visualisation</TITLE>')
Steve McIntyreb74ea6b2015-09-24 20:45:31 +0100138 page.append('<link rel="stylesheet" type="text/css" href="style.css">')
Steve McIntyreb0aa4602015-10-08 15:33:28 +0100139 if config.refresh and config.refresh > 0:
140 page.append('<meta http-equiv="refresh" content="%d">' % config.refresh)
Steve McIntyre2454bf02015-09-23 18:33:02 +0100141 page.append('</HEAD>')
142 page.append('<body>')
Steve McIntyreb74ea6b2015-09-24 20:45:31 +0100143 page.append('<div class="menu">')
144 if len(switches) > 0:
145 page.append('<h2>Menu</h2>')
146 page.append('<p>VLANs: %d</p>' % len(vlans))
147 page.append('<ul>')
148 for vlan in vlans:
149 page.append('<li><a href="./#vlan%d">VLAN id %d, tag %d<br>(%s)</a>' % (vlan.vlan_id, vlan.vlan_id, vlan.tag, vlan.name))
150 page.append('</ul>')
151 page.append('<div class="date"><p>Current time: %s</p>' % datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S UTC"))
152 page.append('<p>version %s</p>' % self.server.state.version)
153 page.append('</div>')
154 page.append('</div>')
155
156 page.append('<div class="content">')
157 page.append('<h1>VLANd visualisation</h1>')
158
Steve McIntyre2454bf02015-09-23 18:33:02 +0100159 if len(switches) == 0:
160 page.append('<p>No switches found in the database, nothing to show...</p>')
161 else:
Steve McIntyre2454bf02015-09-23 18:33:02 +0100162 for vlan in vlans:
Steve McIntyre57a9d0a2015-10-28 18:22:31 +0000163 this_image = cache.graphics[vlan.vlan_id]
Steve McIntyreb74ea6b2015-09-24 20:45:31 +0100164 page.append('<a name="vlan%d"></a>' % vlan.vlan_id)
Steve McIntyre2454bf02015-09-23 18:33:02 +0100165 page.append('<h3>VLAN id %d, tag %d, name %s</h3>' % (vlan.vlan_id, vlan.tag, vlan.name))
Steve McIntyre57a9d0a2015-10-28 18:22:31 +0000166 page.append('<p><img src="/images/vlan/%d.png" ' % vlan.vlan_id)
167 page.append('width="%d" height="%d" ' % ( this_image['image']['width'], this_image['image']['height']))
168 page.append('alt="VLAN %d diagram" usemap="#MAPVLAN%d">' % (vlan.vlan_id,vlan.vlan_id))
169 page.append('<map name="MAPVLAN%d">' % vlan.vlan_id)
170 for switch in this_image['ports'].keys():
171 for portnum in this_image['ports'][switch].keys():
172 this_port = this_image['ports'][switch][portnum]
173 # Grab the data about the port that we stored
174 # earlier when generating the image
175 port = this_port['db']
176 ((ulx,uly),(lrx,lry),upper) = this_port['location']
177 page.append('<area shape="rect" ')
178 page.append('coords="%d,%d,%d,%d" ' % (ulx,uly,lrx,lry))
179 page.append(' />')
180 page.append('<span>Port id: %d Port number: %d<br>' % (port.port_id, port.number))
181 if port.is_locked:
182 page.append('Locked<br>')
183 if port.is_trunk:
184 page.append('Trunk')
185 if port.trunk_id != -1:
186 page.append(' (trunk id %d)' % port.trunk_id)
187 page.append('<br>')
188 else:
189 page.append('Current VLAN id: %d (tag %d)<br>' % (port.current_vlan_id, vlan_tags[port.current_vlan_id]))
190 page.append('Base VLAN id: %d (tag %d)<br>' % (port.base_vlan_id, vlan_tags[port.base_vlan_id]))
191 page.append('</span>')
192 page.append('</map></p>')
Steve McIntyreb74ea6b2015-09-24 20:45:31 +0100193 page.append('<hr>')
Steve McIntyre2454bf02015-09-23 18:33:02 +0100194
Steve McIntyreb74ea6b2015-09-24 20:45:31 +0100195 page.append('</div>')
Steve McIntyre2454bf02015-09-23 18:33:02 +0100196 page.append('</body>')
197 self.wfile.write('\r\n'.join(page))
198
Steve McIntyre57a9d0a2015-10-28 18:22:31 +0000199 # Simple-ish style sheet
Steve McIntyre2454bf02015-09-23 18:33:02 +0100200 def send_style(self):
201 self.send_response(200)
202 self.wfile.write('Content-type: text/css\r\n')
203 self.end_headers()
Steve McIntyre57a9d0a2015-10-28 18:22:31 +0000204 cache = self.server.state.cache
Steve McIntyreb74ea6b2015-09-24 20:45:31 +0100205 page = []
Steve McIntyre57a9d0a2015-10-28 18:22:31 +0000206 page.append('body {')
207 page.append(' background: white;')
208 page.append(' color: black;')
209 page.append(' font-size: 12pt;')
210 page.append('}')
211 page.append('')
212 page.append('.menu {')
213 page.append(' position:fixed;')
214 page.append(' float:left;')
215 page.append(' font-family: arial, Helvetica, sans-serif;')
216 page.append(' width:20%;')
217 page.append(' height:100%;')
218 page.append(' font-size: 10pt;')
219 page.append(' padding-top: 10px;')
220 page.append('}')
221 page.append('')
222 page.append('.content {')
223 page.append(' position:relative;')
224 page.append(' padding-top: 10px;')
225 page.append(' width: %dpx;' % cache.max_width)
226 page.append(' max-width:80%;')
227 page.append(' margin-left: 21%;')
228 page.append(' margin-top: 50px;')
229 page.append(' height:100%;')
230 page.append('}')
231 page.append('')
232 page.append('.footer {')
233 page.append(' vertical-align: bottom;')
234 page.append(' text-align: left;')
235 page.append('}')
236 page.append('')
237 page.append('.caption {')
238 page.append(' padding-top: 1px;')
239 page.append(' padding-left: 10%;')
240 page.append(' padding-right: 10%;')
241 page.append(' font-size: 8pt;')
242 page.append(' font-style: italic;')
243 page.append(' text-align: center;')
244 page.append('}')
245 page.append('td.headline {')
246 page.append(' font-family: arial, Helvetica, sans-serif;')
247 page.append(' font-size: 20pt;')
248 page.append('}')
249 page.append('h1,h2,h3,h4,h5 {')
250 page.append(' font-family: arial, Helvetica, sans-serif;')
251 page.append(' padding-right:3pt;')
252 page.append(' padding-top:2pt;')
253 page.append(' padding-bottom:2pt;')
254 page.append(' margin-top:8pt;')
255 page.append(' margin-bottom:8pt;')
256 page.append(' border-style:none;')
257 page.append(' border-width:thin;')
258 page.append('}')
259 page.append('A:link { text-decoration: none; }')
260 page.append('A:visited { text-decoration: none}')
261 page.append('h1 { font-size: 18pt; }')
262 page.append('h2 { font-size: 14pt; }')
263 page.append('h3 { font-size: 12pt; }')
264 page.append('h4 { font-size: 10pt; }')
265 page.append('h5 { font-size: 8pt; }')
266 page.append('dl,ul { margin-top: 1pt; text-indent: 0 }')
267 page.append('ol { margin-top: 1pt; text-indent: 0 }')
268 page.append('')
269 page.append('tt,pre {')
270 page.append(' font-family: Lucida Console,Courier New,Courier,monotype;')
271 page.append(' font-size: 10pt;')
272 page.append('}')
273 page.append('pre.code {')
274 page.append(' font-family: Lucida Console,Courier New,Courier,monotype;')
275 page.append(' margin-top: 8pt;')
276 page.append(' margin-bottom: 8pt;')
277 page.append(' background-color: #FFFFEE;')
278 page.append(' white-space:pre;')
279 page.append(' border-style:solid;')
280 page.append(' border-width:1pt;')
281 page.append(' border-color:#999999;')
282 page.append(' color:#111111;')
283 page.append(' padding:5px;')
284 page.append('}')
285 page.append('div.date { font-size: 8pt; }')
286 page.append('div.sig { font-size: 8pt; }')
287 page.append('map { ')
288 page.append(' position: relative;')
289 page.append(' text-indent: 0;')
290 page.append('}')
291 page.append('area + span {')
292 page.append(' position: fixed;')
293 page.append(' margin-left: -9999em;')
294 page.append(' background: #00FFFF;')
295 page.append('}')
296 page.append('area:hover + span {')
297 page.append(' display: block;')
298 page.append(' position: fixed;')
299 page.append(' left: 9999em;')
300 page.append(' bottom: 0px;')
301 page.append(' z-index: 99;')
302 page.append(' background: #FFFF00;')
303 page.append(' border-style:solid;')
304 page.append(' border-width:3pt;')
305 page.append(' border-color: #3B3B3B;')
306 page.append(' margin: 2;')
307 page.append(' width: 300px;')
308 page.append(' padding: 5px;')
309 page.append(' font-size: 10pt;')
310 page.append(' font-family: Courier,monotype;')
311 page.append('}')
Steve McIntyreb74ea6b2015-09-24 20:45:31 +0100312 self.wfile.write('\r\n'.join(page))
Steve McIntyre2454bf02015-09-23 18:33:02 +0100313
Steve McIntyre57a9d0a2015-10-28 18:22:31 +0000314 # Send a graphic from our cache
Steve McIntyre2454bf02015-09-23 18:33:02 +0100315 def send_graphic(self):
316 vlan_id = 0
317 vlan_re = re.compile(r'^/images/vlan/(\d+).png$')
318 match = vlan_re.match(self.parsed_path.path)
319 if match:
Steve McIntyre57a9d0a2015-10-28 18:22:31 +0000320 vlan_id = int(match.group(1))
321 cache = self.server.state.cache
322
323 # Do we have a graphic for this VLAN id?
324 if not vlan_id in cache.graphics.keys():
325 logging.debug('asked for vlan_id %s', vlan_id)
326 logging.debug(cache.graphics.keys())
Steve McIntyre2454bf02015-09-23 18:33:02 +0100327 self.send_response(404)
Steve McIntyre4f584a72015-09-28 02:28:56 +0100328 self.wfile.write('Content-type: text/plain\r\n')
Steve McIntyre2454bf02015-09-23 18:33:02 +0100329 self.end_headers()
Steve McIntyre4f584a72015-09-28 02:28:56 +0100330 self.wfile.write('404 Not Found\r\n')
Steve McIntyre0f561cd2015-10-28 18:05:20 +0000331 self.wfile.write('%s' % self.parsed_path.path)
Steve McIntyre4f584a72015-09-28 02:28:56 +0100332 logging.error('VLAN graphic not found - asked for %s', self.parsed_path.path)
Steve McIntyre2454bf02015-09-23 18:33:02 +0100333 return
334
Steve McIntyre57a9d0a2015-10-28 18:22:31 +0000335 # Yes - just send it from the cache
336 self.send_response(200)
337 self.wfile.write('Content-type: image/png\r\n')
338 self.end_headers()
339 self.wfile.write(cache.graphics[vlan_id]['image']['png'].getvalue())
340 return
341
342 # Generate a PNG showing the layout of switches/port/trunks for a
343 # specific VLAN, and return that PNG along with geometry details
344 def generate_graphic(self, vlan_id):
345 db = self.server.state.db
346 vlan = db.get_vlan_by_id(vlan_id)
347 # We've been asked for a VLAN that doesn't exist
348 if vlan is None:
349 return None
350
351 data = {}
352 data['image'] = {}
353 data['ports'] = {}
354
Steve McIntyre2454bf02015-09-23 18:33:02 +0100355 gim = Graphics()
356
Steve McIntyre2454bf02015-09-23 18:33:02 +0100357 # Pick fonts. TODO: Make these configurable?
358 gim.set_font(['/usr/share/fonts/truetype/inconsolata/Inconsolata.otf',
359 '/usr/share/fonts/truetype/freefont/FreeMono.ttf'])
360 try:
361 gim.font
362 # If we can't get the font we need, fail
363 except NameError:
364 self.send_response(500)
Steve McIntyre4f584a72015-09-28 02:28:56 +0100365 self.wfile.write('Content-type: text/plain\r\n')
Steve McIntyre2454bf02015-09-23 18:33:02 +0100366 self.end_headers()
Steve McIntyre4f584a72015-09-28 02:28:56 +0100367 self.wfile.write('500 Internal Server Error\r\n')
368 logging.error('Unable to generate graphic, no fonts found - asked for %s',
369 self.parsed_path.path)
Steve McIntyre2454bf02015-09-23 18:33:02 +0100370 return
371
372 switch = {}
373 size_x = {}
374 size_y = {}
375
376 switches = db.all_switches()
377
378 # Need to set gaps big enough for the number of trunks, at least.
379 trunks = db.all_trunks()
380 y_gap = max(20, 15 * len(trunks))
381 x_gap = max(20, 15 * len(trunks))
382
383 x = 0
384 y = y_gap
385
386 # Work out how much space we need for the switches
387 for i in range(0, len(switches)):
388 ports = db.get_ports_by_switch(switches[i].switch_id)
389 switch[i] = Switch(gim, len(ports), switches[i].name)
390 (size_x[i], size_y[i]) = switch[i].get_dimensions()
391 x = max(x, size_x[i])
392 y += size_y[i] + y_gap
393
394 # Add space for the legend and the label
395 label = "VLAN %d - %s" % (vlan.tag, vlan.name)
396 (legend_width, legend_height) = gim.get_legend_dimensions()
397 (label_width, label_height) = gim.get_label_size(label, gim.label_font_size)
398 x = max(x, legend_width + 2*x_gap + label_width)
399 x = x_gap + x + x_gap
400 y = y + max(legend_height + y_gap, label_height)
401
402 # Create a canvas of the right size
403 gim.create_canvas(x, y)
404
405 # Draw the switches and ports in it
406 curr_y = y_gap
407 for i in range(0, len(switches)):
408 switch[i].draw_switch(gim, x_gap, curr_y)
409 ports = db.get_ports_by_switch(switches[i].switch_id)
Steve McIntyre57a9d0a2015-10-28 18:22:31 +0000410 data['ports'][i] = {}
Steve McIntyre2454bf02015-09-23 18:33:02 +0100411 for port_id in ports:
412 port = db.get_port_by_id(port_id)
Steve McIntyre57a9d0a2015-10-28 18:22:31 +0000413 port_location = switch[i].get_port_location(port.number)
414 data['ports'][i][port.number] = {}
415 data['ports'][i][port.number]['db'] = port
416 data['ports'][i][port.number]['location'] = port_location
Steve McIntyre2454bf02015-09-23 18:33:02 +0100417 if port.is_locked:
418 switch[i].draw_port(gim, port.number, 'locked')
419 elif port.is_trunk:
420 switch[i].draw_port(gim, port.number, 'trunk')
421 elif port.current_vlan_id == int(vlan_id):
422 switch[i].draw_port(gim, port.number, 'VLAN')
423 else:
424 switch[i].draw_port(gim, port.number, 'normal')
425 curr_y += size_y[i] + y_gap
426
427 # Now add the trunks
428 for i in range(0, len(trunks)):
429 ports = db.get_ports_by_trunk(trunks[i].trunk_id)
430 port1 = db.get_port_by_id(ports[0])
431 port2 = db.get_port_by_id(ports[1])
432 for s in range(0, len(switches)):
433 if switches[s].switch_id == port1.switch_id:
434 switch1 = s
435 if switches[s].switch_id == port2.switch_id:
436 switch2 = s
437 gim.draw_trunk(i,
438 switch[switch1].get_port_location(port1.number),
439 switch[switch2].get_port_location(port2.number),
440 gim.port_pallette['trunk']['trace'])
441
442 # And the legend and label
443 gim.draw_legend(x_gap, curr_y)
444 gim.draw_label(x - label_width - 2*x_gap, curr_y, label, int(x_gap / 2))
445
Steve McIntyre57a9d0a2015-10-28 18:22:31 +0000446 # All done - push the image file into the cache for this vlan
447 data['image']['png'] = cStringIO.StringIO()
448 gim.im.writePng(data['image']['png'])
449 data['image']['width'] = x
450 data['image']['height'] = y
451 return data
Steve McIntyre2454bf02015-09-23 18:33:02 +0100452
453 # Implement an HTTP GET handler for the HTTPServer instance
454 def do_GET(self):
455 # Compare the URL path to any of the names we recognise and
456 # call the right generator function if we get a match
457 self.parsed_path = urlparse.urlparse(self.path)
458 for url in self.functionMap:
459 match = re.match(url['re'], self.parsed_path.path)
460 if match:
461 return url['fn'](self)
462
463 # Fall-through for any files we don't recognise
464 self.send_response(404)
Steve McIntyre4f584a72015-09-28 02:28:56 +0100465 self.wfile.write('Content-type: text/plain\r\n')
Steve McIntyre2454bf02015-09-23 18:33:02 +0100466 self.end_headers()
467 self.wfile.write('404 Not Found')
Steve McIntyre0f561cd2015-10-28 18:05:20 +0000468 self.wfile.write('%s' % self.parsed_path.path)
Steve McIntyre4f584a72015-09-28 02:28:56 +0100469 logging.error('File not supported - asked for %s', self.parsed_path.path)
Steve McIntyre2454bf02015-09-23 18:33:02 +0100470 return
471
472 # Override the BaseHTTPRequestHandler log_message() method so we
473 # can log requests properly
Steve McIntyre9ff96bf2015-09-23 18:54:53 +0100474 def log_message(self, fmt, *args):
Steve McIntyre2454bf02015-09-23 18:33:02 +0100475 """Log an arbitrary message. """
Steve McIntyre9ff96bf2015-09-23 18:54:53 +0100476 logging.info('%s %s', self.client_address[0], fmt%args)
Steve McIntyre2454bf02015-09-23 18:33:02 +0100477
478 functionMap = (
Steve McIntyre9ff96bf2015-09-23 18:54:53 +0100479 {'re': r'^/$', 'fn': send_index},
480 {'re': r'^/style.css$', 'fn': send_style},
481 {'re': r'^/images/vlan/(\d+).png$', 'fn': send_graphic}
Steve McIntyre2454bf02015-09-23 18:33:02 +0100482 )