Skip to content

Commit

Permalink
uvicorn: add support for restarting uvicorn
Browse files Browse the repository at this point in the history
Also add gstate property to request uvicorn restart.

Signed-off-by: Joshua Hesketh <jhesketh@suse.com>
  • Loading branch information
jhesketh committed Dec 14, 2021
1 parent a138cd6 commit fbe895e
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
10 changes: 6 additions & 4 deletions src/aquarium.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,8 +152,6 @@ def __init__(self):
self.static_dir = os.path.join(
os.path.dirname(os.path.realpath(__file__)), "glass/dist/"
)
# TODO(jhesketh): Move KV store set up here so we can use it
# to watch for certs.

async def bootstrap(self):
logger.info("Aquarium startup!")
Expand Down Expand Up @@ -230,11 +228,13 @@ async def shutdown(self):

async def main_loop(self):
while not self._is_shutting_down:
if self.gstate.requesting_uvicorn_restart:
await self.restart_uvicorn()
self.gstate.reset_uvicorn_restart()
await asyncio.sleep(1)
# TODO(jhesketh): Watch KV store and restart uvicorn if updates to
# certs.

async def start_uvicorn(self):
logger.debug("Starting uvicorn")
# TODO(jhesketh): Check if we need https or not
uvicorn_config = Config(self.app, host="0.0.0.0", port=80)
self.uvicorn = AquariumUvicorn(config=uvicorn_config)
Expand All @@ -243,11 +243,13 @@ async def start_uvicorn(self):
# instance will work to create http redirect.

async def stop_uvicorn(self):
logger.debug("Stopping uvicorn")
self.uvicorn.should_exit = True
while self.uvicorn._running:
await asyncio.sleep(0.1)

async def restart_uvicorn(self):
logger.debug("Restarting uvicorn")
await self.stop_uvicorn()
await self.start_uvicorn()

Expand Down
12 changes: 12 additions & 0 deletions src/gravel/controllers/gstate.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ class GlobalState:

_config: Config
_is_shutting_down: bool
_requesting_uvicorn_restart: bool
_tickers: Dict[str, Ticker]
_kvstore: KV
devices: Devices
Expand All @@ -140,6 +141,7 @@ class GlobalState:
def __init__(self, kv_class: Type[KV] = KV):
self._config = Config()
self._is_shutting_down = False
self._requesting_uvicorn_restart = False
self._tickers = {}
self._kvstore = kv_class()

Expand Down Expand Up @@ -213,10 +215,20 @@ def rm_ticker(self, desc: str) -> None:
def get_ticker(self, desc: str) -> Ticker:
return self._tickers[desc]

def request_restart_uvicorn(self) -> None:
self._requesting_uvicorn_restart = True

def reset_uvicorn_restart(self) -> None:
self._requesting_uvicorn_restart = False

@property
def config(self) -> Config:
return self._config

@property
def store(self) -> KV:
return self._kvstore

@property
def requesting_uvicorn_restart(self) -> bool:
return self._requesting_uvicorn_restart

0 comments on commit fbe895e

Please sign in to comment.