blob: 164db5f735ce4a69f83fcf33c001e957df241439 [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
30
31if __name__ == '__main__':
32 vlandpath = os.path.abspath(os.path.normpath(os.path.dirname(sys.argv[0])))
33 sys.path.insert(0, vlandpath)
34 sys.path.insert(0, "%s/.." % vlandpath)
35
36from errors import InputError
37from db.db import VlanDB
38from config.config import VlanConfig
39from graphics import Graphics,Switch
40from util import VlanUtil
41class VlandHTTPServer(HTTPServer):
42 """ Trivial wrapper for HTTPServer so we can include our own state. """
43 def __init__(self, server_address, handler, state):
44 HTTPServer.__init__(self, server_address, handler)
45 self.state = state
46
47class Visualisation(object):
48 """ Code and config for the visualisation graphics module. """
49
50 state = None
51 p = None
52
53 # Fork a new process for the visualisation webserver
54 def __init__(self, state):
55 self.state = state
56 self.p = Process(target=self.visloop, args=())
57 self.p.start()
58
59 # The main loop for the visualisation webserver
60 def visloop(self):
61 self.state.db = VlanDB(db_name=self.state.config.database.dbname,
62 username=self.state.config.database.username)
63
64 loglevel = VlanUtil().set_logging_level(self.state.config.logging.level)
65
66 # Should we log to stderr?
67 if self.state.config.logging.filename is None:
68 logging.basicConfig(level = loglevel,
69 format = '%(asctime)s %(levelname)-8s %(message)s')
70 else:
71 logging.basicConfig(level = loglevel,
72 format = '%(asctime)s %(levelname)-8s VIS %(message)s',
73 datefmt = '%Y-%m-%d %H:%M:%S %Z',
74 filename = self.state.config.logging.filename,
75 filemode = 'a')
76 logging.info('%s visualisation starting up', self.state.banner)
77
Steve McIntyre86916e42015-09-28 02:39:32 +010078 server = VlandHTTPServer(('', self.state.config.visualisation.port),
Steve McIntyre2454bf02015-09-23 18:33:02 +010079 GetHandler, self.state)
80 server.serve_forever()
81
82 # Kill the webserver
83 def shutdown(self):
84 self.p.terminate()
85
86class GetHandler(BaseHTTPRequestHandler):
87 """ Methods to generate and serve the pages """
88
89 parsed_path = None
90
91 # Trivial top-level page. Link to images for each of the VLANs we
92 # know about.
93 def send_index(self):
94 self.send_response(200)
95 self.wfile.write('Content-type: text/html\r\n')
96 self.end_headers()
Steve McIntyreb0aa4602015-10-08 15:33:28 +010097 config = self.server.state.config.visualisation
Steve McIntyre2454bf02015-09-23 18:33:02 +010098 page = []
99 page.append('<html>')
100 page.append('<head>')
101 page.append('<TITLE>VLANd visualisation</TITLE>')
Steve McIntyreb74ea6b2015-09-24 20:45:31 +0100102 page.append('<link rel="stylesheet" type="text/css" href="style.css">')
Steve McIntyreb0aa4602015-10-08 15:33:28 +0100103 if config.refresh and config.refresh > 0:
104 page.append('<meta http-equiv="refresh" content="%d">' % config.refresh)
Steve McIntyre2454bf02015-09-23 18:33:02 +0100105 page.append('</HEAD>')
106 page.append('<body>')
Steve McIntyre2454bf02015-09-23 18:33:02 +0100107 switches = self.server.state.db.all_switches()
Steve McIntyreb74ea6b2015-09-24 20:45:31 +0100108 vlans = self.server.state.db.all_vlans()
109 page.append('<div class="menu">')
110 if len(switches) > 0:
111 page.append('<h2>Menu</h2>')
112 page.append('<p>VLANs: %d</p>' % len(vlans))
113 page.append('<ul>')
114 for vlan in vlans:
115 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))
116 page.append('</ul>')
117 page.append('<div class="date"><p>Current time: %s</p>' % datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S UTC"))
118 page.append('<p>version %s</p>' % self.server.state.version)
119 page.append('</div>')
120 page.append('</div>')
121
122 page.append('<div class="content">')
123 page.append('<h1>VLANd visualisation</h1>')
124
Steve McIntyre2454bf02015-09-23 18:33:02 +0100125 if len(switches) == 0:
126 page.append('<p>No switches found in the database, nothing to show...</p>')
127 else:
Steve McIntyre2454bf02015-09-23 18:33:02 +0100128 for vlan in vlans:
Steve McIntyreb74ea6b2015-09-24 20:45:31 +0100129 page.append('<a name="vlan%d"></a>' % vlan.vlan_id)
Steve McIntyre2454bf02015-09-23 18:33:02 +0100130 page.append('<h3>VLAN id %d, tag %d, name %s</h3>' % (vlan.vlan_id, vlan.tag, vlan.name))
131 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))
Steve McIntyreb74ea6b2015-09-24 20:45:31 +0100132 page.append('<hr>')
Steve McIntyre2454bf02015-09-23 18:33:02 +0100133
Steve McIntyreb74ea6b2015-09-24 20:45:31 +0100134 page.append('</div>')
Steve McIntyre2454bf02015-09-23 18:33:02 +0100135 page.append('</body>')
136 self.wfile.write('\r\n'.join(page))
137
138 # Trivial style sheet, TODO!
139 def send_style(self):
140 self.send_response(200)
141 self.wfile.write('Content-type: text/css\r\n')
142 self.end_headers()
Steve McIntyreb74ea6b2015-09-24 20:45:31 +0100143 page = []
144 page.append("body {")
145 page.append(" background: white;")
146 page.append(" color: black;")
147 page.append(" font-size: 12pt;")
148 page.append("}")
149 page.append("")
150 page.append(".menu {")
151 page.append(" position:fixed;")
152 page.append(" float:left;")
153 page.append(" font-family: arial, Helvetica, sans-serif;")
154 page.append(" width:20%;")
155 page.append(" height:100%;")
156 page.append(" font-size: 10pt;")
157 page.append(" padding-top: 10px;")
158 page.append("}")
159 page.append("")
160 page.append(".content {")
161 page.append(" padding-top: 10px;")
162 page.append(" width:80%;")
163 page.append(" max-width:80%;")
164 page.append(" margin-left: 21%;")
165 page.append(" margin-top: 50px;")
166 page.append(" height:100%;")
167 page.append("}")
168 page.append("")
169 page.append(".footer {")
170 page.append(" vertical-align: bottom;")
171 page.append(" text-align: left;")
172 page.append("}")
173 page.append("")
174 page.append(".caption {")
175 page.append(" padding-top: 1px;")
176 page.append(" padding-left: 10%;")
177 page.append(" padding-right: 10%;")
178 page.append(" font-size: 8pt;")
179 page.append(" font-style: italic;")
180 page.append(" text-align: center;")
181 page.append("}")
182 page.append("")
183 page.append("td.headline {")
184 page.append(" font-family: arial, Helvetica, sans-serif;")
185 page.append(" font-size: 20pt;")
186 page.append("}")
187 page.append("h1,h2,h3,h4,h5 {")
188 page.append(" font-family: arial, Helvetica, sans-serif;")
189 page.append(" padding-right:3pt;")
190 page.append(" padding-top:2pt;")
191 page.append(" padding-bottom:2pt;")
192 page.append(" margin-top:8pt;")
193 page.append(" margin-bottom:8pt;")
194 page.append(" border-style:none;")
195 page.append(" border-width:thin;")
196 page.append("}")
197 page.append("")
198 page.append("A:link { text-decoration: none; }")
199 page.append("A:visited { text-decoration: none}")
200 page.append("")
201 page.append("h1 { font-size: 18pt; }")
202 page.append("h2 { font-size: 14pt; }")
203 page.append("h3 { font-size: 12pt; }")
204 page.append("h4 { font-size: 10pt; }")
205 page.append("h5 { font-size: 8pt; }")
206 page.append("dl,ul { margin-top: 1pt; text-indent: 0 }")
207 page.append("ol { margin-top: 1pt; text-indent: 0 }")
208 page.append("")
209 page.append("tt,pre {")
210 page.append(" font-family: Lucida Console,Courier New,Courier,monotype;")
211 page.append(" font-size: 10pt;")
212 page.append("}")
213 page.append("")
214 page.append("pre.code {")
215 page.append(" font-family: Lucida Console,Courier New,Courier,monotype;")
216 page.append(" margin-top: 8pt;")
217 page.append(" margin-bottom: 8pt;")
218 page.append(" background-color: #FFFFEE;")
219 page.append(" white-space:pre;")
220 page.append(" border-style:solid;")
221 page.append(" border-width:1pt;")
222 page.append(" border-color:#999999;")
223 page.append(" color:#111111;")
224 page.append(" padding:5px;")
225 page.append("}")
226 page.append("")
227 page.append("div.date {")
228 page.append(" font-size: 8pt;")
229 page.append("}")
230 page.append("")
231 page.append("div.sig {")
232 page.append(" font-size: 8pt;")
233 page.append("}")
234 page.append("")
235 self.wfile.write('\r\n'.join(page))
Steve McIntyre2454bf02015-09-23 18:33:02 +0100236
237 # Generate a PNG showing the layout of switches/port/trunks for a
238 # specific VLAN
239 def send_graphic(self):
240 vlan_id = 0
241 vlan_re = re.compile(r'^/images/vlan/(\d+).png$')
242 match = vlan_re.match(self.parsed_path.path)
243 if match:
244 vlan_id = match.group(1)
245 db = self.server.state.db
246 vlan = db.get_vlan_by_id(vlan_id)
247 # We've been asked for a VLAN that doesn't exist
248 if vlan is None:
249 self.send_response(404)
Steve McIntyre4f584a72015-09-28 02:28:56 +0100250 self.wfile.write('Content-type: text/plain\r\n')
Steve McIntyre2454bf02015-09-23 18:33:02 +0100251 self.end_headers()
Steve McIntyre4f584a72015-09-28 02:28:56 +0100252 self.wfile.write('404 Not Found\r\n')
253 logging.error('VLAN graphic not found - asked for %s', self.parsed_path.path)
Steve McIntyre2454bf02015-09-23 18:33:02 +0100254 return
255
256 gim = Graphics()
257
Steve McIntyre2454bf02015-09-23 18:33:02 +0100258 # Pick fonts. TODO: Make these configurable?
259 gim.set_font(['/usr/share/fonts/truetype/inconsolata/Inconsolata.otf',
260 '/usr/share/fonts/truetype/freefont/FreeMono.ttf'])
261 try:
262 gim.font
263 # If we can't get the font we need, fail
264 except NameError:
265 self.send_response(500)
Steve McIntyre4f584a72015-09-28 02:28:56 +0100266 self.wfile.write('Content-type: text/plain\r\n')
Steve McIntyre2454bf02015-09-23 18:33:02 +0100267 self.end_headers()
Steve McIntyre4f584a72015-09-28 02:28:56 +0100268 self.wfile.write('500 Internal Server Error\r\n')
269 logging.error('Unable to generate graphic, no fonts found - asked for %s',
270 self.parsed_path.path)
Steve McIntyre2454bf02015-09-23 18:33:02 +0100271 return
272
273 switch = {}
274 size_x = {}
275 size_y = {}
276
277 switches = db.all_switches()
278
279 # Need to set gaps big enough for the number of trunks, at least.
280 trunks = db.all_trunks()
281 y_gap = max(20, 15 * len(trunks))
282 x_gap = max(20, 15 * len(trunks))
283
284 x = 0
285 y = y_gap
286
287 # Work out how much space we need for the switches
288 for i in range(0, len(switches)):
289 ports = db.get_ports_by_switch(switches[i].switch_id)
290 switch[i] = Switch(gim, len(ports), switches[i].name)
291 (size_x[i], size_y[i]) = switch[i].get_dimensions()
292 x = max(x, size_x[i])
293 y += size_y[i] + y_gap
294
295 # Add space for the legend and the label
296 label = "VLAN %d - %s" % (vlan.tag, vlan.name)
297 (legend_width, legend_height) = gim.get_legend_dimensions()
298 (label_width, label_height) = gim.get_label_size(label, gim.label_font_size)
299 x = max(x, legend_width + 2*x_gap + label_width)
300 x = x_gap + x + x_gap
301 y = y + max(legend_height + y_gap, label_height)
302
303 # Create a canvas of the right size
304 gim.create_canvas(x, y)
305
306 # Draw the switches and ports in it
307 curr_y = y_gap
308 for i in range(0, len(switches)):
309 switch[i].draw_switch(gim, x_gap, curr_y)
310 ports = db.get_ports_by_switch(switches[i].switch_id)
311 for port_id in ports:
312 port = db.get_port_by_id(port_id)
313 if port.is_locked:
314 switch[i].draw_port(gim, port.number, 'locked')
315 elif port.is_trunk:
316 switch[i].draw_port(gim, port.number, 'trunk')
317 elif port.current_vlan_id == int(vlan_id):
318 switch[i].draw_port(gim, port.number, 'VLAN')
319 else:
320 switch[i].draw_port(gim, port.number, 'normal')
321 curr_y += size_y[i] + y_gap
322
323 # Now add the trunks
324 for i in range(0, len(trunks)):
325 ports = db.get_ports_by_trunk(trunks[i].trunk_id)
326 port1 = db.get_port_by_id(ports[0])
327 port2 = db.get_port_by_id(ports[1])
328 for s in range(0, len(switches)):
329 if switches[s].switch_id == port1.switch_id:
330 switch1 = s
331 if switches[s].switch_id == port2.switch_id:
332 switch2 = s
333 gim.draw_trunk(i,
334 switch[switch1].get_port_location(port1.number),
335 switch[switch2].get_port_location(port2.number),
336 gim.port_pallette['trunk']['trace'])
337
338 # And the legend and label
339 gim.draw_legend(x_gap, curr_y)
340 gim.draw_label(x - label_width - 2*x_gap, curr_y, label, int(x_gap / 2))
341
342 # All done - send it down the http socket
343 self.send_response(200)
344 self.wfile.write('Content-type: image/png\r\n')
345 self.end_headers()
346 gim.im.writePng(self.wfile)
347
348 # Implement an HTTP GET handler for the HTTPServer instance
349 def do_GET(self):
350 # Compare the URL path to any of the names we recognise and
351 # call the right generator function if we get a match
352 self.parsed_path = urlparse.urlparse(self.path)
353 for url in self.functionMap:
354 match = re.match(url['re'], self.parsed_path.path)
355 if match:
356 return url['fn'](self)
357
358 # Fall-through for any files we don't recognise
359 self.send_response(404)
Steve McIntyre4f584a72015-09-28 02:28:56 +0100360 self.wfile.write('Content-type: text/plain\r\n')
Steve McIntyre2454bf02015-09-23 18:33:02 +0100361 self.end_headers()
362 self.wfile.write('404 Not Found')
Steve McIntyre4f584a72015-09-28 02:28:56 +0100363 logging.error('File not supported - asked for %s', self.parsed_path.path)
Steve McIntyre2454bf02015-09-23 18:33:02 +0100364 return
365
366 # Override the BaseHTTPRequestHandler log_message() method so we
367 # can log requests properly
Steve McIntyre9ff96bf2015-09-23 18:54:53 +0100368 def log_message(self, fmt, *args):
Steve McIntyre2454bf02015-09-23 18:33:02 +0100369 """Log an arbitrary message. """
Steve McIntyre9ff96bf2015-09-23 18:54:53 +0100370 logging.info('%s %s', self.client_address[0], fmt%args)
Steve McIntyre2454bf02015-09-23 18:33:02 +0100371
372 functionMap = (
Steve McIntyre9ff96bf2015-09-23 18:54:53 +0100373 {'re': r'^/$', 'fn': send_index},
374 {'re': r'^/style.css$', 'fn': send_style},
375 {'re': r'^/images/vlan/(\d+).png$', 'fn': send_graphic}
Steve McIntyre2454bf02015-09-23 18:33:02 +0100376 )