updated logger, updated ipc setup

This commit is contained in:
itdominator 2022-06-14 18:19:21 -05:00
parent 88db4171cf
commit d74761344c
3 changed files with 77 additions and 65 deletions

View File

@ -16,7 +16,7 @@ class Application(EventSystem):
def __init__(self, args, unknownargs): def __init__(self, args, unknownargs):
if not debug: if not debug:
event_system.create_ipc_server() event_system.create_ipc_listener()
time.sleep(0.1) time.sleep(0.1)
if not trace_debug: if not trace_debug:

View File

@ -16,73 +16,85 @@ def threaded(fn):
class IPCServer: class IPCServer:
''' Create a listener so that other instances send requests back to existing instance. ''' """ Create a listener so that other SolarFM instances send requests back to existing instance. """
def __init__(self, conn_type: str = "socket"): def __init__(self, ipc_address: str = '127.0.0.1', conn_type: str = "socket"):
self.is_ipc_alive = False self.is_ipc_alive = False
self._conn_type = conn_type self._ipc_port = 4848
self.ipc_authkey = b'app-ipc' self._ipc_address = ipc_address
self.ipc_timeout = 15.0 self._conn_type = conn_type
self._ipc_authkey = b'app-ipc'
self._ipc_timeout = 15.0
if conn_type == "socket": if conn_type == "socket":
self.ipc_address = '/tmp/app-ipc.sock' self._ipc_address = '/tmp/app-ipc.sock'
else: elif conn_type == "full_network":
self.ipc_address = '127.0.0.1' self._ipc_address = '0.0.0.0'
self.ipc_port = 8888 elif conn_type == "full_network_unsecured":
self._ipc_authkey = None
self._ipc_address = '0.0.0.0'
elif conn_type == "local_network_unsecured":
self._ipc_authkey = None
@threaded @threaded
def create_ipc_server(self) -> None: def create_ipc_listener(self) -> None:
if self._conn_type == "socket": if self._conn_type == "socket":
if os.path.exists(self.ipc_address): if os.path.exists(self._ipc_address):
return return
listener = Listener(address=self.ipc_address, family="AF_UNIX", authkey=self.ipc_authkey) listener = Listener(address=self._ipc_address, family="AF_UNIX", authkey=self._ipc_authkey)
elif "unsecured" not in self._conn_type:
listener = Listener((self._ipc_address, self._ipc_port), authkey=self._ipc_authkey)
else: else:
listener = Listener((self.ipc_address, self.ipc_port), authkey=self.ipc_authkey) listener = Listener((self._ipc_address, self._ipc_port))
self.is_ipc_alive = True self.is_ipc_alive = True
while True: while True:
conn = listener.accept() conn = listener.accept()
start_time = time.time() start_time = time.perf_counter()
self.handle_message(conn, start_time)
print(f"New Connection: {listener.last_accepted}")
while True:
msg = conn.recv()
if debug:
print(msg)
if "FILE|" in msg:
file = msg.split("FILE|")[1].strip()
if file:
event_system.push_gui_event([None, "handle_file_from_ipc", (file,)])
conn.close()
break
if msg == 'close connection':
conn.close()
break
if msg == 'close server':
conn.close()
break
# NOTE: Not perfect but insures we don't lockup the connection for too long.
end_time = time.time()
if (end - start) > self.ipc_timeout:
conn.close()
listener.close() listener.close()
def handle_message(self, conn, start_time) -> None:
while True:
msg = conn.recv()
if debug:
print(msg)
if "FILE|" in msg:
file = msg.split("FILE|")[1].strip()
if file:
event_system.push_gui_event([None, "handle_file_from_ipc", (file,)])
conn.close()
break
if msg in ['close connection', 'close server']:
conn.close()
break
# NOTE: Not perfect but insures we don't lock up the connection for too long.
end_time = time.perf_counter()
if (end_time - start_time) > self._ipc_timeout:
conn.close()
break
def send_ipc_message(self, message: str = "Empty Data...") -> None: def send_ipc_message(self, message: str = "Empty Data...") -> None:
try: try:
if self._conn_type == "socket": if self._conn_type == "socket":
conn = Client(address=self.ipc_address, family="AF_UNIX", authkey=self.ipc_authkey) conn = Client(address=self._ipc_address, family="AF_UNIX", authkey=self._ipc_authkey)
elif "unsecured" not in self._conn_type:
conn = Client((self._ipc_address, self._ipc_port), authkey=self._ipc_authkey)
else: else:
conn = Client((self.ipc_address, self.ipc_port), authkey=self.ipc_authkey) conn = Client((self._ipc_address, self._ipc_port))
conn.send(message) conn.send(message)
conn.send('close connection')
conn.close() conn.close()
except ConnectionRefusedError as e:
print("Connection refused...")
except Exception as e: except Exception as e:
print(repr(e)) print(repr(e))

View File

@ -5,39 +5,39 @@ import os, logging
class Logger: class Logger:
def __init__(self, config_path: str): """
self._CONFIG_PATH = config_path Create a new logging object and return it.
:note:
def get_logger(self, loggerName: str = "NO_LOGGER_NAME_PASSED", createFile: bool = True) -> logging.Logger: NOSET # Don't know the actual log level of this... (defaulting or literally none?)
""" Log Levels (From least to most)
Create a new logging object and return it.
:note:
NOSET # Don't know the actual log level of this... (defaulting or literally none?)
Log Levels (From least to most)
Type Value Type Value
CRITICAL 50 CRITICAL 50
ERROR 40 ERROR 40
WARNING 30 WARNING 30
INFO 20 INFO 20
DEBUG 10 DEBUG 10
:param loggerName: Sets the name of the logger object. (Used in log lines) :param loggerName: Sets the name of the logger object. (Used in log lines)
:param createFile: Whether we create a log file or just pump to terminal :param createFile: Whether we create a log file or just pump to terminal
:return: the logging object we created :return: the logging object we created
""" """
globalLogLvl = logging.DEBUG # Keep this at highest so that handlers can filter to their desired levels def __init__(self, config_path: str, _ch_log_lvl = logging.CRITICAL, _fh_log_lvl = logging.INFO):
chLogLevel = logging.CRITICAL # Prety musch the only one we change ever self._CONFIG_PATH = config_path
fhLogLevel = logging.DEBUG self.global_lvl = logging.DEBUG # Keep this at highest so that handlers can filter to their desired levels
self.ch_log_lvl = _ch_log_lvl # Prety much the only one we ever change
self.fh_log_lvl = _fh_log_lvl
def get_logger(self, loggerName: str = "NO_LOGGER_NAME_PASSED", createFile: bool = True) -> logging.Logger:
log = logging.getLogger(loggerName) log = logging.getLogger(loggerName)
log.setLevel(globalLogLvl) log.setLevel(self.global_lvl)
# Set our log output styles # Set our log output styles
fFormatter = logging.Formatter('[%(asctime)s] %(pathname)s:%(lineno)d %(levelname)s - %(message)s', '%m-%d %H:%M:%S') fFormatter = logging.Formatter('[%(asctime)s] %(pathname)s:%(lineno)d %(levelname)s - %(message)s', '%m-%d %H:%M:%S')
cFormatter = logging.Formatter('%(pathname)s:%(lineno)d] %(levelname)s - %(message)s') cFormatter = logging.Formatter('%(pathname)s:%(lineno)d] %(levelname)s - %(message)s')
ch = logging.StreamHandler() ch = logging.StreamHandler()
ch.setLevel(level=chLogLevel) ch.setLevel(level=self.ch_log_lvl)
ch.setFormatter(cFormatter) ch.setFormatter(cFormatter)
log.addHandler(ch) log.addHandler(ch)
@ -49,7 +49,7 @@ class Logger:
os.mkdir(folder) os.mkdir(folder)
fh = logging.FileHandler(file) fh = logging.FileHandler(file)
fh.setLevel(level=fhLogLevel) fh.setLevel(level=self.fh_log_lvl)
fh.setFormatter(fFormatter) fh.setFormatter(fFormatter)
log.addHandler(fh) log.addHandler(fh)