Skip to content

Commit

Permalink
fix: database credential access in Docker build (#90)
Browse files Browse the repository at this point in the history
  • Loading branch information
holtgrewe authored Oct 2, 2023
1 parent 81bfd43 commit 2d8f3ca
Show file tree
Hide file tree
Showing 5 changed files with 36 additions and 19 deletions.
1 change: 1 addition & 0 deletions backend/.dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.env
19 changes: 12 additions & 7 deletions backend/app/backend_pre_start.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import asyncio
import logging

from sqlalchemy import text
from tenacity import after_log, before_log, retry, stop_after_attempt, wait_fixed

from app.db.session import SyncSessionLocal
import alembic.config
from app.db.session import SessionLocal

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
Expand All @@ -18,21 +20,24 @@
before=before_log(logger, logging.INFO),
after=after_log(logger, logging.WARN),
)
def init() -> None:
async def init():
try:
db = SyncSessionLocal()
db = SessionLocal()
# Try to create session to check if DB is awake
db.execute(text("SELECT 1"))
await db.execute(text("SELECT 1"))
# Ensure to run Alembic on startup
alembicArgs = ["--raiseerr", "upgrade", "head"]
alembic.config.main(alembicArgs)
except Exception as e:
logger.error(e)
raise e


def main() -> None:
async def main():
logger.info("Initializing service")
init()
await init()
logger.info("Service finished initializing")


if __name__ == "__main__":
main()
asyncio.run(main())
27 changes: 21 additions & 6 deletions backend/app/core/config.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import logging
import os
import secrets
from typing import Any
Expand All @@ -8,6 +9,9 @@

from app.schemas import OAuth2ProviderConfig

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


class Settings(BaseSettings):
model_config = SettingsConfigDict(
Expand Down Expand Up @@ -50,7 +54,7 @@ def assemble_reev_version(cls, v: str | None, info: ValidationInfo) -> str | Non
# == security-related settings ==

#: Secret key
SECRET_KEY: str = secrets.token_urlsafe(32) # TODO: load from config
SECRET_KEY: str = secrets.token_urlsafe(32)
#: Expiration of cookies.
SESSION_EXPIRE_MINUTES: int = 60 * 24 * 8
#: Expiry of access token (60 minutes * 24 hours * 8 days = 8 days)
Expand Down Expand Up @@ -106,15 +110,17 @@ def assemble_cors_origins(cls, v: str | list[str]) -> list[str] | str: # pragma
# sqlite database (test use only).

#: Postgres hostname
POSTGRES_HOST: str | None = None
POSTGRES_HOST: str = "postgres"
#: Postgres port
POSTGRES_PORT: int = 5432
#: Postgres user
POSTGRES_USER: str | None = None
POSTGRES_USER: str = "reev"
#: Postgres password file
POSTGRES_PASSWORD_FILE: str | None = None
#: Postgres password
POSTGRES_PASSWORD: str | None = None
#: Postgres database name
POSTGRES_DB: str | None = None
POSTGRES_DB: str = "reev"
#: SQLAlchemy Postgres DSN
SQLALCHEMY_DATABASE_URI: PostgresDsn | str | None = None

Expand All @@ -125,14 +131,23 @@ def assemble_db_connection(cls, v: str | None, info: ValidationInfo) -> Any:
elif isinstance(v, str): # pragma: no cover
return v
else:
return PostgresDsn.build(
password_file = info.data.get("POSTGRES_PASSWORD_FILE")
if password_file:
logger.info(f"Reading password from {password_file}")
with open(password_file, "rt") as inputf:
password = inputf.read().strip()
else:
password = None
dsn = PostgresDsn.build(
scheme="postgresql+asyncpg",
username=info.data.get("POSTGRES_USER"),
password=info.data.get("POSTGRES_PASSWORD"),
password=info.data.get("POSTGRES_PASSWORD", password),
host=info.data.get("POSTGRES_HOST"),
port=info.data.get("POSTGRES_PORT"),
path=f"{info.data.get('POSTGRES_DB') or ''}",
)
logger.info(f"DNS={dsn} %s" % (password,))
return dsn

# -- Email Sending Configuration -----------------------------------------

Expand Down
5 changes: 0 additions & 5 deletions backend/app/db/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,4 @@
autocommit=False, autoflush=False, expire_on_commit=False, bind=engine
)

#: Sync engine for Alembic migrations.
sync_engine = create_engine(str(settings.SQLALCHEMY_DATABASE_URI), pool_pre_ping=True)
# Sync session, to be used for Alembic migrations.
SyncSessionLocal = sessionmaker(autocommit=False, expire_on_commit=False, bind=sync_engine)

Base = declarative_base()
3 changes: 2 additions & 1 deletion utils/docker/entrypoint.sh
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ set -euo pipefail
HTTP_HOST=${HTTP_HOST-0.0.0.0}
HTTP_PORT=${HTTP_PORT-8080}

python /home/reev/app/backend_pre_start.py
cd /home/reev && \
PYTHONPATH=. python app/backend_pre_start.py

uvicorn app.main:app --host $HTTP_HOST --port $HTTP_PORT

0 comments on commit 2d8f3ca

Please sign in to comment.