Browse Source

Fix for #107 - Main functions not running when using uvicorn

pull/109/head
Per-Arne Andersen 4 years ago
parent
commit
20eeecc86d
  1. 22
      wg-manager-backend/database/util.py
  2. 28
      wg-manager-backend/main.py
  3. 12
      wg-manager-backend/migrations/versions/4ac3e58519eb_base.py

22
wg-manager-backend/database/util.py

@ -1,4 +1,3 @@
import contextlib
import os import os
import alembic.command import alembic.command
@ -27,6 +26,7 @@ def perform_migrations():
def setup_initial_database(): def setup_initial_database():
if not database_exists(engine.url): if not database_exists(engine.url):
logger.info("Database does not exists. Creating initial database...") logger.info("Database does not exists. Creating initial database...")
# Create database from metadata # Create database from metadata
Base.metadata.create_all(engine) Base.metadata.create_all(engine)
logger.info("Database creation done!") logger.info("Database creation done!")
@ -34,25 +34,23 @@ def setup_initial_database():
# Create default user # Create default user
_db: Session = SessionLocal() _db: Session = SessionLocal()
admin_exists = ( # Retrieve user with admin role
_db.query(models.User.id) admin_exists = _db.query(models.User.id).filter_by(role="admin").first() is not None
.filter_by(role="admin")
.first()
) is not None
if not admin_exists: if not admin_exists:
logger.info("Admin user does not exists. Creating with env variables ADMIN_USERNAME, ADMIN_PASSWORD") logger.info("Admin user does not exists. Creating with env variables ADMIN_USERNAME, ADMIN_PASSWORD")
ADMIN_USERNAME = os.getenv("ADMIN_USERNAME") env_admin_username = os.getenv("ADMIN_USERNAME")
ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD") env_admin_password = os.getenv("ADMIN_PASSWORD")
if not ADMIN_USERNAME: if not env_admin_username:
raise RuntimeError("Database does not exist and the environment variable ADMIN_USERNAME is set") raise RuntimeError("Database does not exist and the environment variable ADMIN_USERNAME is set")
if not ADMIN_PASSWORD:
if not env_admin_password:
raise RuntimeError("Database does not exist and the environment variable ADMIN_PASSWORD is set") raise RuntimeError("Database does not exist and the environment variable ADMIN_PASSWORD is set")
_db.merge(models.User( _db.merge(models.User(
username=ADMIN_USERNAME, username=env_admin_username,
password=middleware.get_password_hash(ADMIN_PASSWORD), password=middleware.get_password_hash(env_admin_password),
full_name="Admin", full_name="Admin",
role="admin", role="admin",
email="" email=""

28
wg-manager-backend/main.py

@ -67,17 +67,7 @@ def root():
app.mount("/", StaticFiles(directory=pkg_resources.resource_filename(__name__, 'build')), name="static") app.mount("/", StaticFiles(directory=pkg_resources.resource_filename(__name__, 'build')), name="static")
@app.on_event("startup") def main():
async def startup():
pass
@app.on_event("shutdown")
async def shutdown():
pass
if __name__ == "__main__":
# Sleep the wait timer. # Sleep the wait timer.
time.sleep(const.INIT_SLEEP) time.sleep(const.INIT_SLEEP)
@ -90,6 +80,22 @@ if __name__ == "__main__":
# Configure wireguard # Configure wireguard
script.wireguard_startup.setup_on_start() script.wireguard_startup.setup_on_start()
@app.on_event("startup")
async def startup():
if __name__ != "__main__":
main()
@app.on_event("shutdown")
async def shutdown():
pass
if __name__ == "__main__":
main()
run_uvicorn_loguru( run_uvicorn_loguru(
uvicorn.Config( uvicorn.Config(
"__main__:app", "__main__:app",

12
wg-manager-backend/migrations/versions/4ac3e58519eb_base.py

@ -8,7 +8,6 @@ Create Date: 2021-03-13 20:29:10.062757
from alembic import op from alembic import op
import sqlalchemy as sa import sqlalchemy as sa
# revision identifiers, used by Alembic. # revision identifiers, used by Alembic.
from sqlalchemy.exc import OperationalError from sqlalchemy.exc import OperationalError
@ -17,6 +16,7 @@ down_revision = None
branch_labels = None branch_labels = None
depends_on = None depends_on = None
def ignore_duplicate(fn): def ignore_duplicate(fn):
try: try:
fn() fn()
@ -24,6 +24,7 @@ def ignore_duplicate(fn):
if "duplicate" in str(e): if "duplicate" in str(e):
pass pass
def upgrade(): def upgrade():
# ### commands auto generated by Alembic - please adjust! ### # ### commands auto generated by Alembic - please adjust! ###
try: try:
@ -32,7 +33,8 @@ def upgrade():
sa.Column('key', sa.String(), nullable=True), sa.Column('key', sa.String(), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True), sa.Column('user_id', sa.Integer(), nullable=True),
sa.Column('created_date', sa.DateTime(), nullable=True), sa.Column('created_date', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], name='fk_user_api_key_user_id', onupdate='CASCADE', ondelete='CASCADE'), sa.ForeignKeyConstraint(['user_id'], ['users.id'], name='fk_user_api_key_user_id',
onupdate='CASCADE', ondelete='CASCADE'),
sa.PrimaryKeyConstraint('id'), sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('key') sa.UniqueConstraint('key')
) )
@ -51,7 +53,8 @@ def upgrade():
batch_op.drop_constraint("fk_peer_server_id_server", type_="foreignkey") batch_op.drop_constraint("fk_peer_server_id_server", type_="foreignkey")
with op.batch_alter_table('peer', schema=None) as batch_op: with op.batch_alter_table('peer', schema=None) as batch_op:
batch_op.create_foreign_key('fk_peer_server_id_server', 'server', ['server_id'], ['id'], onupdate='CASCADE', ondelete='CASCADE') batch_op.create_foreign_key('fk_peer_server_id_server', 'server', ['server_id'], ['id'], onupdate='CASCADE',
ondelete='CASCADE')
ignore_duplicate(lambda: op.add_column('peer', sa.Column('configuration', sa.Text(), nullable=True))) ignore_duplicate(lambda: op.add_column('peer', sa.Column('configuration', sa.Text(), nullable=True)))
ignore_duplicate(lambda: op.add_column('peer', sa.Column('keep_alive', sa.Integer(), nullable=True))) ignore_duplicate(lambda: op.add_column('peer', sa.Column('keep_alive', sa.Integer(), nullable=True)))
@ -60,12 +63,10 @@ def upgrade():
ignore_duplicate(lambda: op.add_column('peer', sa.Column('shared_key', sa.Text(), nullable=True))) ignore_duplicate(lambda: op.add_column('peer', sa.Column('shared_key', sa.Text(), nullable=True)))
ignore_duplicate(lambda: op.add_column('peer', sa.Column('v6_address', sa.String(), nullable=True))) ignore_duplicate(lambda: op.add_column('peer', sa.Column('v6_address', sa.String(), nullable=True)))
# op.drop_constraint(None, 'peer', type_='foreignkey') # op.drop_constraint(None, 'peer', type_='foreignkey')
# #
# op.drop_column('peer', 'server') # op.drop_column('peer', 'server')
try: try:
with op.batch_alter_table('peer', schema=None) as batch_op: with op.batch_alter_table('peer', schema=None) as batch_op:
batch_op.drop_column("server") batch_op.drop_column("server")
@ -82,7 +83,6 @@ def upgrade():
ignore_duplicate(lambda: op.add_column('server', sa.Column('v6_subnet', sa.Integer(), nullable=False))) ignore_duplicate(lambda: op.add_column('server', sa.Column('v6_subnet', sa.Integer(), nullable=False)))
# op.create_unique_constraint(None, 'server', ['v6_address']) # op.create_unique_constraint(None, 'server', ['v6_address'])
try: try:
with op.batch_alter_table('server', schema=None) as batch_op: with op.batch_alter_table('server', schema=None) as batch_op:
batch_op.drop_column("shared_key") batch_op.drop_column("shared_key")

Loading…
Cancel
Save