Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bridges updates, part two #2411

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion core/libs/bridges/bridges/bridges.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import logging
import shlex
import time
from enum import Enum
from shutil import which
from subprocess import PIPE, Popen

Expand All @@ -9,6 +10,13 @@
from bridges.serialhelper import Baudrate


class Status(Enum):
STARTING = "STARTING"
RUNNING = "RUNNING"
STOPPING = "STOPPING"
DEAD = "DEAD"


# pylint: disable=too-many-arguments
class Bridge:
"""Basic abstraction of Bridges. Used to bridge serial devices to UDP ports"""
Expand All @@ -23,10 +31,11 @@ def __init__(
automatic_disconnect: bool = True,
) -> None:
bridges = which("bridges")
self.status = Status.STARTING
automatic_disconnect_clients = "" if automatic_disconnect else "--no-udp-disconnection"
is_server = ip == "0.0.0.0"
port = udp_listen_port if is_server else udp_target_port

self.output: str = ""
command_line = f"{bridges} -u {ip}:{port} -p {serial_port.device}:{baud} {automatic_disconnect_clients}"
if not is_server and udp_listen_port != 0:
command_line += f" --listen-port {udp_listen_port}"
Expand All @@ -39,14 +48,28 @@ def __init__(
_stdout, strerr = self.process.communicate()
error = strerr.decode("utf-8") if strerr else "Empty error"
raise RuntimeError(f'Failed to initialize bridge, code: {self.process.returncode}, message: "{error}".')
self.status = Status.RUNNING

def stop(self) -> None:
self.status = Status.STOPPING
if not self.process:
raise RuntimeError("Bridges process doesn't exist.")
self.process.kill()
time.sleep(1.0)
if self.process.poll() is None:
raise RuntimeError("Failed to kill bridges process.")
self.status = Status.DEAD

def commmunicate(self) -> tuple[bytes, bytes]:
if not self.process:
self.status = Status.DEAD
raise RuntimeError("Bridges process doesn't exist.")
output, error = self.process.communicate()
self.output += output.decode("utf-8") + error.decode("utf-8")
# Limit the size of self.output to 1000 characterxs
if len(self.output) > 1000:
self.output = self.output[-1000:]
return output, error

def __del__(self) -> None:
self.stop()
7 changes: 7 additions & 0 deletions core/services/bridget/bridget.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import asyncio
import logging
from pathlib import Path
from typing import Dict, List
Expand Down Expand Up @@ -95,6 +96,12 @@ def remove_bridge(self, bridge_spec: BridgeFrontendSpec) -> None:
raise RuntimeError("Bridge doesn't exist.")
bridge.stop()

async def do_house_keeping(self) -> None:
while True:
await asyncio.sleep(5)
for _, bridge in self._bridges.items():
bridge.commmunicate()

def stop(self) -> None:
logging.debug("Stopping Bridget and removing all bridges.")
for bridge_spec in self._bridges:
Expand Down
11 changes: 9 additions & 2 deletions core/services/bridget/main.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
#! /usr/bin/env python3
import asyncio
import logging
from typing import Any, List

import uvicorn
from commonwealth.utils.apis import GenericErrorHandlingRoute, PrettyJSONResponse
from commonwealth.utils.logs import InterceptHandler, init_logger
from fastapi import FastAPI, status
from fastapi.responses import HTMLResponse
from fastapi_versioning import VersionedFastAPI, version
from loguru import logger
from uvicorn import Config, Server

from bridget import BridgeFrontendSpec, Bridget

Expand Down Expand Up @@ -76,5 +77,11 @@ async def read_items() -> Any:


if __name__ == "__main__":
loop = asyncio.new_event_loop()

# Running uvicorn with log disabled so loguru can handle it
uvicorn.run(app, host="0.0.0.0", port=27353, log_config=None)
config = Config(app=app, loop=loop, host="0.0.0.0", port=27353, log_config=None)
server = Server(config)

loop.create_task(controller.do_house_keeping())
loop.run_until_complete(server.serve())
Loading