summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authoruser <user@node5.net>2024-03-17 20:31:18 +0100
committeruser <user@node5.net>2024-03-17 20:31:18 +0100
commit254c85bf5cbab73654df3de7926bd96069eb017f (patch)
tree240575a9cac4e85e80954229063399fe8ab12e5b /src
parent937a5571a158115060f062b066543132d8c66752 (diff)
refactoring - whitespace
Diffstat (limited to 'src')
-rw-r--r--src/server_status.py55
1 files changed, 29 insertions, 26 deletions
diff --git a/src/server_status.py b/src/server_status.py
index cba9bdd..d6a1989 100644
--- a/src/server_status.py
+++ b/src/server_status.py
@@ -1,11 +1,11 @@
-import telegram # Notifications
-import asyncio # Telegram library is async
-import requests # HTTP
-import os # Unix socket file handling
-import subprocess # Ping
-import socket # Hostname, unix socket
-import yaml # Config file
-import logging # Log messages
+import telegram # Notifications
+import asyncio # Telegram library is async
+import requests # HTTP
+import os # Unix socket file handling
+import subprocess # Ping
+import socket # Hostname, unix socket
+import yaml # Config file
+import logging # Log messages
logger = logging.getLogger('server_status')
logger.setLevel(level=logging.DEBUG)
@@ -23,26 +23,30 @@ hostname = socket.gethostname()
# Initialise data stucture based on targets in config file
state = {}
for host, host_config in config["hosts"].items():
- state[host] = {"online": None,"open_ports": []}
+ state[host] = {"online": None, "open_ports": []}
if 'urls' in host_config:
state[host]["http_status"] = {}
for url in host_config['urls']:
state[host]['http_status'][url] = None
+
# Send message from non async function
def send_message(text):
logger.debug(f"Sending message: {text}")
asyncio.run(async_send_message(text))
+
async def async_send_message(text):
async with bot:
- await bot.send_message(text=text, chat_id=config["telegram"]["chat_id"],
+ await bot.send_message(text=text, chat_id=config["telegram"]["chat_id"],
parse_mode=telegram.constants.ParseMode.MARKDOWN)
+
def ping(host: str) -> bool:
response = subprocess.run(["ping", "-c", "1", host])
return response.returncode == 0
+
def check_target(host: str, host_config: dict):
# Ping
online = ping(host)
@@ -55,14 +59,14 @@ def check_target(host: str, host_config: dict):
host_is_desired_state: {host_is_desired_state}
first_test: {first_test}
changed_state: {changed_state}
- ''')
+ ''')
# notify if the host online state changed, or on fresh boot, if it isn't the desired online state
if changed_state or (first_test and not host_is_desired_state):
message = f"`{host}` is {'online' if online else 'offline'}"
logger.warning(message)
send_message(message)
- state[host]['online'] = online # Save current state
-
+ state[host]['online'] = online # Save current state
+
if not online:
return
@@ -71,13 +75,13 @@ def check_target(host: str, host_config: dict):
http_state = None
# HTTP Code
try:
- #print(f'''
- #---=== Getting: {url} ===---
- #''')
+ # print(f'''
+ # ---=== Getting: {url} ===---
+ # ''')
r = requests.get(url)
if r.status_code != 200:
http_state = r.status_code
- except requests.exceptions.SSLError as exception:
+ except requests.exceptions.SSLError as exception:
try:
reason = exception.args[0].reason.args[0].verify_message
except Exception as exception:
@@ -91,9 +95,9 @@ def check_target(host: str, host_config: dict):
messages.append(f'[{url}]({url}) {http_state}')
state[host]['http_status'][url] = http_state
-
if len(messages) > 0:
- send_message('\n'.join(messages)) # NTEINRIETNOIW NOIE#NOIE#N#IEN##I @NUY UYN@YUN@UY@NYU@N YUN@ UYN@YUN@YUN@YU@NUY@NU@NYU@N@UY@UNYUN@
+ send_message('\n'.join(
+ messages))
def check_status():
@@ -104,7 +108,7 @@ def check_status():
except Exception as ex:
send_message("Error getting status")
raise ex
-
+
def listen():
# remove the socket file if it already exists
@@ -113,7 +117,7 @@ def listen():
except OSError:
if os.path.exists(socket_path):
raise
-
+
try:
# Create the Unix socket server
server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
@@ -123,7 +127,7 @@ def listen():
# Listen for incoming connections
server.listen(1)
-
+
while True:
try:
# accept connections
@@ -149,9 +153,8 @@ def listen():
if "connection" in locals():
connection.close()
finally:
- # remove the socket file
- os.unlink(socket_path)
-
+ # remove the socket file
+ os.unlink(socket_path)
def main():
@@ -159,6 +162,6 @@ def main():
check_status()
listen()
+
if __name__ == "__main__":
asyncio.run(main())
-