fix: 单实例锁、应用日志和容器健康检查

This commit is contained in:
2026-11-16 09:32:33 +08:00
parent 990b80c017
commit 9c4f319908
10 changed files with 115 additions and 6 deletions
+2
View File
@@ -1,5 +1,7 @@
[alembic]
script_location = alembic
prepend_sys_path = .
path_separator = os
sqlalchemy.url = sqlite:///data/euniv.db
[loggers]
+29 -1
View File
@@ -3,10 +3,18 @@
from __future__ import annotations
import asyncio
import logging
import os
from contextlib import asynccontextmanager
from pathlib import Path
logging.basicConfig(
level=os.getenv("EUNIV_LOG_LEVEL", "INFO"),
format="%(asctime)s %(levelname)s %(name)s %(message)s",
)
logging.getLogger("httpx").setLevel(logging.WARNING)
logging.getLogger("httpcore").setLevel(logging.WARNING)
from fastapi import Depends, FastAPI, HTTPException, Request, Response, WebSocket, WebSocketDisconnect
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, Field
@@ -71,6 +79,11 @@ class StudyControlBody(_BaseModel):
@asynccontextmanager
async def lifespan(_app: FastAPI):
from euniv.instance_lock import acquire_instance_lock
acquire_instance_lock()
if os.environ.get("EUNIV_DISABLE_REFRESH") == "1":
logging.getLogger("euniv.api").warning("EUNIV_DISABLE_REFRESH=1,后台刷新、自动学习和代理池都不会启动")
init_db()
ensure_admin_seed()
from admin.settings import ensure_key_check
@@ -129,7 +142,22 @@ class QrPollBody(BaseModel):
@app.get("/api/health")
def health() -> dict:
return {"ok": True}
from sqlalchemy import text
from euniv.db import SessionLocal
with SessionLocal() as db:
db.execute(text("SELECT 1"))
study_alive = False
try:
from euniv import autostudy
worker = autostudy._worker
thread = getattr(worker, "_thread", None) if worker is not None else None
study_alive = bool(thread is not None and thread.is_alive())
except Exception:
study_alive = False
return {"ok": True, "database": True, "study": study_alive}
def _open_session(response: Response, payload: dict) -> dict:
+11 -3
View File
@@ -6,7 +6,7 @@ import base64
import hashlib
import os
from cryptography.fernet import Fernet
from cryptography.fernet import Fernet, MultiFernet
_PLACEHOLDER_SECRETS = {"请换成一串只放在服务器上的密钥"}
@@ -19,8 +19,16 @@ def require_secret() -> str:
return secret
def _fernet() -> Fernet:
digest = hashlib.sha256(require_secret().encode("utf-8")).digest()
def _fernet() -> MultiFernet:
fernets = [_one_fernet(require_secret())]
previous = os.environ.get("EUNIV_SECRET_KEY_OLD", "").strip()
if previous and previous != require_secret():
fernets.append(_one_fernet(previous))
return MultiFernet(fernets)
def _one_fernet(secret: str) -> Fernet:
digest = hashlib.sha256(secret.encode("utf-8")).digest()
return Fernet(base64.urlsafe_b64encode(digest))
+35
View File
@@ -0,0 +1,35 @@
"""保证同一份数据库只被一个进程使用。"""
from __future__ import annotations
import os
from pathlib import Path
_handle = None
def acquire_instance_lock() -> None:
global _handle
if _handle is not None:
return
database = os.environ.get("EUNIV_DB_PATH", "data/euniv.db")
path = Path(database).resolve().with_name("euniv.lock")
path.parent.mkdir(parents=True, exist_ok=True)
handle = path.open("a+b")
try:
if handle.seek(0, os.SEEK_END) == 0:
handle.write(b"\0")
handle.flush()
handle.seek(0)
if os.name == "nt":
import msvcrt
msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)
else:
import fcntl
fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
except OSError as exc:
handle.close()
raise SystemExit("已经有一个实例在使用这份数据库") from exc
_handle = handle
+1
View File
@@ -0,0 +1 @@
pytest==9.1.1
+1 -1
View File
@@ -1,5 +1,4 @@
httpx==0.28.1
socksio==1.0.0
httpx-socks==0.10.1
python-socks==3.2.1
sniffio==1.3.1
@@ -7,6 +6,7 @@ cryptography==50.0.2
pillow==13.0.0
qrcode==8.2
fastapi==0.162.0
starlette==1.10.0
uvicorn==0.54.0
wsproto==1.2.0
sqlalchemy==2.1.6