-
Notifications
You must be signed in to change notification settings - Fork 1
/
httpserver.py
470 lines (440 loc) · 20.6 KB
/
httpserver.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
'''Provides the threaded http handler for the SBCEye project
'''
# pragma pylint: disable=logging-fstring-interpolation,no-self-use
import sys
import os.path
import time
from subprocess import check_output
import re
# HTTP server
import http.server
from urllib.parse import urlparse, parse_qs
from threading import Thread
# Logging
import logging
def serve_http(settings, rrd, data, helpers):
'''Spawns a http.server.HTTPServer in a separate thread on the given port'''
handler = _BaseRequestHandler
httpd = http.server.ThreadingHTTPServer((settings.web_host, settings.web_port), handler, False)
#httpd = http.server.HTTPServer((settings.web_host, settings.web_port), handler, False)
# Block only for 0.5 seconds max
httpd.timeout = 0.5
# HTTPServer sets this as well (left here to make obvious).
httpd.allow_reuse_address = True
# I'm just passing objects blindly into the http class itself, quick and dirty but it works
# there is probably a better way to do this, eg using a meta-class and inheritance
http.settings = settings
http.rrd = rrd
http.data = data
http.button_control = helpers[0]
http.icon_file = 'favicon.ico'
if not os.path.exists(http.icon_file):
http.icon_file = f'{sys.path[0]}/{http.icon_file}'
if rrd.rrdtool:
http.db_graphable = True
if settings.web_allow_dump:
logging.info("RRD database is dumpable via web")
http.db_dumpable = True
else:
http.db_dumpable = False
else:
logging.warning('Commandline rrdtool not found, '\
'graphing and dumping functions are unavailable')
http.db_dumpable = False
http.db_graphable = False
# Start the server
logging.info(f'HTTP server will bind to port {str(settings.web_port)} '\
f'on host {settings.web_host}')
httpd.server_bind()
address = f"http://{httpd.server_name}:{httpd.server_port}"
print(f"Webserver starting on : {address}")
httpd.server_activate()
def serve_forever(httpd):
with httpd: # to make sure httpd.server_close is called
logging.info("Http Server starting")
httpd.serve_forever()
logging.info("Http Server closing down")
thread = Thread(target=serve_forever, args=(httpd, ))
thread.setDaemon(True )
thread.start()
class _BaseRequestHandler(http.server.BaseHTTPRequestHandler):
'''Handles each individual request in a new thread'''
def _set_headers(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.send_header("Cache-Control", "no-cache, no-store, must-revalidate")
self.send_header("Pragma", "no-cache")
self.send_header("Expires", "0")
self.end_headers()
def _set_png_headers(self):
self.send_response(200)
self.send_header("Content-type", "image/png")
self.send_header("Cache-Control", "max-age=60")
self.end_headers()
def _set_download_headers(self, size, name):
self.send_response(200)
self.send_header("Content-Type", 'application/octet-stream')
self.send_header("Content-Disposition", f'attachment; filename="{name}"')
self.send_header("Content-Length", str(size))
self.end_headers()
def _set_icon_headers(self):
self.send_response(200)
self.send_header("Content-type", "image/x-icon")
self.end_headers()
def _give_head(self, title_extra=""):
title = http.settings.name
if len(title_extra) > 0:
title = f"{http.settings.name}{title_extra}"
return f'''
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>{title}</title>
<style>
body {{display:flex; flex-direction: column; align-items: center;}}
a {{color:#000000; text-decoration: none;}}
img {{width:auto; max-width:100%;}}
table {{border-spacing-top: 0.4em; width:auto; max-width:100%;}}
th {{font-size: 110%; text-align: left;}}
td {{padding-left: 1em; padding-right: 0;}}
</style>
</head>
<body>'''
def _give_foot(self, refresh=0, scroll=False):
ret = '''</body>\n
<script>\n'''
if refresh > 0:
ret += 'setTimeout(function(){location.replace(document.URL);}, '\
f'{str(refresh*1000)});\n'
if scroll:
ret += '''function down() {
window.scrollTo(0,document.body.scrollHeight);
console.log("SCROLL" + document.body.scrollHeight);
}
window.onload = down;'''
ret += '''</script>
</html>'''
return ret
def _give_timestamp(self):
timestamp = time.strftime(http.settings.long_format,
time.localtime(http.data["update-time"]))
return f'''<div title="Time of latest data readings"
style="color:#555555;
font-size: 94%; padding-top: 0.5em;">{timestamp}</div>
<div style="color:#555555;
font-size: 66%; font-weight: lighter; padding-top:0.5em">
<a style="color:#555555;"
href="https://github.com/easytarget/SBCEye"
title="Project homepage on GitHub" target="_blank">
SBCEye</a></div>'''
def _give_env(self):
# Environmental sensor
sensorlist = {
'env-temp': ('Temperature','.1f','°'),
'env-humi': ('Humidity','.1f','<span style="font-size: 75%;">%</span>'),
'env-pres': ('Presssure','.0f','<span style="font-size: 75%;"> mb</span>'),
}
ret = ''
if len(http.data.keys() & sensorlist.keys()) > 0:
ret += f'<tr><th>{http.settings.web_sensor_name}</th></tr>\n'
for sense,(name,fmt,suffix) in sensorlist.items():
if sense in http.data.keys():
ret += f'<tr><td>{name}: </td><td style="text-align: right;">'\
f'{http.data[sense]:{fmt}}</td>'\
f'<td style="padding-left: 0;">{suffix}</td></tr>\n'
return ret
def _give_sys(self):
# Internal Sensors
sensorlist = {
'sys-temp': ('CPU Temperature','.1f','°'),
'sys-load': ('CPU Load','1.2f',''),
'sys-freq': ('CPU Frequency','.0f','<span style="font-size: 75%;"> MHz</span>'),
'sys-mem': ('Memory used','.1f','<span style="font-size: 75%;">%</span>'),
'sys-disk': ('Disk used','.1f','<span style="font-size: 75%;">%</span>'),
'sys-proc': ('Processes','.0f',''),
'sys-net-io': ('Network IO','.1f','<span style="font-size: 75%;"> k/s</span>'),
'sys-disk-io': ('Disk IO','.1f','<span style="font-size: 75%;"> k/s</span>'),
'sys-cpu-int': ('Soft Interrupts','.0f','<span style="font-size: 75%;"> /s</span>'),
}
ret = ''
if len(http.data.keys() & sensorlist.keys()) > 0:
ret = '<tr><th>Server</th></tr>\n'
for sense,(name,fmt,suffix) in sensorlist.items():
if sense in http.data.keys():
ret += f'<tr><td>{name}: </td><td style="text-align: right;">'\
f'{http.data[sense]:{fmt}}</td>'\
f'<td style="padding-left: 0;">{suffix}</td></tr>\n'
return ret
def _give_net(self):
# Network Connectivity
ret = ''
netlist = {}
for key in http.data.keys():
if key[0:4] == 'net-':
netlist[key] = key[4:]
if len(http.data.keys() & netlist.keys()) > 0:
ret += '<tr><th>Ping</th></tr>\n'
for item,name in netlist.items():
ret += f'<tr><td>{name}:</td><td style="text-align: right;">'
if http.data[item] == 'U':
ret += 'Fail</td></tr>\n'
else:
ret += f'{http.data[item]:.1f}</td>'\
'<td style="padding-left: 0;">'\
'<span style="font-size: 75%;"> ms</span>'\
'</td></tr>\n'
return ret
def _give_pins(self):
# GPIO states
ret = ''
pinlist = {}
for key in http.data.keys():
if key[0:4] == 'pin-':
pinlist[key] = key[4:]
if len(http.data.keys() & pinlist.keys()) > 0:
ret += '<tr><th>GPIO</th></tr>\n'
for item,name in pinlist.items():
ret += f'<tr><td>{name}:</td><td style="text-align: right;">'\
f'{http.settings.pin_state_names[http.data[item]]}</td></tr>\n'
return ret
def _give_graphlinks(self, skip=""):
# A list of available graph pages
ret = ''
skip = skip.lstrip('end-')
if (len(http.settings.graph_durations) > 0) and http.db_graphable:
if len(skip) == 0:
ret += '<tr><th>Graphs</th></tr>\n'
ret += '<tr><td colspan="2" style="text-align: center;">\n'
for duration in http.settings.graph_durations:
if duration != skip:
ret += f' <a href="./graphs?start=end-{duration}" '\
f'title="Graphs covering the last {duration} in time">'\
f'{duration}</a> \n'
else:
ret += f' <span style="color: #BBBBBB;">{duration}</span> \n'
if len(skip) > 0:
ret += ' : <a href="./" title="Main page">Home</a>\n'
ret += '</td></tr>\n'
return ret
def _give_links(self):
# Link to the log and pin contol pages
ret = f'''{self._give_graphlinks()}
<tr><td colspan="2" style="text-align: center;">
<a href="./log" title="Open log in a new page" target="_blank">
Log</a>\n'''
if http.settings.web_show_control and (http.settings.button_pin > 0):
ret += f' <a href="./{http.settings.button_url}" '\
f'title="{http.settings.button_name} status and control page">'\
f'{http.settings.button_name}</a>\n'
ret += '</td></tr>\n'
return ret
def _give_log(self, lines=25):
# Combine and give last (lines) lines of log
parsed_lines = parse_qs(urlparse(self.path).query).get('lines', None)
if isinstance(parsed_lines, list):
lines = parsed_lines[0]
# Do not pass anything other than integers to the shell commsnd..
if not isinstance(lines, int):
try:
lines = int(lines)
except ValueError:
lines = int(100)
lines = max(1, min(lines, 250000))
# Use a shell one-liner used to extract the last {lines} of data from the logs
# There is doubtless a more 'python' way to do this, but it is fast, cheap and works..
log_command = \
f"for a in `ls -tr {http.settings.log_file}*`;do cat $a ; done | tail -{lines}"
log = check_output(log_command, shell=True).decode('utf-8')
ret = f'''
<div style="overflow-x: auto; width: 100%;">\n
<span style="font-size: 110%; font-weight: bold;">Recent log activity:</span>
<hr><pre>\n{log}</pre><hr>
<span style="font-size: 80%;">Latest {lines} lines shown</span>\n
</div>\n
<div><a href="./log?lines=25" title="show 25 lines">25</a> :
<a href="./log?lines=250" title="show 250 lines">250</a> :
<a href="./log?lines=2500" title="show 2500 lines">2500</a> :
<a href="./" title="Main page">Home</a></div>\n'''
return ret
def _give_graphs(self, start, end, stamp):
ret = f'''<table>\n
<tr><th>Graphs: {stamp}</th></tr>\n'''
for graph,(title,*_) in http.rrd.graph_map.items():
if graph in http.rrd.sources:
ret += f'''<tr><td>\n
<a href="graph?graph={graph}&start={start}&end={end}">
<img title="{title}"
src="graph?graph={graph}&start={start}&end={end}"></a>\n
</td></tr>\n'''
ret += self._give_graphlinks(skip=start)
ret += '</table>\n'
return ret
def _give_dump_portal(self):
return '''
<h2>RRD database dump in gzipped XML format</h2>
<div style="text-align: center; width: 80%">What is this?
See: <a href="https://oss.oetiker.ch/rrdtool/doc/rrddump.en.html"
title = "RRDTool documentation" target="_blank">The Docs</a>
</div>
<div style="text-align: center;">
<hr>
Generating the dump imposes a high load on the SBCEye process and
can potentially impact other software running on the system.
<br>
It can take several minutes to complete; depending on the
host machine and db size+complexity. <em>Use with care!</em>
<hr>
If you are sure you wish to proceed:<br>
<a href="./dump_gz" title = "Direct download link">Download</a>
</div>
'''
def _write_dedented(self, html):
# Strip leading whitespace and write
response = re.sub(r'^\s*','', html, flags=re.MULTILINE)
self.wfile.write(bytes(response, 'utf-8'))
def do_GET(self):
'''Process requests and parse their options'''
if (urlparse(self.path).path == '/graph') and http.db_graphable:
# Individual Graph
parsed_graph = parse_qs(urlparse(self.path).query).get('graph', None)
parsed_start = parse_qs(urlparse(self.path).query).get('start', None)
parsed_end = parse_qs(urlparse(self.path).query).get('end', None)
if not parsed_graph:
body = ""
else:
graph = parsed_graph[0]
if not parsed_start:
start = "end-1d"
else:
start = parsed_start[0]
if not parsed_end:
end = "now"
stamp = f'{start.replace("end","")} >> now'
else:
end = parsed_end[0]
stamp = f'{start} >> {end}'
body = http.rrd.draw_graph(start, end, stamp, graph)
if len(body) == 0:
self.send_error(404, 'Graph unavailable',
'Check your parameters and try again,'\
'see the "/graphs/" page for examples.')
return
self._set_png_headers()
self.wfile.write(body)
elif (urlparse(self.path).path == '/graphs') and http.db_graphable:
# Graph Index Page
parsed_start = parse_qs(urlparse(self.path).query).get('start', None)
parsed_end = parse_qs(urlparse(self.path).query).get('end', None)
if not parsed_start:
start = "end-1d"
else:
start = parsed_start[0]
if not parsed_end:
end =''
stamp = f'{start.replace("end","")} >> now'
else:
end = parsed_end[0]
stamp = f'{start} >> {end}'
self._set_headers()
response = self._give_head(f" :: graphs {stamp}")
response += f'<h2><a href="/">{http.settings.name}</a></h2>'
response += self._give_graphs(start, end, stamp)
response += self._give_timestamp()
response += self._give_foot(refresh=300)
self._write_dedented(response)
elif urlparse(self.path).path == '/favicon.ico':
# Favicon
if not os.path.exists(http.icon_file):
self.send_error(404, 'unavailable',
f'{http.icon_file} not found.')
else:
self._set_icon_headers()
with open(http.icon_file,'rb') as favicon:
self.wfile.write(favicon.read())
elif ((urlparse(self.path).path == '/' + http.settings.button_url)
and (len(http.settings.button_url) > 0)
and (http.settings.button_out > 0)):
# Web button control
parsed = parse_qs(urlparse(self.path).query).get('state', ['status'])
action = parsed[0]
if action != 'status':
logging.info(f'Web button triggered by: {self.client_address[0]}'\
f' with action: {action}')
status, state = http.button_control(action)
self._set_headers()
response = self._give_head(f" :: {http.settings.button_name}")
response += f'<h2>{status}</h2>\n'
invert_state = http.settings.pin_state_names[not state]
response += f'''<div>
<a href="./{http.settings.button_url}?state={invert_state}"
title = "Switch {http.settings.button_name} {invert_state}">
Switch {invert_state}</a>
</div>\n'''
response += '<div style="padding-top: 1em;">\n'\
'<a href="./" title="Main page">Home</a></div>\n'
response += self._give_timestamp()
response += '<script>\n'\
'setTimeout(function(){location.replace(location.pathname);}, '\
'60000);\n</script>\n'
response += self._give_foot()
self._write_dedented(response)
elif (urlparse(self.path).path == '/dump_gz') and http.db_dumpable:
# Raw dump download
start = time.time()
logging.info(f"RRD database dump requested by {self.client_address[0]}")
response = http.rrd.dump()
self._set_download_headers(len(response),
f'{http.settings.name}-rrd-{time.strftime("%Y%m%d-%H%M%S")}.xml.gz')
self.wfile.write(response)
logging.info(f"Dump completed in {(time.time() - start):.2f}s")
elif (urlparse(self.path).path == '/dump') and http.db_dumpable:
# Dump warning and link page
self._set_headers()
response = self._give_head(" :: RRD Dump")
response += self._give_dump_portal()
response += self._give_foot()
self._write_dedented(response)
elif urlparse(self.path).path == '/log':
self._set_headers()
response = self._give_head()
response += f'<h2><a href="/" title="Home">{http.settings.name}</a> Log</h2>\n'
response += self._give_log()
response += self._give_timestamp()
response += self._give_foot(refresh=60, scroll=True)
self._write_dedented(response)
elif urlparse(self.path).path == '/':
# Main Page
cam = parse_qs(urlparse(self.path).query).get('cam', None)
exclude = parse_qs(urlparse(self.path).query).get('exclude', '')
exclude = [item for sublist in exclude for item in sublist.split(',')]
self._set_headers()
response = self._give_head()
if not "deco" in exclude:
response += f'<h2>{http.settings.name}</h2>\n'
if cam and http.settings.cam_url:
response += f'<img src="{http.settings.cam_url}" alt="Webcam" '\
f'style="display: block; width: {http.settings.cam_width}%">\n'
response += '<table>\n'
if not "env" in exclude:
response += self._give_env()
if not "sys" in exclude:
response += self._give_sys()
if not "net" in exclude:
response += self._give_net()
if not "gpio" in exclude:
response += self._give_pins()
if not "links" in exclude:
response += self._give_links()
response += '</table>\n'
if not "deco" in exclude:
response += self._give_timestamp()
response += self._give_foot(refresh=60)
self._write_dedented(response)
else:
self.send_error(404, 'No Such Page',
'Nothing matches the given URL on this server')
def do_HEAD(self):
'''returns headers'''
self._set_headers()