feat: 管理后台可动态调整采集和导出的并行数量
This commit is contained in:
+107
-2
@@ -2,10 +2,17 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import contextlib
|
||||
import logging
|
||||
|
||||
import procrastinate
|
||||
from procrastinate.worker import Worker
|
||||
|
||||
from app.config import postgres_conninfo
|
||||
from app.tasks.runner import execute_collection, execute_export
|
||||
from app.tasks.runner import current_concurrency, execute_collection, execute_export
|
||||
|
||||
logger = logging.getLogger("decom")
|
||||
|
||||
conninfo = postgres_conninfo() or "postgresql://invalid"
|
||||
queue = procrastinate.App(connector=procrastinate.PsycopgConnector(conninfo=conninfo))
|
||||
@@ -26,6 +33,97 @@ def defer(name: str, **kwargs) -> None:
|
||||
job.defer(**kwargs)
|
||||
|
||||
|
||||
class DynamicGate:
|
||||
"""正在执行的数量低于目标才允许再领任务。调小目标时不打断已开始的任务。"""
|
||||
|
||||
def __init__(self, limit: int) -> None:
|
||||
self._limit = limit
|
||||
self._held = 0
|
||||
self._waiters: list[asyncio.Event] = []
|
||||
|
||||
@property
|
||||
def limit(self) -> int:
|
||||
return self._limit
|
||||
|
||||
@property
|
||||
def held(self) -> int:
|
||||
return self._held
|
||||
|
||||
def set_limit(self, value: int) -> None:
|
||||
self._limit = value
|
||||
self._wake()
|
||||
|
||||
async def acquire(self) -> None:
|
||||
while True:
|
||||
if self._held < self._limit:
|
||||
self._held += 1
|
||||
return
|
||||
event = asyncio.Event()
|
||||
self._waiters.append(event)
|
||||
await event.wait()
|
||||
|
||||
def release(self) -> None:
|
||||
self._held = max(0, self._held - 1)
|
||||
self._wake()
|
||||
|
||||
def _wake(self) -> None:
|
||||
waiters = self._waiters
|
||||
self._waiters = []
|
||||
for event in waiters:
|
||||
event.set()
|
||||
|
||||
|
||||
class DynamicWorker(Worker):
|
||||
def __init__(self, gate: DynamicGate, **kwargs) -> None:
|
||||
self._gate = gate
|
||||
super().__init__(**kwargs)
|
||||
|
||||
async def _watch_limit(self) -> None:
|
||||
while not self._stop_event.is_set():
|
||||
try:
|
||||
limit = await asyncio.to_thread(current_concurrency)
|
||||
if limit != self._gate.limit:
|
||||
logger.info("并行数量改为 %s", limit)
|
||||
self._gate.set_limit(limit)
|
||||
except Exception as exc:
|
||||
logger.info("读取并行数量未完成: %s", exc)
|
||||
await asyncio.sleep(2)
|
||||
|
||||
async def _run_loop(self) -> None:
|
||||
from procrastinate import signals, utils
|
||||
|
||||
self.logger.info(
|
||||
f"Starting worker on {utils.queues_display(self.queues)}",
|
||||
extra=self._log_extra(action="start_worker", context=None, queues=self.queues, job_result=None),
|
||||
)
|
||||
self._new_job_event.clear()
|
||||
self._running_jobs = {}
|
||||
self._job_semaphore = self._gate
|
||||
watch = asyncio.create_task(self._watch_limit(), name="decom-concurrency")
|
||||
side_tasks = self._start_side_tasks()
|
||||
side_tasks_monitor = asyncio.create_task(self._monitor_side_tasks(side_tasks), name="side_tasks_monitor")
|
||||
context = signals.on_stop(self.stop) if self.install_signal_handlers else contextlib.nullcontext()
|
||||
try:
|
||||
with context:
|
||||
await self._fetch_and_process_jobs()
|
||||
if not self.wait:
|
||||
self._stop_event.set()
|
||||
while not self._stop_event.is_set():
|
||||
await utils.wait_any(
|
||||
self._new_job_event.wait(),
|
||||
asyncio.sleep(self.fetch_job_polling_interval),
|
||||
self._stop_event.wait(),
|
||||
)
|
||||
await self._fetch_and_process_jobs()
|
||||
finally:
|
||||
watch.cancel()
|
||||
with contextlib.suppress(asyncio.CancelledError):
|
||||
await watch
|
||||
if not side_tasks_monitor.done():
|
||||
side_tasks_monitor.cancel()
|
||||
await self._shutdown(side_tasks=side_tasks)
|
||||
|
||||
|
||||
def serve() -> None:
|
||||
import logging
|
||||
|
||||
@@ -35,4 +133,11 @@ def serve() -> None:
|
||||
queue.schema_manager.apply_schema()
|
||||
except Exception as exc:
|
||||
logger.info("队列结构已存在: %s", exc)
|
||||
queue.run_worker(queues=["decom"], concurrency=4)
|
||||
|
||||
async def run() -> None:
|
||||
gate = DynamicGate(current_concurrency())
|
||||
async with queue.open_async():
|
||||
worker = DynamicWorker(app=queue, gate=gate, queues=["decom"])
|
||||
await worker.run()
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
Reference in New Issue
Block a user