356 lines
13 KiB
Python
356 lines
13 KiB
Python
from __future__ import annotations
|
|
|
|
import threading
|
|
import time
|
|
import uuid
|
|
from datetime import datetime
|
|
from typing import Any
|
|
|
|
from croniter import croniter
|
|
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.excel_service import export_schedule_result_excel
|
|
from app.services.schedule.mail_service import build_schedule_mail_html, send_schedule_mail
|
|
|
|
_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 create_task(
|
|
*,
|
|
name: str,
|
|
schedule_type: str,
|
|
owner_user_id: int,
|
|
cron_expr: str,
|
|
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:
|
|
if not normalize_platform_api_path(platform_api_path):
|
|
raise ValueError("platform_api_path is required for platform_app")
|
|
|
|
task = ScheduleTask(
|
|
schedule_no=_generate_schedule_no(),
|
|
name=name,
|
|
schedule_type="platform_app",
|
|
owner_user_id=owner_user_id,
|
|
cron_expr=cron_expr,
|
|
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:
|
|
try:
|
|
iter = croniter(task.cron_expr, datetime.utcnow())
|
|
task.next_run_at = iter.get_next(datetime)
|
|
except Exception:
|
|
task.next_run_at = 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",
|
|
"wait_seconds",
|
|
"dify_agent_id",
|
|
"notify_enabled",
|
|
"enabled",
|
|
]:
|
|
if key in payload:
|
|
setattr(task, key, payload[key])
|
|
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 not normalize_platform_api_path(task.platform_api_path):
|
|
raise ValueError("platform_api_path is required for platform_app")
|
|
task.schedule_type = "platform_app"
|
|
|
|
if task.enabled and task.cron_expr:
|
|
try:
|
|
iter = croniter(task.cron_expr, datetime.utcnow())
|
|
task.next_run_at = iter.get_next(datetime)
|
|
except Exception:
|
|
task.next_run_at = None
|
|
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()
|
|
|
|
if task.cron_expr and trigger_type == "cron":
|
|
try:
|
|
iter = croniter(task.cron_expr, datetime.utcnow())
|
|
task.next_run_at = iter.get_next(datetime)
|
|
except Exception:
|
|
task.next_run_at = None
|
|
db.session.commit()
|
|
|
|
start_ts = time.time()
|
|
try:
|
|
executor = resolve_schedule_executor(task)
|
|
total_count, success_count, failed_count, skipped_count, details, errors = executor(task, run)
|
|
except Exception as exc:
|
|
total_count, success_count, failed_count, skipped_count, details, errors = 0, 0, 0, 0, [], [str(exc)]
|
|
|
|
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:
|
|
header_order, header_labels = resolve_schedule_header(task.platform_api_path)
|
|
file_path, 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,
|
|
root_dir=str(current_app.config.get("SCHEDULE_EXCEL_STORAGE_ROOT") or "").strip(),
|
|
header_order=header_order,
|
|
header_labels=header_labels,
|
|
)
|
|
except Exception as excel_exc:
|
|
if current_app:
|
|
current_app.logger.error("[schedule-run] excel export failed: %s", excel_exc)
|
|
file_path, 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.response_summary_json = {
|
|
"errors": errors[:20],
|
|
"schedule_type": task.schedule_type,
|
|
"platform_api_path": task.platform_api_path,
|
|
}
|
|
run.error_message = "; ".join(errors[:3]) if errors else None
|
|
run.excel_file_path = file_path
|
|
run.excel_file_name = file_name
|
|
run.excel_file_size = file_size or 0
|
|
|
|
try:
|
|
if task.notify_enabled:
|
|
users = db.session.query(User).filter(User.id.in_(task.notify_user_ids_json or [])).all()
|
|
to_addrs = [u.email for u in users if u.email]
|
|
if to_addrs:
|
|
try:
|
|
send_schedule_mail(
|
|
smtp_host=str(current_app.config.get("SMTP_HOST") or ""),
|
|
smtp_port=int(current_app.config.get("SMTP_PORT") or 25),
|
|
smtp_user=str(current_app.config.get("SMTP_USER") or ""),
|
|
smtp_password=str(current_app.config.get("SMTP_PASSWORD") or ""),
|
|
use_tls=bool(current_app.config.get("SMTP_USE_TLS", True)),
|
|
from_addr=str(current_app.config.get("SMTP_FROM") or current_app.config.get("SMTP_USER") or "noreply@example.com"),
|
|
to_addrs=to_addrs,
|
|
subject=f"排程执行结果 {task.name} {run.run_no}",
|
|
html_body=build_schedule_mail_html(
|
|
schedule_name=task.name,
|
|
run_no=run.run_no,
|
|
status=status,
|
|
total=total_count,
|
|
success=success_count,
|
|
failed=failed_count,
|
|
),
|
|
)
|
|
run.mail_sent = True
|
|
run.mail_sent_at = datetime.utcnow()
|
|
except Exception as mail_exc:
|
|
run.mail_sent = False
|
|
run.mail_error = str(mail_exc)
|
|
except Exception as mail_exc:
|
|
if current_app:
|
|
current_app.logger.error("[schedule-run] mail send failed: %s", mail_exc)
|
|
|
|
task.last_run_at = datetime.utcnow()
|
|
db.session.commit()
|
|
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 <= datetime.utcnow(),
|
|
).all()
|
|
for t in stale:
|
|
if t.cron_expr:
|
|
try:
|
|
it = croniter(t.cron_expr, datetime.utcnow())
|
|
t.next_run_at = it.get_next(datetime)
|
|
except Exception:
|
|
t.next_run_at = 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 = datetime.utcnow()
|
|
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:
|
|
try:
|
|
iter = croniter(task.cron_expr, datetime.utcnow())
|
|
task.next_run_at = iter.get_next(datetime)
|
|
except Exception:
|
|
task.next_run_at = 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:
|
|
try:
|
|
iter = croniter(task.cron_expr, datetime.utcnow())
|
|
task.next_run_at = iter.get_next(datetime)
|
|
except Exception:
|
|
task.next_run_at = 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()
|