471 lines
17 KiB
Python
471 lines
17 KiB
Python
from __future__ import annotations
|
|
|
|
import threading
|
|
import time
|
|
import uuid
|
|
from datetime import datetime
|
|
from typing import Any
|
|
|
|
from flask import current_app
|
|
|
|
from app import db
|
|
from app.models import ScheduleRun, ScheduleTask, User
|
|
from app.services.schedule import normalize_platform_api_path, resolve_schedule_executor, resolve_schedule_header
|
|
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
|
|
from app.services.schedule.excel_service import export_schedule_result_excel
|
|
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
|
|
from app.services.schedule.cron_util import normalize_cron_expr
|
|
from app.services.schedule.timezone_util import compute_next_run_at, normalize_schedule_timezone, utc_now_naive
|
|
|
|
_worker_started = False
|
|
_worker_lock = threading.Lock()
|
|
_cancelled_runs: set[int] = set()
|
|
_cancel_lock = threading.Lock()
|
|
|
|
|
|
def request_cancel_run(run_id: int) -> None:
|
|
with _cancel_lock:
|
|
_cancelled_runs.add(run_id)
|
|
|
|
|
|
def is_run_cancelled(run_id: int) -> bool:
|
|
with _cancel_lock:
|
|
return run_id in _cancelled_runs
|
|
|
|
|
|
def clear_cancelled_run(run_id: int) -> None:
|
|
with _cancel_lock:
|
|
_cancelled_runs.discard(run_id)
|
|
|
|
|
|
def _generate_schedule_no() -> str:
|
|
return f"SCH{datetime.utcnow().strftime('%Y%m%d%H%M%S')}{uuid.uuid4().hex[:4].upper()}"
|
|
|
|
|
|
def _generate_run_no() -> str:
|
|
return f"RUN{datetime.utcnow().strftime('%Y%m%d%H%M%S')}{uuid.uuid4().hex[:4].upper()}"
|
|
|
|
|
|
def _generate_test_run_no() -> str:
|
|
return f"TESTRUN{datetime.utcnow().strftime('%Y%m%d%H%M%S')}{uuid.uuid4().hex[:4].upper()}"
|
|
|
|
|
|
_WECOM_STATUS_LABEL = {
|
|
'success': '成功',
|
|
'failed': '失败',
|
|
'partial_failed': '部分失败',
|
|
}
|
|
|
|
_WECOM_EVENT_TYPE = 'schedule_completed'
|
|
|
|
|
|
def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
|
|
from app.services.wecom_notify import (
|
|
upload_wecom_temp_media,
|
|
send_wecom_file_message,
|
|
send_wecom_textcard_message,
|
|
_create_audit,
|
|
_build_jump_url,
|
|
_get_enabled_events,
|
|
)
|
|
|
|
if not current_app.config.get('WECOM_NOTIFY_ENABLED', True):
|
|
run.wecom_notify_error = 'WECOM_NOTIFY_ENABLED=false'
|
|
return
|
|
|
|
if _WECOM_EVENT_TYPE not in _get_enabled_events():
|
|
run.wecom_notify_error = f'event {_WECOM_EVENT_TYPE} disabled'
|
|
return
|
|
|
|
user_ids = task.notify_user_ids_json or []
|
|
if not user_ids:
|
|
return
|
|
|
|
users = db.session.query(User).filter(User.id.in_(user_ids)).all()
|
|
wecom_users = [u for u in users if u.wecom_userid]
|
|
if not wecom_users:
|
|
run.wecom_notify_error = 'no wecom_userid bound users in notify list'
|
|
return
|
|
|
|
status_label = _WECOM_STATUS_LABEL.get(run.status, run.status)
|
|
title = f'排程执行结果: {task.name}'
|
|
description = (
|
|
f'执行单号: {run.run_no}\n'
|
|
f'状态: {status_label}\n'
|
|
f'总数: {run.total_count} 成功: {run.success_count} 失败: {run.failed_count}'
|
|
)
|
|
|
|
media_id = None
|
|
if run.excel_file_data and run.excel_file_name:
|
|
try:
|
|
media_id = upload_wecom_temp_media(run.excel_file_data, run.excel_file_name)
|
|
except Exception as exc:
|
|
current_app.logger.warning(
|
|
'[wecom-schedule] media upload failed for run %s: %s',
|
|
run.run_no, exc,
|
|
)
|
|
|
|
textcard_ok_count = 0
|
|
errors = []
|
|
|
|
for u in wecom_users:
|
|
trace_id = uuid.uuid4().hex
|
|
jump_url = _build_jump_url('/workspace', trace_id, {'tab': 'schedule-runs'})
|
|
|
|
try:
|
|
audit = _create_audit(_WECOM_EVENT_TYPE, u, title, description, trace_id)
|
|
audit.jump_url = jump_url
|
|
|
|
data = send_wecom_textcard_message(u.wecom_userid, title, description, jump_url)
|
|
if data.get('errcode') == 0:
|
|
audit.status = 'sent'
|
|
textcard_ok_count += 1
|
|
else:
|
|
audit.error_code = str(data.get('errcode'))
|
|
audit.error_message = str(data.get('errmsg', 'unknown'))[:255]
|
|
errors.append(f'{u.real_name or u.username}: textcard errcode={data.get("errcode")}')
|
|
except Exception as exc:
|
|
errors.append(f'{u.real_name or u.username}: textcard exception={exc}')
|
|
|
|
if media_id:
|
|
try:
|
|
file_audit = _create_audit(
|
|
f'{_WECOM_EVENT_TYPE}_file', u,
|
|
title, f'[文件] {run.excel_file_name}', uuid.uuid4().hex,
|
|
)
|
|
file_data = send_wecom_file_message(u.wecom_userid, media_id)
|
|
if file_data.get('errcode') == 0:
|
|
file_audit.status = 'sent'
|
|
else:
|
|
file_audit.error_code = str(file_data.get('errcode'))
|
|
file_audit.error_message = str(file_data.get('errmsg', 'unknown'))[:255]
|
|
errors.append(f'{u.real_name or u.username}: file errcode={file_data.get("errcode")}')
|
|
except Exception as exc:
|
|
errors.append(f'{u.real_name or u.username}: file exception={exc}')
|
|
|
|
if textcard_ok_count > 0:
|
|
run.wecom_notified = True
|
|
run.wecom_notified_at = datetime.utcnow()
|
|
else:
|
|
run.wecom_notified = False
|
|
|
|
if errors:
|
|
run.wecom_notify_error = '; '.join(errors[:5])
|
|
|
|
db.session.flush()
|
|
|
|
|
|
def create_task(
|
|
*,
|
|
name: str,
|
|
schedule_type: str,
|
|
owner_user_id: int,
|
|
cron_expr: str,
|
|
schedule_timezone: str | None = None,
|
|
wait_seconds: int,
|
|
dify_agent_id: int | None,
|
|
platform_api_path: str | None,
|
|
notify_user_ids_json: list[int] | None,
|
|
notify_enabled: bool,
|
|
enabled: bool,
|
|
actor_id: int | None,
|
|
) -> ScheduleTask:
|
|
cron_expr = normalize_cron_expr(cron_expr)
|
|
task = ScheduleTask(
|
|
schedule_no=_generate_schedule_no(),
|
|
name=name,
|
|
schedule_type="platform_app",
|
|
owner_user_id=owner_user_id,
|
|
cron_expr=cron_expr,
|
|
schedule_timezone=normalize_schedule_timezone(schedule_timezone),
|
|
wait_seconds=max(0, int(wait_seconds or 0)),
|
|
dify_agent_id=dify_agent_id,
|
|
platform_api_path=normalize_platform_api_path(platform_api_path) or None,
|
|
notify_user_ids_json=notify_user_ids_json or [],
|
|
notify_enabled=bool(notify_enabled),
|
|
enabled=bool(enabled),
|
|
created_by=actor_id,
|
|
updated_by=actor_id,
|
|
)
|
|
if task.enabled and task.cron_expr:
|
|
task.next_run_at = compute_next_run_at(task.cron_expr, timezone_name=task.schedule_timezone)
|
|
if task.next_run_at is None:
|
|
task.enabled = False
|
|
db.session.add(task)
|
|
db.session.commit()
|
|
return task
|
|
|
|
|
|
def update_task(task: ScheduleTask, *, payload: dict[str, Any], actor_id: int | None) -> ScheduleTask:
|
|
for key in [
|
|
"name",
|
|
"owner_user_id",
|
|
"cron_expr",
|
|
"schedule_timezone",
|
|
"wait_seconds",
|
|
"dify_agent_id",
|
|
"notify_enabled",
|
|
"enabled",
|
|
]:
|
|
if key in payload:
|
|
if key == "schedule_timezone":
|
|
value = normalize_schedule_timezone(payload[key])
|
|
elif key == "cron_expr":
|
|
value = normalize_cron_expr(str(payload[key] or ""))
|
|
else:
|
|
value = payload[key]
|
|
setattr(task, key, value)
|
|
if "platform_api_path" in payload:
|
|
task.platform_api_path = normalize_platform_api_path(payload.get("platform_api_path")) or None
|
|
if "notify_user_ids_json" in payload and isinstance(payload.get("notify_user_ids_json"), list):
|
|
task.notify_user_ids_json = payload.get("notify_user_ids_json")
|
|
if "kb_sync_enabled" in payload:
|
|
task.kb_sync_enabled = bool(payload.get("kb_sync_enabled"))
|
|
if "kb_group_id" in payload:
|
|
raw_group_id = payload.get("kb_group_id")
|
|
task.kb_group_id = int(raw_group_id) if raw_group_id not in (None, "", 0, "0") else None
|
|
|
|
if not normalize_platform_api_path(task.platform_api_path):
|
|
dst = str(getattr(task, "data_source_type", None) or "database")
|
|
if dst != "faq_hot_aggregate":
|
|
raise ValueError("platform_api_path is required for platform_app")
|
|
task.platform_api_path = "faq-aggregate-hot"
|
|
task.schedule_type = "platform_app"
|
|
|
|
if task.enabled and task.cron_expr:
|
|
task.schedule_timezone = normalize_schedule_timezone(getattr(task, "schedule_timezone", None))
|
|
task.next_run_at = compute_next_run_at(task.cron_expr, timezone_name=task.schedule_timezone)
|
|
else:
|
|
task.next_run_at = None
|
|
|
|
task.updated_by = actor_id
|
|
db.session.commit()
|
|
return task
|
|
|
|
|
|
def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id: int | None, run: ScheduleRun | None = None) -> ScheduleRun:
|
|
if run is None:
|
|
existing = db.session.query(ScheduleRun).filter(
|
|
ScheduleRun.schedule_task_id == task.id,
|
|
ScheduleRun.status == "running",
|
|
).first()
|
|
if existing:
|
|
return existing
|
|
run = ScheduleRun(
|
|
run_no=_generate_run_no(),
|
|
schedule_task_id=task.id,
|
|
trigger_type=trigger_type,
|
|
triggered_by_user_id=triggered_by_user_id,
|
|
started_at=datetime.utcnow(),
|
|
status="running",
|
|
)
|
|
db.session.add(run)
|
|
db.session.commit()
|
|
|
|
capture_dify_execution_snapshot(run, task)
|
|
db.session.commit()
|
|
|
|
if task.cron_expr and trigger_type == "cron":
|
|
task.next_run_at = compute_next_run_at(task.cron_expr, timezone_name=getattr(task, "schedule_timezone", None))
|
|
db.session.commit()
|
|
|
|
start_ts = time.time()
|
|
step_logs: list = []
|
|
try:
|
|
executor = resolve_schedule_executor(task)
|
|
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = executor(task, run)
|
|
except Exception as exc:
|
|
total_count, success_count, failed_count, skipped_count, details, errors = 0, 0, 0, 0, [], [str(exc)]
|
|
step_logs = [{"step": "executor_error", "status": "failed", "detail": {"error": str(exc)}}]
|
|
|
|
try:
|
|
db.session.refresh(run)
|
|
except Exception:
|
|
pass
|
|
|
|
if is_run_cancelled(run.id):
|
|
run.finished_at = datetime.utcnow()
|
|
run.duration_ms = int((time.time() - start_ts) * 1000)
|
|
run.status = "failed"
|
|
run.error_message = "排程已被删除,执行中断"
|
|
db.session.commit()
|
|
clear_cancelled_run(run.id)
|
|
return run
|
|
|
|
duration_ms = int((time.time() - start_ts) * 1000)
|
|
if current_app:
|
|
current_app.logger.info(
|
|
"[schedule-run] run_no=%s total=%d success=%d failed=%d skipped=%d errors=%d",
|
|
run.run_no, total_count, success_count, failed_count, skipped_count, len(errors),
|
|
)
|
|
if total_count == 0 and not errors:
|
|
status = "success"
|
|
run.error_message = "无待处理数据"
|
|
elif failed_count == 0:
|
|
status = "success"
|
|
elif success_count == 0:
|
|
status = "failed"
|
|
else:
|
|
status = "partial_failed"
|
|
|
|
try:
|
|
cfg = get_schedule_sql_config_by_task_id(task.id)
|
|
if cfg and cfg.alias_order and cfg.header_labels:
|
|
header_order, header_labels = cfg.alias_order, cfg.header_labels
|
|
else:
|
|
header_order, header_labels = resolve_schedule_header(task.platform_api_path)
|
|
detail_alias_order = (cfg.detail_alias_order if cfg else None) or []
|
|
file_data, file_name, file_size = export_schedule_result_excel(
|
|
run_no=run.run_no,
|
|
summary={
|
|
"status": status,
|
|
"total_count": total_count,
|
|
"success_count": success_count,
|
|
"failed_count": failed_count,
|
|
"duration_ms": duration_ms,
|
|
},
|
|
details=details,
|
|
header_order=header_order,
|
|
header_labels=header_labels,
|
|
detail_alias_order=detail_alias_order,
|
|
)
|
|
except Exception as excel_exc:
|
|
if current_app:
|
|
current_app.logger.error("[schedule-run] excel export failed: %s", excel_exc)
|
|
file_data, file_name, file_size = None, None, 0
|
|
errors.append(f"Excel导出失败: {excel_exc}")
|
|
|
|
run.finished_at = datetime.utcnow()
|
|
run.duration_ms = duration_ms
|
|
run.status = status
|
|
run.total_count = total_count
|
|
run.success_count = success_count
|
|
run.failed_count = failed_count
|
|
run.skipped_count = skipped_count
|
|
run.step_logs = step_logs if step_logs else None
|
|
response_summary = dict(run.response_summary_json or {})
|
|
response_summary.update({
|
|
"errors": errors[:20],
|
|
"schedule_type": task.schedule_type,
|
|
"platform_api_path": task.platform_api_path,
|
|
})
|
|
run.response_summary_json = response_summary
|
|
run.error_message = "; ".join(errors[:3]) if errors else None
|
|
run.excel_file_data = file_data
|
|
run.excel_file_name = file_name
|
|
run.excel_file_size = file_size or 0
|
|
task.last_run_at = datetime.utcnow()
|
|
db.session.commit()
|
|
|
|
try:
|
|
from app.services.schedule.kb_sync import sync_schedule_run_excel_to_kb
|
|
|
|
db.session.refresh(task)
|
|
db.session.refresh(run)
|
|
sync_schedule_run_excel_to_kb(task, run, process_inline=True)
|
|
db.session.refresh(run)
|
|
except Exception as kb_exc:
|
|
db.session.rollback()
|
|
db.session.refresh(run)
|
|
if current_app:
|
|
current_app.logger.error("[schedule-run] kb sync failed: %s", kb_exc, exc_info=True)
|
|
run.kb_sync_status = "failed"
|
|
run.kb_group_id = getattr(task, "kb_group_id", None)
|
|
run.kb_sync_error = str(kb_exc)
|
|
db.session.commit()
|
|
|
|
try:
|
|
if task.notify_enabled:
|
|
_notify_schedule_run_wecom(task, run)
|
|
except Exception as wecom_exc:
|
|
if current_app:
|
|
current_app.logger.error("[schedule-run] wecom notify failed: %s", wecom_exc)
|
|
|
|
return run
|
|
|
|
|
|
def start_scheduler(app):
|
|
global _worker_started
|
|
with _worker_lock:
|
|
if _worker_started:
|
|
return
|
|
_worker_started = True
|
|
|
|
if not bool(app.config.get("SCHEDULE_WORKER_ENABLED", True)):
|
|
return
|
|
|
|
import os
|
|
if os.environ.get('WERKZEUG_RUN_MAIN') == 'true' or not app.debug:
|
|
pass
|
|
else:
|
|
_worker_started = False
|
|
return
|
|
|
|
def _loop():
|
|
with app.app_context():
|
|
stale = db.session.query(ScheduleTask).filter(
|
|
ScheduleTask.enabled.is_(True),
|
|
ScheduleTask.next_run_at.isnot(None),
|
|
ScheduleTask.next_run_at <= utc_now_naive(),
|
|
).all()
|
|
for t in stale:
|
|
if t.cron_expr:
|
|
t.next_run_at = compute_next_run_at(t.cron_expr, timezone_name=getattr(t, "schedule_timezone", None))
|
|
if t.next_run_at is None:
|
|
t.enabled = False
|
|
else:
|
|
t.next_run_at = None
|
|
if stale:
|
|
db.session.commit()
|
|
current_app.logger.info("[schedule-worker] reset %d stale next_run_at on startup", len(stale))
|
|
|
|
stuck = db.session.query(ScheduleRun).filter(
|
|
ScheduleRun.status == "running",
|
|
).all()
|
|
for r in stuck:
|
|
r.status = "failed"
|
|
r.error_message = "服务重启,执行中断"
|
|
r.finished_at = datetime.utcnow()
|
|
if stuck:
|
|
db.session.commit()
|
|
current_app.logger.info("[schedule-worker] cleaned %d stuck running runs on startup", len(stuck))
|
|
|
|
while True:
|
|
try:
|
|
now = utc_now_naive()
|
|
due_tasks = db.session.query(ScheduleTask).filter(
|
|
ScheduleTask.enabled.is_(True),
|
|
ScheduleTask.next_run_at.isnot(None),
|
|
ScheduleTask.next_run_at <= now,
|
|
).limit(5).with_for_update(skip_locked=True).all()
|
|
for task in due_tasks:
|
|
has_running = db.session.query(ScheduleRun).filter(
|
|
ScheduleRun.schedule_task_id == task.id,
|
|
ScheduleRun.status == "running",
|
|
).first()
|
|
if has_running:
|
|
if task.cron_expr:
|
|
task.next_run_at = compute_next_run_at(task.cron_expr, timezone_name=getattr(task, "schedule_timezone", None))
|
|
db.session.commit()
|
|
continue
|
|
try:
|
|
run_task_now(task, trigger_type="cron", triggered_by_user_id=None)
|
|
except Exception as e:
|
|
current_app.logger.error("[schedule-worker] task_id=%s run failed: %s", task.id, e, exc_info=True)
|
|
db.session.rollback()
|
|
|
|
if task.cron_expr:
|
|
task.next_run_at = compute_next_run_at(task.cron_expr, timezone_name=getattr(task, "schedule_timezone", None))
|
|
if task.next_run_at is None:
|
|
task.enabled = False
|
|
else:
|
|
task.next_run_at = None
|
|
|
|
db.session.commit()
|
|
except Exception:
|
|
db.session.rollback()
|
|
time.sleep(30)
|
|
|
|
t = threading.Thread(target=_loop, daemon=True, name="schedule-worker")
|
|
t.start()
|