Started work on core exceptions and request type

This commit is contained in:
Thastertyn 2025-01-26 18:26:07 +01:00
parent ce30e03767
commit 5a1aa79216
6 changed files with 42 additions and 8 deletions

View File

@ -3,7 +3,7 @@
## Sources ## Sources
### Signal catching ### Signal catching
- [Catch SIGTERM](https://stackoverflow.com/a/31464349) - [Catch SIGTERM](https://dnmtechs.com/graceful-sigterm-signal-handling-in-python-3-best-practices-and-implementation/)
- [Get ENUM name from value](https://stackoverflow.com/a/38716384) - [Get ENUM name from value](https://stackoverflow.com/a/38716384)
### Networking ### Networking

View File

@ -3,10 +3,14 @@ import signal
import sys import sys
import logging import logging
from core.config import BankNodeConfig from core.config import BankNodeConfig
from utils import setup_logger
class BankNode(): class BankNode():
def __init__(self): def __init__(self):
setup_logger()
self.logger = logging.getLogger(__name__) self.logger = logging.getLogger(__name__)
self._setup_signals() self._setup_signals()
self.config = BankNodeConfig() self.config = BankNodeConfig()
@ -16,13 +20,6 @@ class BankNode():
signal.signal(signal.SIGTERM, self.gracefully_exit) signal.signal(signal.SIGTERM, self.gracefully_exit)
signal.signal(signal.SIGINT, self.gracefully_exit) signal.signal(signal.SIGINT, self.gracefully_exit)
def gracefully_exit(self, signum, frame):
signal_name = signal.Signals(signum).name
self.logger.warning("Caught %s. Cleaning up before exiting", signal_name)
self.cleanup()
sys.exit(0)
def start_server(self): def start_server(self):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as socket_server: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as socket_server:
socket_server.bind(("127.0.0.1", 6969)) socket_server.bind(("127.0.0.1", 6969))
@ -37,3 +34,9 @@ class BankNode():
def cleanup(self): def cleanup(self):
pass pass
def gracefully_exit(self, signum, frame):
signal_name = signal.Signals(signum).name
self.logger.warning("Caught %s. Cleaning up before exiting", signal_name)
self.cleanup()
sys.exit(0)

View File

@ -0,0 +1,13 @@
class BankProtocolError(Exception):
def __init__(self, message):
super().__init__(message)
self.message = message
class InvalidRequest(BankProtocolError):
def __init__(self, message):
super().__init__(message)
self.message = message
__all__ = ["BankProtocolError", "InvalidRequest"]

View File

@ -0,0 +1,10 @@
from core.exceptions import *
class Request():
def __init__(self, raw_request):
try:
self.command_code = raw_request[0:1]
self.body = raw_request[2:-1]
except IndexError:
pass

View File

@ -0,0 +1,5 @@
from .logger import *
__all__ = [
*logger.__all__
]

View File

@ -11,3 +11,6 @@ def setup_logger():
handler.setFormatter(formatter) handler.setFormatter(formatter)
logger.addHandler(handler) logger.addHandler(handler)
__all__ = ["setup_logger"]