fix: 单实例锁、应用日志和容器健康检查
This commit is contained in:
@@ -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
|
||||
Reference in New Issue
Block a user