selfhost-utils/dashboard/dashboard.py

117 lines
3.4 KiB
Python
Raw Normal View History

2022-04-06 19:29:30 +02:00
#!/usr/bin/env python3
import os
import sys
import time
from http.server import BaseHTTPRequestHandler, HTTPServer
import logging
import traceback
import re
import locale
import subprocess
import configparser
""" @package docstring
Resources dashboard
Starts a webserver on a specific port of the monitored server and serves a simple webpage containing
the monitored sensors graphs.
Installation:
- Copy dashboard.cfg in /usr/local/etc/dashboard.cfg and customize it
- Copy dashboard.py in /usr/local/bin/dashboard.py
Usage:
Start the server:
/usr/local/bin/dashboard.py /usr/local/etc/dashboard.cfg
@author Daniele Verducci <daniele.verducci@ichibi.eu>
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 3 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, see <http://www.gnu.org/licenses/>.
"""
NAME = 'dashboard'
VERSION = '0.1'
DESCRIPTION = 'A simple system resources dashboard'
class WebServer(BaseHTTPRequestHandler):
def __init__(self, configPath):
''' Sets up locale (needed for parsing numbers) '''
# Get system locale from $LANG (i.e. "en_GB.UTF-8")
systemLocale = os.getenv('LANG')
if not systemLocale:
raise ValueError('System environment variabile $LANG is not set!')
locale.setlocale(locale.LC_ALL, systemLocale)
''' Reads the config '''
self._log = logging.getLogger('main')
if not os.path.exists(configPath) or not os.path.isfile(configPath):
raise ValueError('configPath must be a file')
self.config = configparser.ConfigParser(interpolation=None) # Disable interpolation because contains regexp
self.config.read(configPath)
self.hostname = os.uname()[1]
def do_GET(self):
self.readSensors()
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(bytes("<html><head><title>https://pythonbasics.org</title></head>", "utf-8"))
self.wfile.write(bytes("<p>Request: %s</p>" % self.path, "utf-8"))
self.wfile.write(bytes("<body>", "utf-8"))
self.wfile.write(bytes("<p>This is an example web server.</p>", "utf-8"))
self.wfile.write(bytes("</body></html>", "utf-8"))
def readSensors():
return
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(
prog = NAME + '.py',
description = NAME + ' ' + VERSION + '\n' + DESCRIPTION,
formatter_class = argparse.RawTextHelpFormatter
)
parser.add_argument('configFile', help="configuration file path")
parser.add_argument('-q', '--quiet', action='store_true', help="suppress non-essential output")
args = parser.parse_args()
if args.quiet:
level = logging.WARNING
else:
level = logging.INFO
logging.basicConfig(level=level)
port =
httpd = HTTPServer(('localhost', port), Server)
logging.info('Serving on port {}'.format(port))
try:
httpd.serve_forever()
except KeyboardInterrupt:
pass
except Exception as e:
logging.critical(traceback.format_exc())
print('ERROR: {}'.format(e))
sys.exit(1)
finally:
httpd.server_close()
sys.exit(0)