Backend logging & hardening
This commit is contained in:
parent
b37d2b1d97
commit
c1c00e2868
3 changed files with 81 additions and 22 deletions
|
|
@ -6,14 +6,22 @@ Changes come in via WebAPI so we can make a lightweight desktop client and leave
|
||||||
Also allows the TidByt to still have forgeserv.net data without needing to be stood up
|
Also allows the TidByt to still have forgeserv.net data without needing to be stood up
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from fastapi import FastAPI
|
import logging
|
||||||
|
|
||||||
|
from fastapi import FastAPI, Response
|
||||||
|
|
||||||
from server.state import AppState, StateManager
|
from server.state import AppState, StateManager
|
||||||
|
|
||||||
app = FastAPI()
|
app: FastAPI = FastAPI()
|
||||||
state_mgr = StateManager(timeout=10)
|
logger = logging.getLogger("uvicorn.error")
|
||||||
|
state_mgr: StateManager = StateManager(timeout=10)
|
||||||
|
state_mgr.start()
|
||||||
|
|
||||||
|
|
||||||
@app.post("/")
|
@app.post("/")
|
||||||
def change_state(new_state: int):
|
def change_state(new_state: int):
|
||||||
|
try:
|
||||||
state_mgr.update(AppState(new_state))
|
state_mgr.update(AppState(new_state))
|
||||||
return {"msg": "👍"}
|
except Exception as e:
|
||||||
|
logger.warning(f"/change_state ran into an {type(e).__name__}: {str(e)}")
|
||||||
|
return Response(status_code=200)
|
||||||
|
|
|
||||||
|
|
@ -1,26 +1,33 @@
|
||||||
"""A Python Wrapper for Pixlet ops"""
|
"""A Python Wrapper for Pixlet ops"""
|
||||||
|
|
||||||
import subprocess
|
import logging
|
||||||
from os import getenv
|
from os import getenv
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from platform import machine
|
from platform import machine
|
||||||
|
from subprocess import PIPE, Popen
|
||||||
|
from time import sleep
|
||||||
|
from typing import Tuple
|
||||||
|
|
||||||
from server.renderables import Renderable
|
from server.renderables import Renderable
|
||||||
|
|
||||||
|
|
||||||
class PixletHelper:
|
class PixletHelper:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
|
self.logger = logging.getLogger("uvicorn.error")
|
||||||
self.root_path: Path = Path("./").resolve()
|
self.root_path: Path = Path("./").resolve()
|
||||||
self.pixlet: Path = self.root_path.joinpath(f"pixlet.{machine()}").resolve()
|
self.pixlet: Path = self.root_path.joinpath(f"pixlet.{machine()}").resolve()
|
||||||
self.device_id: str = getenv("TIDBYT_DEVICE_ID", "")
|
self.device_id: str = getenv("TIDBYT_DEVICE_ID", "")
|
||||||
|
|
||||||
def push_to_tidbyt(self, renderable: Renderable) -> None:
|
def push_to_tidbyt(self, renderable: Renderable) -> bool:
|
||||||
"""Pushes a renderable to the Tidbyt device
|
"""Pushes a renderable to the Tidbyt device
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
renderable (Renderable): The Pixlet Configuration for the given state
|
renderable (Renderable): The Pixlet Configuration for the given state
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
bool: True if the process succeeded, False otherwise
|
||||||
"""
|
"""
|
||||||
self.__display(self.__render(renderable))
|
return self.__display(self.__render(renderable))
|
||||||
|
|
||||||
def __render(self, renderable: Renderable) -> Path:
|
def __render(self, renderable: Renderable) -> Path:
|
||||||
"""Renders a given PixeltConfiguration (and any template args) to webp
|
"""Renders a given PixeltConfiguration (and any template args) to webp
|
||||||
|
|
@ -33,19 +40,27 @@ class PixletHelper:
|
||||||
"""
|
"""
|
||||||
output_path = self.__prepare_file(renderable)
|
output_path = self.__prepare_file(renderable)
|
||||||
|
|
||||||
with subprocess.Popen([self.pixlet, "render", str(output_path)]) as proc:
|
with Popen(
|
||||||
proc.wait()
|
[self.pixlet, "render", str(output_path)], stdout=PIPE, stderr=PIPE
|
||||||
|
) as proc:
|
||||||
|
exit_code = proc.wait()
|
||||||
|
stdout, stderr = self.__get_decoded_out(proc)
|
||||||
|
if exit_code != 0 and (stdout or stderr):
|
||||||
|
self.logger.warning(f"__render call failed: {stdout or stderr}")
|
||||||
|
|
||||||
return self.root_path.joinpath("tmp.webp").resolve()
|
return self.root_path.joinpath("tmp.webp").resolve()
|
||||||
|
|
||||||
def __display(self, path: Path, attempt=0) -> None:
|
def __display(self, path: Path, attempt=0) -> bool:
|
||||||
"""Pushes a given rendered webp file to the pixlet on the same installation id
|
"""Pushes a given rendered webp file to the pixlet on the same installation id
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
path (Path): The path to the given rendered webp
|
path (Path): The path to the given rendered webp
|
||||||
attempt (int, optional): Used to track recursive calls in case pushing fails. Defaults to 0.
|
attempt (int, optional): Used to track recursive calls in case pushing fails. Defaults to 0.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
bool: True if pushing the rendered path to the Tidbyt succeeded, False otherwise
|
||||||
"""
|
"""
|
||||||
with subprocess.Popen(
|
with Popen(
|
||||||
[
|
[
|
||||||
self.pixlet,
|
self.pixlet,
|
||||||
"push",
|
"push",
|
||||||
|
|
@ -53,11 +68,23 @@ class PixletHelper:
|
||||||
"automation",
|
"automation",
|
||||||
self.device_id,
|
self.device_id,
|
||||||
str(path),
|
str(path),
|
||||||
]
|
],
|
||||||
|
stdout=PIPE,
|
||||||
|
stderr=PIPE,
|
||||||
) as proc:
|
) as proc:
|
||||||
exit_code = proc.wait()
|
exit_code = proc.wait()
|
||||||
if exit_code != 0 and attempt < 5:
|
if exit_code == 0:
|
||||||
self.__display(path, attempt=attempt + 1)
|
return True
|
||||||
|
if attempt < 5:
|
||||||
|
sleep(3 * (attempt + 1))
|
||||||
|
return self.__display(path, attempt=attempt + 1)
|
||||||
|
else:
|
||||||
|
stdout, stderr = self.__get_decoded_out(proc)
|
||||||
|
if exit_code != 0 and (stdout or stderr):
|
||||||
|
self.logger.warning(
|
||||||
|
f"__display call failed after 5 attempts: {stdout or stderr}"
|
||||||
|
)
|
||||||
|
return False
|
||||||
|
|
||||||
def __prepare_file(self, renderable: Renderable) -> Path:
|
def __prepare_file(self, renderable: Renderable) -> Path:
|
||||||
"""Prepares a given pixlet star file. If the file is a template, checks the template keys and prepares the template before writing to the temp path
|
"""Prepares a given pixlet star file. If the file is a template, checks the template keys and prepares the template before writing to the temp path
|
||||||
|
|
@ -89,3 +116,14 @@ class PixletHelper:
|
||||||
handle.write(data)
|
handle.write(data)
|
||||||
|
|
||||||
return output_path
|
return output_path
|
||||||
|
|
||||||
|
def __get_decoded_out(self, proc: Popen[bytes]) -> Tuple[str, str]:
|
||||||
|
"""Gets the decoded stdout and stderr from a Popen call
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Tuple[str, str]: (stdout, stderr) respectively, decoded as strings.
|
||||||
|
"""
|
||||||
|
stdout, stderr = proc.communicate()
|
||||||
|
stdout = stdout.decode().replace("\n", " ")
|
||||||
|
stderr = stderr.decode().replace("\n", " ")
|
||||||
|
return (stdout, stderr)
|
||||||
|
|
|
||||||
|
|
@ -1,14 +1,14 @@
|
||||||
|
import logging
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from threading import Thread
|
from threading import Thread
|
||||||
from time import sleep
|
from time import sleep
|
||||||
from typing import Dict
|
from typing import Dict
|
||||||
|
|
||||||
|
from common.appstate import AppState
|
||||||
from server.pixlet import PixletHelper
|
from server.pixlet import PixletHelper
|
||||||
from server.renderables import Renderable
|
from server.renderables import Renderable
|
||||||
from server.renderables.forgeserv import ForgeServ
|
from server.renderables.forgeserv import ForgeServ
|
||||||
|
|
||||||
from common.appstate import AppState
|
|
||||||
|
|
||||||
|
|
||||||
class StateManager:
|
class StateManager:
|
||||||
def __init__(self, timeout=1):
|
def __init__(self, timeout=1):
|
||||||
|
|
@ -17,6 +17,7 @@ class StateManager:
|
||||||
Args:
|
Args:
|
||||||
timeout (int, optional): How long to wait between iterations (in seconds). Defaults to 1.
|
timeout (int, optional): How long to wait between iterations (in seconds). Defaults to 1.
|
||||||
"""
|
"""
|
||||||
|
self.logger = logging.getLogger("uvicorn.error")
|
||||||
self.state: AppState = AppState.IDLE
|
self.state: AppState = AppState.IDLE
|
||||||
self.renderables: Dict[AppState, Renderable] = {
|
self.renderables: Dict[AppState, Renderable] = {
|
||||||
AppState.IDLE: ForgeServ(),
|
AppState.IDLE: ForgeServ(),
|
||||||
|
|
@ -36,7 +37,6 @@ class StateManager:
|
||||||
self.thread: Thread = None
|
self.thread: Thread = None
|
||||||
self.stop_thread = False
|
self.stop_thread = False
|
||||||
self.__pixlet_helper = PixletHelper()
|
self.__pixlet_helper = PixletHelper()
|
||||||
self.__start()
|
|
||||||
|
|
||||||
def update(self, new_state: AppState):
|
def update(self, new_state: AppState):
|
||||||
"""Update the Tidbyt's state, returning the prior state
|
"""Update the Tidbyt's state, returning the prior state
|
||||||
|
|
@ -50,7 +50,7 @@ class StateManager:
|
||||||
self.state = new_state
|
self.state = new_state
|
||||||
self.__pixlet_helper.push_to_tidbyt(self.renderables[self.state])
|
self.__pixlet_helper.push_to_tidbyt(self.renderables[self.state])
|
||||||
|
|
||||||
def __start(self):
|
def start(self):
|
||||||
"""Instantiates and starts the worker thread
|
"""Instantiates and starts the worker thread
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
|
|
@ -60,10 +60,23 @@ class StateManager:
|
||||||
raise Exception("Thread has already been initialized!")
|
raise Exception("Thread has already been initialized!")
|
||||||
self.thread = Thread(target=self.__thread_task, daemon=True)
|
self.thread = Thread(target=self.__thread_task, daemon=True)
|
||||||
self.thread.start()
|
self.thread.start()
|
||||||
|
self.logger.info(f"Started thread with tid={self.thread.ident}")
|
||||||
|
|
||||||
def __thread_task(self):
|
def __thread_task(self):
|
||||||
"""A looping task that renders and pushes the correct pixlet based on state"""
|
"""A looping task that renders and pushes the correct pixlet based on state"""
|
||||||
while not self.stop_thread:
|
while not self.stop_thread:
|
||||||
|
try:
|
||||||
if self.renderables[self.state].is_dynamic:
|
if self.renderables[self.state].is_dynamic:
|
||||||
self.__pixlet_helper.push_to_tidbyt(self.renderables[self.state])
|
if not self.__pixlet_helper.push_to_tidbyt(
|
||||||
|
self.renderables[self.state]
|
||||||
|
):
|
||||||
|
self.logger.warning(
|
||||||
|
f"Failed to push {self.state.name} to TidByt - pausing for {10 * self.timeout} seconds"
|
||||||
|
)
|
||||||
|
sleep(10 * self.timeout)
|
||||||
sleep(self.timeout)
|
sleep(self.timeout)
|
||||||
|
except Exception as e:
|
||||||
|
self.logger.warning(
|
||||||
|
f"Thread task ran into an {type(e).__name__}: {str(e)}"
|
||||||
|
)
|
||||||
|
sleep(self.timeout * 2)
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue