From a8c8dca4aa130216afe5e9082e4a0f954b9ef218 Mon Sep 17 00:00:00 2001 From: ChaoticByte Date: Sun, 23 Feb 2025 20:57:42 +0100 Subject: [PATCH] Add HTTPServer and PingableSystem to dashboad.system and add an example. --- dashboard/system.py | 55 +++++++++++++++++++++++++++++++++++++++++++++ example.py | 4 ++-- 2 files changed, 57 insertions(+), 2 deletions(-) diff --git a/dashboard/system.py b/dashboard/system.py index 663216e..a28fc81 100644 --- a/dashboard/system.py +++ b/dashboard/system.py @@ -1,7 +1,14 @@ # Copyright (c) 2025, Julian Müller (ChaoticByte) +# additional libraries + +import platform +import requests +import subprocess + from enum import Enum +from typing import Tuple # base classes and types and stuff @@ -28,3 +35,51 @@ class System: # to be overridden self.state = SystemState.UNKNOWN self.state_verbose = "" + + +# some basic systems + + +class PingableSystem(System): + + def __init__(self, name, description, host: str): + super().__init__(name, description) + self.host = host + + def ping(self) -> Tuple[bool, str, str]: + if platform.system().lower() == "windows": p = "-n" + else: p = "-c" + s = subprocess.run(["ping", p, '1', self.host], stdout=subprocess.PIPE, stderr=subprocess.PIPE) + return s.returncode == 0, s.stdout.decode(), s.stderr.decode() + + def update_state(self): + self.state = SystemState.UNKNOWN + ok, stdout, stderr = self.ping() + if ok: + self.state = SystemState.OK + self.state_verbose = stdout + else: + self.state = SystemState.FAILED + self.state_verbose = stdout + "\n" + stderr + + +class HTTPServer(System): + + def __init__(self, name, description, url: str, expected_status_code: int = 200, allow_self_signed_cert: bool = False): + super().__init__(name, description) + self.url = url + self.expected_status = expected_status_code + self.allow_self_signed_cert = allow_self_signed_cert + + def update_state(self): + self.state = SystemState.UNKNOWN + try: + r = requests.head(self.url, timeout=1.0, verify=not self.allow_self_signed_cert) + if r.status_code == 200: + self.state = SystemState.OK + else: + self.state = SystemState.FAILED + self.state_verbose = f"Status {r.status_code} {r.url}" + except requests.ConnectionError as e: + self.state = SystemState.FAILED + self.state_verbose = f"Exception: {str(e)}" diff --git a/example.py b/example.py index 40183fd..e7169cb 100644 --- a/example.py +++ b/example.py @@ -3,7 +3,7 @@ from nicegui import ui -from dashboard.system import System, SystemState +from dashboard.system import HTTPServer, System, SystemState from dashboard.ui import init_ui @@ -50,7 +50,7 @@ systems = [ "Example Heading 1", ExampleSystem("Example System 1", "Description text ..."), "Example Heading 2", - ExampleSystem("Example System 2", "Another description text ...") + HTTPServer("example.org", "The example.org HTTP server.", "https://example.org/") ] #