Server: basic implementation. Not tested => no python installed; bugfix in ESP (uvicorn on port 8090)
This commit is contained in:
1 parent
3694cdf207
commit
8a51e3d95e
38 files changed
+2442
-21
No files matched your search
@@ -0,0 +1,164 @@
|
||||
"""Entry points.
|
||||
|
||||
``poorbird check`` is the one to reach for first on a fresh machine: it
|
||||
validates config, storage paths and database connectivity and prints what it
|
||||
found, without starting anything.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from . import __version__
|
||||
from .config import get_settings
|
||||
from .logging_setup import configure_logging
|
||||
|
||||
|
||||
def _alembic_config():
|
||||
from alembic.config import Config
|
||||
|
||||
candidate = Path(os.environ.get("POORBIRD_ALEMBIC_INI", "alembic.ini"))
|
||||
if not candidate.is_absolute():
|
||||
candidate = Path.cwd() / candidate
|
||||
if not candidate.exists():
|
||||
raise SystemExit(
|
||||
f"alembic.ini not found at {candidate}. Run from the server/ directory, "
|
||||
"or set POORBIRD_ALEMBIC_INI."
|
||||
)
|
||||
cfg = Config(str(candidate))
|
||||
cfg.set_main_option("script_location", str(candidate.parent / "migrations"))
|
||||
return cfg
|
||||
|
||||
|
||||
def cmd_serve(args: argparse.Namespace) -> int:
|
||||
import uvicorn
|
||||
|
||||
settings = get_settings()
|
||||
uvicorn.run(
|
||||
"poorbird.api.app:app",
|
||||
host=args.host or settings.api_host,
|
||||
port=args.port or settings.api_port,
|
||||
reload=args.reload,
|
||||
log_config=None, # our own stdout logging, see logging_setup
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_worker(_args: argparse.Namespace) -> int:
|
||||
from .worker import run
|
||||
|
||||
return run()
|
||||
|
||||
|
||||
def cmd_migrate(_args: argparse.Namespace) -> int:
|
||||
from alembic import command
|
||||
|
||||
command.upgrade(_alembic_config(), "head")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_enqueue(args: argparse.Namespace) -> int:
|
||||
from .db import SessionLocal
|
||||
from .worker.queue import enqueue
|
||||
|
||||
payload = json.loads(args.payload) if args.payload else {}
|
||||
with SessionLocal() as session:
|
||||
job = enqueue(session, args.kind, payload)
|
||||
session.commit()
|
||||
print(f"queued job {job.id} ({args.kind})")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_check(_args: argparse.Namespace) -> int:
|
||||
settings = get_settings()
|
||||
problems: list[str] = []
|
||||
|
||||
print(f"poorbird {__version__}")
|
||||
print(f" python {sys.version.split()[0]}")
|
||||
|
||||
# Never print the password.
|
||||
url = settings.database_url
|
||||
if "@" in url:
|
||||
scheme, _, rest = url.partition("://")
|
||||
url = f"{scheme}://***@{rest.rpartition('@')[2]}"
|
||||
print(f" database_url {url}")
|
||||
|
||||
try:
|
||||
from sqlalchemy import text
|
||||
|
||||
from .db import engine
|
||||
|
||||
with engine.connect() as conn:
|
||||
version = conn.execute(text("SHOW server_version")).scalar()
|
||||
print(f" database reachable (PostgreSQL {version})")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(f" database UNREACHABLE: {type(exc).__name__}: {exc}")
|
||||
problems.append("database unreachable")
|
||||
|
||||
try:
|
||||
from alembic import command
|
||||
|
||||
print(" migrations ", end="")
|
||||
command.current(_alembic_config())
|
||||
except SystemExit as exc:
|
||||
print(f"not checked ({exc})")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(f"error: {type(exc).__name__}: {exc}")
|
||||
|
||||
for path in settings.storage_paths():
|
||||
if not path.exists():
|
||||
print(f" path {path} MISSING")
|
||||
problems.append(f"{path} missing")
|
||||
elif not os.access(path, os.W_OK):
|
||||
print(f" path {path} NOT WRITABLE")
|
||||
problems.append(f"{path} not writable")
|
||||
else:
|
||||
print(f" path {path} ok")
|
||||
|
||||
if not settings.enroll_secret_is_set:
|
||||
print(" enroll_secret NOT SET (fine for Phase 1, required for Phase 2)")
|
||||
|
||||
if problems:
|
||||
print(f"\n{len(problems)} problem(s): " + "; ".join(problems))
|
||||
return 1
|
||||
print("\nall checks passed")
|
||||
return 0
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(prog="poorbird", description="poorBird server")
|
||||
parser.add_argument("--version", action="version", version=__version__)
|
||||
sub = parser.add_subparsers(dest="command", required=True)
|
||||
|
||||
p = sub.add_parser("serve", help="run the HTTP API")
|
||||
p.add_argument("--host")
|
||||
p.add_argument("--port", type=int)
|
||||
p.add_argument("--reload", action="store_true", help="development only")
|
||||
p.set_defaults(func=cmd_serve)
|
||||
|
||||
p = sub.add_parser("worker", help="run the job queue worker and scheduler")
|
||||
p.set_defaults(func=cmd_worker)
|
||||
|
||||
p = sub.add_parser("migrate", help="apply migrations (alembic upgrade head)")
|
||||
p.set_defaults(func=cmd_migrate)
|
||||
|
||||
p = sub.add_parser("check", help="validate config, storage and database")
|
||||
p.set_defaults(func=cmd_check)
|
||||
|
||||
p = sub.add_parser("enqueue", help="put a job on the queue (smoke test)")
|
||||
p.add_argument("kind")
|
||||
p.add_argument("payload", nargs="?", help="JSON object")
|
||||
p.set_defaults(func=cmd_enqueue)
|
||||
|
||||
args = parser.parse_args(argv)
|
||||
settings = get_settings()
|
||||
configure_logging(settings.log_level, settings.log_format)
|
||||
return args.func(args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in new issue
Block a user