Rewrote the Flask server into a FastAPI one that has Prometheus metrics and connects to a database

This commit is contained in:
florian committed 2025-10-09 20:21:04 +02:00
1 parent 0d04a0f790
commit db70de7659
13 files changed
+294 -124

No files matched your search

+113
View File
@@ -0,0 +1,113 @@
from fastapi import FastAPI, Depends, HTTPException, Response, Request
import uvicorn
from github_api import find_package_version_with_tag as find_package_version_with_tag_github
from dockerhub_api import find_package_version_with_tag as find_package_version_with_tag_dockerhub
import uvicorn
from contextlib import asynccontextmanager
from db import get_db, create_connection_pool, close_connection_pool
import logging
from send_notification import send_notification
from metrics_server import REQUEST_COUNTER
import asyncio
logger = logging.getLogger(__name__)
@asynccontextmanager
async def lifespan(app: FastAPI):
logger.info("Starting application...")
logger.info("Creating MySQL connection pool...")
create_connection_pool()
yield
logger.info("Closing MySQL connection pool...")
close_connection_pool()
api = FastAPI(
title="Docker Repository Query",
description="Queries Dockerhub and GHCR for new docker images",
version="1.0.0",
lifespan=lifespan
)
@api.middleware("http")
async def prometheus_middleware(request: Request, call_next):
try:
response = await call_next(request)
status = response.status_code
except Exception:
status = 500
raise
finally:
REQUEST_COUNTER.labels(request.method, request.url.path, status).inc()
return response
@api.get("/health")
def return_health():
return Response(status_code=200)
@api.get("/suwayomi")
def handle_suwayomi(
request: Request,
db = Depends(get_db)
):
try:
logger.info("Suwayomi handler invoked")
latest_online_version = find_package_version_with_tag_github("Suwayomi", "tachidesk", "stable")
cursor = db.cursor()
cursor.execute("SELECT latest_version FROM docker_repositories WHERE app='suwayomi'")
local_state = cursor.fetchone()
if local_state and latest_online_version != local_state[0]:
cursor.execute ("UPDATE docker_repositories SET latest_version=%s WHERE app='suwayomi'",
(latest_online_version,))
db.commit()
logger.info("New Suwayomi version has been found")
send_notification("New Suwayomi version has been found")
return Response(status_code=200)
return Response(status_code=204)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@api.get("/pihole")
def handle_pihole(
request: Request,
db = Depends(get_db)
):
try:
logger.info("Pi-hole handler invoked")
latest_online_version = find_package_version_with_tag_dockerhub("pihole/pihole", "latest")
cursor = db.cursor()
cursor.execute("SELECT latest_version FROM docker_repositories WHERE app='pihole'")
local_state = cursor.fetchone()
if local_state and latest_online_version != local_state[0]:
cursor.execute ("UPDATE docker_repositories SET latest_version=%s WHERE app='pihole'",
(latest_online_version,))
db.commit()
logger.info("New Pi-hole version has been found")
send_notification("New Pi-hole version has been found")
return Response(status_code=200)
return Response(status_code=204)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
async def start_servers():
config_main = uvicorn.Config("main:api", host="0.0.0.0", port=5000, log_level="info")
config_metrics = uvicorn.Config("metrics_server:metrics_api", host="0.0.0.0", port=9000, log_level="info")
server_main = uvicorn.Server(config_main)
server_metrics = uvicorn.Server(config_metrics)
await asyncio.gather(server_main.serve(), server_metrics.serve())
if __name__ == "__main__":
asyncio.run(start_servers())