""" 流水线:子进程执行 run.py → 将 accounts/oauth/*.json 迁到目标目录 → 可选钉钉通知。 - 独立进程:`python scripts/cpa_runner.py`(读环境变量 / .env) - 嵌入维护台:由 `maintain.app` 调用 `execute_pipeline_cycle`,配置来自 SQLite """ from __future__ import annotations import base64 import hashlib import hmac import json import logging import os import shutil import subprocess import time from dataclasses import dataclass from datetime import datetime from pathlib import Path from typing import Any, Callable, Optional from urllib.parse import quote_plus import requests from maintain.paths_config import CPA_AUTHS_DIR REPO_ROOT = Path(__file__).resolve().parent.parent logger = logging.getLogger("cpa-runner") def load_env(path: Path) -> None: if not path.exists(): return for line in path.read_text(encoding="utf-8").splitlines(): line = line.strip() if not line or line.startswith("#") or "=" not in line: continue key, value = line.split("=", 1) os.environ.setdefault(key.strip(), value.strip()) load_env(REPO_ROOT / ".env") load_env(REPO_ROOT / ".env.cpa-runner") def env_int(name: str, default: int) -> int: value = os.getenv(name, str(default)).strip() try: return int(value) except ValueError: return default def env_bool(name: str, default: bool) -> bool: v = os.getenv(name, "").strip().lower() if not v: return default return v in ("1", "true", "yes", "on") @dataclass class RunnerConfig: run_script: Path oauth_dir: Path target_dir: Path python_bin: str = "python3" dingtalk_webhook: str = "" dingtalk_secret: str = "" exit_on_zero_moved: bool = True subprocess_timeout_sec: int = 60 * 8 state_file: Path = REPO_ROOT / "maintain" / "data" / "pipeline_state.json" log_file: Path = REPO_ROOT / "maintain" / "data" / "cpa_runner.log" lock_file: Path = REPO_ROOT / "maintain" / "data" / "cpa_runner.lock" def runner_config_from_env() -> RunnerConfig: return RunnerConfig( run_script=Path( os.getenv("RUN_SCRIPT", str(REPO_ROOT / "run.py")) ).resolve(), oauth_dir=Path( os.getenv("OAUTH_DIR", str(REPO_ROOT / "accounts" / "oauth")) ).resolve(), target_dir=Path( os.getenv( "TARGET_DIR", CPA_AUTHS_DIR, ) ).resolve(), python_bin=os.getenv("PYTHON_BIN", "python3"), dingtalk_webhook=os.getenv("DINGTALK_WEBHOOK", "").strip(), dingtalk_secret=os.getenv("DINGTALK_SECRET", "").strip(), exit_on_zero_moved=env_bool("CPA_EXIT_ON_EMPTY", True), subprocess_timeout_sec=env_int("RUN_SUBPROCESS_TIMEOUT_SEC", 60 * 8), state_file=Path( os.getenv( "STATE_FILE", str(REPO_ROOT / "maintain" / "data" / "pipeline_state.json"), ) ).resolve(), log_file=Path( os.getenv( "LOG_FILE", str(REPO_ROOT / "maintain" / "data" / "cpa_runner.log"), ) ).resolve(), lock_file=Path( os.getenv( "LOCK_FILE", str(REPO_ROOT / "maintain" / "data" / "cpa_runner.lock"), ) ).resolve(), ) CONFIG = runner_config_from_env() DEFAULT_STATE: dict[str, Any] = { "last_run_at": None, "last_notify_at": None, "last_run_moved": 0, "last_run_return_code": None, "last_stdout_tail": "", "last_stderr_tail": "", "last_error": "", } LOCK_HANDLE: Any = None def _setup_cli_logging(cfg: RunnerConfig) -> None: cfg.log_file.parent.mkdir(parents=True, exist_ok=True) if logger.handlers: return logger.setLevel(logging.INFO) fmt = logging.Formatter("%(asctime)s [%(levelname)s] %(message)s") fh = logging.FileHandler(cfg.log_file, encoding="utf-8") fh.setFormatter(fmt) sh = logging.StreamHandler() sh.setFormatter(fmt) logger.addHandler(fh) logger.addHandler(sh) def ensure_pipeline_file_handler(cfg: RunnerConfig) -> None: """ 嵌入维护台时 cpa-runner 可能已有 StreamHandler 而无 FileHandler; 保证流水线日志写入 cfg.log_file(run.py 输出等)。 """ cfg.log_file.parent.mkdir(parents=True, exist_ok=True) logger.setLevel(logging.INFO) fmt = logging.Formatter("%(asctime)s [%(levelname)s] %(message)s") want = str(cfg.log_file.resolve()) for h in logger.handlers: if isinstance(h, logging.FileHandler): try: if os.path.abspath(h.baseFilename) == want: return except (OSError, ValueError, AttributeError): continue fh = logging.FileHandler(cfg.log_file, encoding="utf-8") fh.setFormatter(fmt) logger.addHandler(fh) def load_state(path: Path) -> dict[str, Any]: if path.exists(): try: return {**DEFAULT_STATE, **json.loads(path.read_text(encoding="utf-8"))} except Exception as e: logger.warning("load state failed: %s", e) return {**DEFAULT_STATE} def save_state(path: Path, state: dict[str, Any]) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(state, ensure_ascii=False, indent=2), encoding="utf-8") def acquire_single_instance_lock(cfg: RunnerConfig) -> None: global LOCK_HANDLE try: import fcntl except ImportError: logger.warning("fcntl unavailable, skip single-instance lock (non-Unix)") return cfg.lock_file.parent.mkdir(parents=True, exist_ok=True) lock_handle = cfg.lock_file.open("w") try: fcntl.flock(lock_handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError: logger.error( "another cpa-runner instance is already running, lock=%s", cfg.lock_file ) raise SystemExit(1) lock_handle.write(str(os.getpid())) lock_handle.flush() LOCK_HANDLE = lock_handle def build_dingtalk_url(webhook: str, secret: str) -> str: if not secret: return webhook timestamp = str(round(time.time() * 1000)) sign_data = f"{timestamp}\n{secret}".encode("utf-8") sign = quote_plus( base64.b64encode( hmac.new(secret.encode("utf-8"), sign_data, digestmod=hashlib.sha256).digest() ) ) sep = "&" if "?" in webhook else "?" return f"{webhook}{sep}timestamp={timestamp}&sign={sign}" def send_dingtalk(cfg: RunnerConfig, payload: dict) -> bool: if not cfg.dingtalk_webhook: logger.info("skip notify: dingtalk webhook empty") return False url = build_dingtalk_url(cfg.dingtalk_webhook, cfg.dingtalk_secret) try: resp = requests.post(url, json=payload, timeout=15) resp.raise_for_status() data = resp.json() if data.get("errcode") != 0: logger.error("dingtalk notify failed: %s", data) return False return True except Exception as e: logger.exception("send dingtalk notify error: %s", e) return False def send_dingtalk_markdown(cfg: RunnerConfig, title: str, markdown_text: str) -> bool: return send_dingtalk( cfg, { "msgtype": "markdown", "markdown": {"title": title, "text": markdown_text}, }, ) def format_ts(ts: Optional[int]) -> str: if not ts: return "-" return datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M:%S") def _tail(s: str, n: int = 4000) -> str: s = (s or "").strip() if len(s) <= n: return s return "…" + s[-n:] def build_status_markdown( *, moved: int, return_code: int, title: str, status_label: str, status_emoji: str, state: dict[str, Any], cfg: RunnerConfig, note: Optional[str] = None, ) -> str: lines = [ f"# {status_emoji} {title}", "", f"> 状态:**{status_label}**", "", f"- 本次迁出 JSON:**{moved}** 个", f"- run.py 返回码:**{return_code}**", f"- 执行时间:`{format_ts(state.get('last_run_at'))}`", f"- 目标目录:`{cfg.target_dir}`", ] if note: lines.extend(["", f"> {note}"]) return "\n".join(lines) def move_json_files(cfg: RunnerConfig) -> int: moved = 0 if not cfg.oauth_dir.exists(): logger.warning("oauth dir not found: %s", cfg.oauth_dir) return 0 cfg.target_dir.mkdir(parents=True, exist_ok=True) for src in sorted(cfg.oauth_dir.glob("*.json")): target = cfg.target_dir / src.name if target.exists(): stem = src.stem suffix = src.suffix target = cfg.target_dir / f"{stem}_{int(time.time())}{suffix}" shutil.move(str(src), str(target)) moved += 1 logger.info("moved json: %s -> %s", src, target) return moved def execute_pipeline_cycle( cfg: RunnerConfig, state: dict[str, Any], *, allow_sys_exit_on_empty: bool = False, ) -> dict[str, Any]: """ 执行一次:run.py → 迁出 oauth json → 钉钉。 返回更新后的 state(调用方负责 save_state)。 allow_sys_exit_on_empty:仅独立脚本进程应为 True。 """ out = {**DEFAULT_STATE, **state} ensure_pipeline_file_handler(cfg) logger.info("pipeline cycle start run_script=%s", cfg.run_script) cmd = [cfg.python_bin, str(cfg.run_script)] try: completed = subprocess.run( cmd, cwd=str(cfg.run_script.parent), capture_output=True, text=True, timeout=cfg.subprocess_timeout_sec, ) rc = completed.returncode logger.info("run.py return code: %s", rc) if completed.stdout: logger.info("run.py stdout:\n%s", completed.stdout.strip()) if completed.stderr: logger.warning("run.py stderr:\n%s", completed.stderr.strip()) out["last_stdout_tail"] = _tail(completed.stdout or "") out["last_stderr_tail"] = _tail(completed.stderr or "") out["last_error"] = "" moved = move_json_files(cfg) out["last_run_moved"] = moved out["last_run_return_code"] = rc out["last_run_at"] = int(time.time()) if moved == 0: md = build_status_markdown( moved=moved, return_code=rc, title="流水线告警", status_label="未迁出任何 JSON", status_emoji="🚨", state=out, cfg=cfg, note=f"OAuth 目录:`{cfg.oauth_dir}`", ) send_dingtalk_markdown(cfg, "流水线告警", md) logger.warning("pipeline: moved=0, alert sent") if cfg.exit_on_zero_moved and allow_sys_exit_on_empty: raise SystemExit(0) else: md = build_status_markdown( moved=moved, return_code=rc, title="流水线战报", status_label="执行完成", status_emoji="✅", state=out, cfg=cfg, ) send_dingtalk_markdown(cfg, "流水线战报", md) out["last_notify_at"] = int(time.time()) logger.info("pipeline done moved=%s", moved) except subprocess.TimeoutExpired: logger.exception("run.py timeout") out["last_run_return_code"] = -1 out["last_run_at"] = int(time.time()) out["last_error"] = "subprocess timeout" except Exception as e: logger.exception("execute_pipeline_cycle failed") out["last_run_return_code"] = -2 out["last_run_at"] = int(time.time()) out["last_error"] = str(e)[:500] return out def run_once_cli() -> None: """独立进程入口使用:读 CONFIG,写 state 文件。""" global CONFIG CONFIG = runner_config_from_env() _setup_cli_logging(CONFIG) CONFIG.target_dir.mkdir(parents=True, exist_ok=True) st = load_state(CONFIG.state_file) st = execute_pipeline_cycle(CONFIG, st, allow_sys_exit_on_empty=True) save_state(CONFIG.state_file, st) def main_blocking() -> None: from apscheduler.schedulers.blocking import BlockingScheduler from apscheduler.triggers.interval import IntervalTrigger global CONFIG CONFIG = runner_config_from_env() _setup_cli_logging(CONFIG) acquire_single_instance_lock(CONFIG) logger.info("cpa-runner (standalone) starting") logger.info("run_script=%s", CONFIG.run_script) logger.info("interval_min=%s", env_int("RUN_EVERY_MINUTES", 10)) scheduler = BlockingScheduler(timezone="Asia/Shanghai") scheduler.add_job( run_once_cli, IntervalTrigger(minutes=env_int("RUN_EVERY_MINUTES", 10)), id="run_job", max_instances=1, coalesce=True, ) run_once_cli() scheduler.start() def runner_config_from_db(get_setting: Callable[[str, str], str]) -> RunnerConfig: """从维护台 SQLite settings 构造配置。""" g = get_setting return RunnerConfig( run_script=Path( g("pipeline_run_script", str(REPO_ROOT / "run.py")) ).resolve(), oauth_dir=Path( g("pipeline_oauth_dir", str(REPO_ROOT / "accounts" / "oauth")) ).resolve(), target_dir=Path(g("cpa_target_dir", CPA_AUTHS_DIR)).resolve(), python_bin=g("pipeline_python_bin", "python3"), dingtalk_webhook=g("dingtalk_webhook", "").strip(), dingtalk_secret=g("dingtalk_secret", "").strip(), exit_on_zero_moved=g("cpa_exit_on_empty", "0") == "1", subprocess_timeout_sec=int(g("run_subprocess_timeout_sec", "480") or 480), state_file=Path( g( "pipeline_state_file", str(REPO_ROOT / "maintain" / "data" / "pipeline_state.json"), ) ).resolve(), log_file=Path( g( "pipeline_log_file", str(REPO_ROOT / "maintain" / "data" / "pipeline.log"), ) ).resolve(), lock_file=Path( g( "pipeline_lock_file", str(REPO_ROOT / "maintain" / "data" / "cpa_runner.lock"), ) ).resolve(), )