blob: 5df91633fcd0e29a49a4e13b70f51ba703ca9efa [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
78 server = VlandHTTPServer(('localhost', self.state.config.visualisation.port),
79 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()
97 page = []
98 page.append('<html>')
99 page.append('<head>')
100 page.append('<TITLE>VLANd visualisation</TITLE>')
Steve McIntyreb74ea6b2015-09-24 20:45:31 +0100101 page.append('<link rel="stylesheet" type="text/css" href="style.css">')
Steve McIntyre2454bf02015-09-23 18:33:02 +0100102 page.append('</HEAD>')
103 page.append('<body>')
Steve McIntyre2454bf02015-09-23 18:33:02 +0100104 switches = self.server.state.db.all_switches()
Steve McIntyreb74ea6b2015-09-24 20:45:31 +0100105 vlans = self.server.state.db.all_vlans()
106 page.append('<div class="menu">')
107 if len(switches) > 0:
108 page.append('<h2>Menu</h2>')
109 page.append('<p>VLANs: %d</p>' % len(vlans))
110 page.append('<ul>')
111 for vlan in vlans:
112 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))
113 page.append('</ul>')
114 page.append('<div class="date"><p>Current time: %s</p>' % datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S UTC"))
115 page.append('<p>version %s</p>' % self.server.state.version)
116 page.append('</div>')
117 page.append('</div>')
118
119 page.append('<div class="content">')
120 page.append('<h1>VLANd visualisation</h1>')
121
Steve McIntyre2454bf02015-09-23 18:33:02 +0100122 if len(switches) == 0:
123 page.append('<p>No switches found in the database, nothing to show...</p>')
124 else:
Steve McIntyre2454bf02015-09-23 18:33:02 +0100125 for vlan in vlans:
Steve McIntyreb74ea6b2015-09-24 20:45:31 +0100126 page.append('<a name="vlan%d"></a>' % vlan.vlan_id)
Steve McIntyre2454bf02015-09-23 18:33:02 +0100127 page.append('<h3>VLAN id %d, tag %d, name %s</h3>' % (vlan.vlan_id, vlan.tag, vlan.name))
128 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 +0100129 page.append('<hr>')
Steve McIntyre2454bf02015-09-23 18:33:02 +0100130
Steve McIntyreb74ea6b2015-09-24 20:45:31 +0100131 page.append('</div>')
Steve McIntyre2454bf02015-09-23 18:33:02 +0100132 page.append('</body>')
133 self.wfile.write('\r\n'.join(page))
134
135 # Trivial style sheet, TODO!
136 def send_style(self):
137 self.send_response(200)
138 self.wfile.write('Content-type: text/css\r\n')
139 self.end_headers()
Steve McIntyreb74ea6b2015-09-24 20:45:31 +0100140 page = []
141 page.append("body {")
142 page.append(" background: white;")
143 page.append(" color: black;")
144 page.append(" font-size: 12pt;")
145 page.append("}")
146 page.append("")
147 page.append(".menu {")
148 page.append(" position:fixed;")
149 page.append(" float:left;")
150 page.append(" font-family: arial, Helvetica, sans-serif;")
151 page.append(" width:20%;")
152 page.append(" height:100%;")
153 page.append(" font-size: 10pt;")
154 page.append(" padding-top: 10px;")
155 page.append("}")
156 page.append("")
157 page.append(".content {")
158 page.append(" padding-top: 10px;")
159 page.append(" width:80%;")
160 page.append(" max-width:80%;")
161 page.append(" margin-left: 21%;")
162 page.append(" margin-top: 50px;")
163 page.append(" height:100%;")
164 page.append("}")
165 page.append("")
166 page.append(".footer {")
167 page.append(" vertical-align: bottom;")
168 page.append(" text-align: left;")
169 page.append("}")
170 page.append("")
171 page.append(".caption {")
172 page.append(" padding-top: 1px;")
173 page.append(" padding-left: 10%;")
174 page.append(" padding-right: 10%;")
175 page.append(" font-size: 8pt;")
176 page.append(" font-style: italic;")
177 page.append(" text-align: center;")
178 page.append("}")
179 page.append("")
180 page.append("td.headline {")
181 page.append(" font-family: arial, Helvetica, sans-serif;")
182 page.append(" font-size: 20pt;")
183 page.append("}")
184 page.append("h1,h2,h3,h4,h5 {")
185 page.append(" font-family: arial, Helvetica, sans-serif;")
186 page.append(" padding-right:3pt;")
187 page.append(" padding-top:2pt;")
188 page.append(" padding-bottom:2pt;")
189 page.append(" margin-top:8pt;")
190 page.append(" margin-bottom:8pt;")
191 page.append(" border-style:none;")
192 page.append(" border-width:thin;")
193 page.append("}")
194 page.append("")
195 page.append("A:link { text-decoration: none; }")
196 page.append("A:visited { text-decoration: none}")
197 page.append("")
198 page.append("h1 { font-size: 18pt; }")
199 page.append("h2 { font-size: 14pt; }")
200 page.append("h3 { font-size: 12pt; }")
201 page.append("h4 { font-size: 10pt; }")
202 page.append("h5 { font-size: 8pt; }")
203 page.append("dl,ul { margin-top: 1pt; text-indent: 0 }")
204 page.append("ol { margin-top: 1pt; text-indent: 0 }")
205 page.append("")
206 page.append("tt,pre {")
207 page.append(" font-family: Lucida Console,Courier New,Courier,monotype;")
208 page.append(" font-size: 10pt;")
209 page.append("}")
210 page.append("")
211 page.append("pre.code {")
212 page.append(" font-family: Lucida Console,Courier New,Courier,monotype;")
213 page.append(" margin-top: 8pt;")
214 page.append(" margin-bottom: 8pt;")
215 page.append(" background-color: #FFFFEE;")
216 page.append(" white-space:pre;")
217 page.append(" border-style:solid;")
218 page.append(" border-width:1pt;")
219 page.append(" border-color:#999999;")
220 page.append(" color:#111111;")
221 page.append(" padding:5px;")
222 page.append("}")
223 page.append("")
224 page.append("div.date {")
225 page.append(" font-size: 8pt;")
226 page.append("}")
227 page.append("")
228 page.append("div.sig {")
229 page.append(" font-size: 8pt;")
230 page.append("}")
231 page.append("")
232 self.wfile.write('\r\n'.join(page))
Steve McIntyre2454bf02015-09-23 18:33:02 +0100233
234 # Generate a PNG showing the layout of switches/port/trunks for a
235 # specific VLAN
236 def send_graphic(self):
237 vlan_id = 0
238 vlan_re = re.compile(r'^/images/vlan/(\d+).png$')
239 match = vlan_re.match(self.parsed_path.path)
240 if match:
241 vlan_id = match.group(1)
242 db = self.server.state.db
243 vlan = db.get_vlan_by_id(vlan_id)
244 # We've been asked for a VLAN that doesn't exist
245 if vlan is None:
246 self.send_response(404)
Steve McIntyre4f584a72015-09-28 02:28:56 +0100247 self.wfile.write('Content-type: text/plain\r\n')
Steve McIntyre2454bf02015-09-23 18:33:02 +0100248 self.end_headers()
Steve McIntyre4f584a72015-09-28 02:28:56 +0100249 self.wfile.write('404 Not Found\r\n')
250 logging.error('VLAN graphic not found - asked for %s', self.parsed_path.path)
Steve McIntyre2454bf02015-09-23 18:33:02 +0100251 return
252
253 gim = Graphics()
254
Steve McIntyre2454bf02015-09-23 18:33:02 +0100255 # Pick fonts. TODO: Make these configurable?
256 gim.set_font(['/usr/share/fonts/truetype/inconsolata/Inconsolata.otf',
257 '/usr/share/fonts/truetype/freefont/FreeMono.ttf'])
258 try:
259 gim.font
260 # If we can't get the font we need, fail
261 except NameError:
262 self.send_response(500)
Steve McIntyre4f584a72015-09-28 02:28:56 +0100263 self.wfile.write('Content-type: text/plain\r\n')
Steve McIntyre2454bf02015-09-23 18:33:02 +0100264 self.end_headers()
Steve McIntyre4f584a72015-09-28 02:28:56 +0100265 self.wfile.write('500 Internal Server Error\r\n')
266 logging.error('Unable to generate graphic, no fonts found - asked for %s',
267 self.parsed_path.path)
Steve McIntyre2454bf02015-09-23 18:33:02 +0100268 return
269
270 switch = {}
271 size_x = {}
272 size_y = {}
273
274 switches = db.all_switches()
275
276 # Need to set gaps big enough for the number of trunks, at least.
277 trunks = db.all_trunks()
278 y_gap = max(20, 15 * len(trunks))
279 x_gap = max(20, 15 * len(trunks))
280
281 x = 0
282 y = y_gap
283
284 # Work out how much space we need for the switches
285 for i in range(0, len(switches)):
286 ports = db.get_ports_by_switch(switches[i].switch_id)
287 switch[i] = Switch(gim, len(ports), switches[i].name)
288 (size_x[i], size_y[i]) = switch[i].get_dimensions()
289 x = max(x, size_x[i])
290 y += size_y[i] + y_gap
291
292 # Add space for the legend and the label
293 label = "VLAN %d - %s" % (vlan.tag, vlan.name)
294 (legend_width, legend_height) = gim.get_legend_dimensions()
295 (label_width, label_height) = gim.get_label_size(label, gim.label_font_size)
296 x = max(x, legend_width + 2*x_gap + label_width)
297 x = x_gap + x + x_gap
298 y = y + max(legend_height + y_gap, label_height)
299
300 # Create a canvas of the right size
301 gim.create_canvas(x, y)
302
303 # Draw the switches and ports in it
304 curr_y = y_gap
305 for i in range(0, len(switches)):
306 switch[i].draw_switch(gim, x_gap, curr_y)
307 ports = db.get_ports_by_switch(switches[i].switch_id)
308 for port_id in ports:
309 port = db.get_port_by_id(port_id)
310 if port.is_locked:
311 switch[i].draw_port(gim, port.number, 'locked')
312 elif port.is_trunk:
313 switch[i].draw_port(gim, port.number, 'trunk')
314 elif port.current_vlan_id == int(vlan_id):
315 switch[i].draw_port(gim, port.number, 'VLAN')
316 else:
317 switch[i].draw_port(gim, port.number, 'normal')
318 curr_y += size_y[i] + y_gap
319
320 # Now add the trunks
321 for i in range(0, len(trunks)):
322 ports = db.get_ports_by_trunk(trunks[i].trunk_id)
323 port1 = db.get_port_by_id(ports[0])
324 port2 = db.get_port_by_id(ports[1])
325 for s in range(0, len(switches)):
326 if switches[s].switch_id == port1.switch_id:
327 switch1 = s
328 if switches[s].switch_id == port2.switch_id:
329 switch2 = s
330 gim.draw_trunk(i,
331 switch[switch1].get_port_location(port1.number),
332 switch[switch2].get_port_location(port2.number),
333 gim.port_pallette['trunk']['trace'])
334
335 # And the legend and label
336 gim.draw_legend(x_gap, curr_y)
337 gim.draw_label(x - label_width - 2*x_gap, curr_y, label, int(x_gap / 2))
338
339 # All done - send it down the http socket
340 self.send_response(200)
341 self.wfile.write('Content-type: image/png\r\n')
342 self.end_headers()
343 gim.im.writePng(self.wfile)
344
345 # Implement an HTTP GET handler for the HTTPServer instance
346 def do_GET(self):
347 # Compare the URL path to any of the names we recognise and
348 # call the right generator function if we get a match
349 self.parsed_path = urlparse.urlparse(self.path)
350 for url in self.functionMap:
351 match = re.match(url['re'], self.parsed_path.path)
352 if match:
353 return url['fn'](self)
354
355 # Fall-through for any files we don't recognise
356 self.send_response(404)
Steve McIntyre4f584a72015-09-28 02:28:56 +0100357 self.wfile.write('Content-type: text/plain\r\n')
Steve McIntyre2454bf02015-09-23 18:33:02 +0100358 self.end_headers()
359 self.wfile.write('404 Not Found')
Steve McIntyre4f584a72015-09-28 02:28:56 +0100360 logging.error('File not supported - asked for %s', self.parsed_path.path)
Steve McIntyre2454bf02015-09-23 18:33:02 +0100361 return
362
363 # Override the BaseHTTPRequestHandler log_message() method so we
364 # can log requests properly
Steve McIntyre9ff96bf2015-09-23 18:54:53 +0100365 def log_message(self, fmt, *args):
Steve McIntyre2454bf02015-09-23 18:33:02 +0100366 """Log an arbitrary message. """
Steve McIntyre9ff96bf2015-09-23 18:54:53 +0100367 logging.info('%s %s', self.client_address[0], fmt%args)
Steve McIntyre2454bf02015-09-23 18:33:02 +0100368
369 functionMap = (
Steve McIntyre9ff96bf2015-09-23 18:54:53 +0100370 {'re': r'^/$', 'fn': send_index},
371 {'re': r'^/style.css$', 'fn': send_style},
372 {'re': r'^/images/vlan/(\d+).png$', 'fn': send_graphic}
Steve McIntyre2454bf02015-09-23 18:33:02 +0100373 )