fixed exit on migration exception

This commit is contained in:
magowiz 2021-12-14 22:37:49 +01:00
parent c27a18cc17
commit e836e51ee4
1 changed files with 24 additions and 46 deletions

View File

@ -1,5 +1,5 @@
import logging
import asyncio
import sys
from pathlib import Path
from tortoise import Tortoise
from aerich import Command
@ -23,47 +23,26 @@ def get_db_url():
return db_url
TORTOISE_ORM = {
"connections": {"default": get_db_url()},
"apps": {
"models": {
"models": ["mobilizon_reshare.models.event",
"mobilizon_reshare.models.notification",
"mobilizon_reshare.models.publication",
"mobilizon_reshare.models.publisher", "aerich.models"],
"default_connection": "default",
def get_tortoise_orm():
return {
"connections": {"default": get_db_url()},
"apps": {
"models": {
"models": [
"mobilizon_reshare.models.event",
"mobilizon_reshare.models.notification",
"mobilizon_reshare.models.publication",
"mobilizon_reshare.models.publisher",
"aerich.models",
],
"default_connection": "default",
},
},
},
}
async def shutdown(loop):
"""shutdown method"""
logging.critical("SHUTDOWN CALLED")
logging.info("closing database connections")
tasks = [t for t in asyncio.all_tasks() if t is asyncio.current_task()]
_ = [task.cancel() for task in tasks]
logging.info("Cancelling %i tasks", len(tasks))
await asyncio.gather(*tasks, return_exceptions=True)
logging.info("flushing metrics")
loop.stop()
async def handle_exception(loop, context):
"""exception handler"""
logging.critical("HANDLER CALLED")
msg = context.get("exception", context["message"])
logging.critical("Caught exception: %s", msg)
logging.info("shutting down")
await shutdown(loop)
await tear_down()
}
class MoReDB:
def __init__(self, path: Path):
loop = asyncio.get_event_loop()
loop.set_exception_handler(handle_exception)
self.path = path
# TODO: Check if DB is openable/"queriable"
self.is_init = self.path.exists() and (not self.path.is_dir())
@ -74,21 +53,20 @@ class MoReDB:
logging.info("Updating database to latest version")
try:
command = Command(tortoise_config=TORTOISE_ORM, app='models',
location='./migrations')
command = Command(
tortoise_config=get_tortoise_orm(),
app="models",
location="./migrations",
)
await command.init()
await command.upgrade()
except FileNotFoundError:
logging.critical("aerich configuration not found, fatal error")
raise
await tear_down()
sys.exit(1)
async def setup(self):
implement_db_changes = asyncio.create_task(self._implement_db_changes())
_, _ = await asyncio.wait({implement_db_changes},
return_when=asyncio.FIRST_EXCEPTION)
if implement_db_changes.exception():
logging.critical("exception during aerich init")
raise implement_db_changes.exception()
await self._implement_db_changes()
await Tortoise.init(
db_url=get_db_url(),
modules={