507 lines
27 KiB
Python
507 lines
27 KiB
Python
from __future__ import annotations
|
|
import threading
|
|
from datetime import datetime
|
|
from flask import Blueprint, current_app, jsonify, request, send_file
|
|
from flask import Response
|
|
from io import BytesIO
|
|
import json
|
|
from app.decorators import require_admin
|
|
from app import db
|
|
from app.models import ScheduleRun, ScheduleTask, ScheduleTaskConfig
|
|
from app.auth_jwt import get_current_user
|
|
from app.services.schedule.query_service import get_run, list_runs, list_tasks, serialize_run, serialize_task
|
|
from app.services.schedule.scheduler_service import create_task, run_task_now, update_task, _generate_run_no, _generate_test_run_no, _notify_schedule_run_wecom
|
|
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id, upsert_schedule_task_config, _build_fetch_sql
|
|
from app.services.schedule.srm_service import _fetch_records
|
|
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
|
schedule_admin_bp = Blueprint('schedule_admin', __name__)
|
|
|
|
def _serialize_task_for_export(task: ScheduleTask, cfg_model: ScheduleTaskConfig | None) -> dict:
|
|
payload = serialize_task(task)
|
|
payload['config'] = _serialize_task_config(cfg_model) if cfg_model else None
|
|
return payload
|
|
|
|
def _serialize_task_config(cfg_model: ScheduleTaskConfig) -> dict:
|
|
return {'row_id_key': cfg_model.row_id_key or 'id', 'log_prefix': cfg_model.log_prefix or '', 'base_fetch_sql': cfg_model.base_fetch_sql or '', 'fetch_where_conditions': cfg_model.fetch_where_conditions or '', 'fetch_order_by': cfg_model.fetch_order_by or '', 'writeback_sql': cfg_model.writeback_sql or '', 'detail_sql': cfg_model.detail_sql or '', 'alias_order': cfg_model.alias_order or [], 'detail_alias_order': cfg_model.detail_alias_order or [], 'header_labels': cfg_model.header_labels or {}, 'data_source': {'db_type': cfg_model.ds_db_type or 'sqlserver', 'host': cfg_model.ds_host or '', 'port': cfg_model.ds_port or '', 'database': cfg_model.ds_database or '', 'username': cfg_model.ds_username or '', 'password': cfg_model.ds_password or '', 'driver': cfg_model.ds_driver or '', 'encrypt': cfg_model.ds_encrypt or '', 'trust_cert': cfg_model.ds_trust_cert or ''}, 'external_api': {'url': cfg_model.api_url or '', 'method': cfg_model.api_method or 'POST', 'headers': cfg_model.api_headers or {}, 'body_template': cfg_model.api_body_template or ''}, 'dify_system_prompt': cfg_model.dify_system_prompt or ''}
|
|
|
|
@schedule_admin_bp.route('/schedule-config/<int:task_id>', methods=['GET'])
|
|
@require_admin
|
|
def get_schedule_task_config(task_id: int):
|
|
task = db.session.get(ScheduleTask, task_id)
|
|
if not task:
|
|
raise NotFoundError('Not found')
|
|
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
|
if not cfg_model:
|
|
return jsonify({'data_source_type': task.data_source_type, 'config': None})
|
|
return jsonify({'data_source_type': task.data_source_type, 'config': _serialize_task_config(cfg_model)})
|
|
|
|
@schedule_admin_bp.route('/schedule-config/<int:task_id>', methods=['PUT'])
|
|
@require_admin
|
|
def update_schedule_task_config(task_id: int):
|
|
task = db.session.get(ScheduleTask, task_id)
|
|
if not task:
|
|
raise NotFoundError('Not found')
|
|
data = request.get_json(silent=True) or {}
|
|
try:
|
|
if 'data_source_type' in data:
|
|
task.data_source_type = str(data['data_source_type'])
|
|
db.session.commit()
|
|
config_data = data.get('config', data)
|
|
cfg = upsert_schedule_task_config(task_id, config_data)
|
|
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
|
return jsonify({'data_source_type': task.data_source_type, 'config': _serialize_task_config(cfg_model) if cfg_model else None})
|
|
except Exception as e:
|
|
db.session.rollback()
|
|
raise ValidationError(str(e))
|
|
|
|
@schedule_admin_bp.route('/schedule-config/<int:task_id>/test-sql', methods=['POST'])
|
|
@require_admin
|
|
def test_schedule_sql(task_id: int):
|
|
cfg = get_schedule_sql_config_by_task_id(task_id)
|
|
if not cfg:
|
|
raise NotFoundError(f'Config for task {task_id} not found')
|
|
data = request.get_json(silent=True) or {}
|
|
custom_where = str(data.get('fetch_where_conditions') or cfg.fetch_where_conditions).strip()
|
|
custom_order_by = str(data.get('fetch_order_by') or cfg.fetch_order_by).strip()
|
|
limit = min(int(data.get('limit') or 10), 100)
|
|
base = cfg.base_fetch_sql or cfg.fetch_sql
|
|
if cfg.base_fetch_sql:
|
|
sql = _build_fetch_sql(base, custom_where, custom_order_by)
|
|
else:
|
|
sql = base
|
|
try:
|
|
from app.services.schedule import _build_srm_conn_str
|
|
import decimal, datetime
|
|
if cfg.data_source and (not cfg.data_source.is_empty()):
|
|
conn_str = cfg.data_source.build_connection_string()
|
|
else:
|
|
conn_str = _build_srm_conn_str()
|
|
rows = _fetch_records(conn_str, sql)
|
|
|
|
def _safe(v):
|
|
if isinstance(v, decimal.Decimal):
|
|
return float(v)
|
|
if isinstance(v, (datetime.date, datetime.datetime)):
|
|
return v.isoformat()
|
|
if isinstance(v, datetime.timedelta):
|
|
return str(v)
|
|
return v
|
|
result_rows = [{k: _safe(v) for k, v in r.items()} for r in rows[:limit]]
|
|
return jsonify({'total': len(rows), 'showing': len(result_rows), 'limit': limit, 'sql': sql, 'columns': list(result_rows[0].keys()) if result_rows else [], 'rows': result_rows})
|
|
except Exception as e:
|
|
raise AppError(code='SYSTEM.HTTP_ERROR', message=str(e), http_status=400, details={'sql': sql})
|
|
|
|
@schedule_admin_bp.route('/schedule-config/<int:task_id>/test-run', methods=['POST'])
|
|
@require_admin
|
|
def test_schedule_run(task_id: int):
|
|
import time as _time
|
|
from app.services.schedule.excel_service import export_schedule_result_excel
|
|
task = db.session.get(ScheduleTask, task_id)
|
|
if not task:
|
|
raise NotFoundError('Not found')
|
|
cfg = get_schedule_sql_config_by_task_id(task_id)
|
|
if not cfg:
|
|
raise NotFoundError(f'Config for task {task_id} not found')
|
|
data = request.get_json(silent=True) or {}
|
|
custom_where = str(data.get('fetch_where_conditions') or cfg.fetch_where_conditions).strip()
|
|
custom_order_by = str(data.get('fetch_order_by') or cfg.fetch_order_by).strip()
|
|
limit = min(int(data.get('limit') or 3), 10)
|
|
raw_kb_sync = data.get('kb_sync_enabled', False)
|
|
if isinstance(raw_kb_sync, str):
|
|
test_kb_sync_enabled = raw_kb_sync.strip().lower() in ('1', 'true', 'yes', 'on')
|
|
else:
|
|
test_kb_sync_enabled = bool(raw_kb_sync)
|
|
base = cfg.base_fetch_sql or cfg.fetch_sql
|
|
if cfg.base_fetch_sql:
|
|
test_sql = _build_fetch_sql(base, custom_where, custom_order_by)
|
|
else:
|
|
test_sql = base
|
|
from app.services.schedule import _build_srm_conn_str, _resolve_dify_agent, _resolve_schedule_user
|
|
from app.services.schedule.srm_service import _fetch_records, _run_check_job_loop, _build_record_text, _execute_writeback
|
|
if cfg.data_source and (not cfg.data_source.is_empty()):
|
|
conn_str = cfg.data_source.build_connection_string()
|
|
else:
|
|
conn_str = _build_srm_conn_str()
|
|
agent = _resolve_dify_agent(task) if task else None
|
|
user = _resolve_schedule_user(task) if task else 'test_user'
|
|
wait_seconds = task.wait_seconds if task else 120
|
|
dify_agent_id = task.dify_agent_id if task else None
|
|
run = ScheduleRun(run_no=_generate_test_run_no(), schedule_task_id=task_id, trigger_type='test', triggered_by_user_id=getattr(get_current_user(), 'id', None), started_at=datetime.utcnow(), status='running')
|
|
db.session.add(run)
|
|
db.session.commit()
|
|
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
|
|
capture_dify_execution_snapshot(run, task)
|
|
db.session.commit()
|
|
if not cfg.fetch_sql:
|
|
run.status = 'success'
|
|
run.finished_at = datetime.utcnow()
|
|
run.error_message = '无抓取SQL,跳过外部系统数据抓取'
|
|
try:
|
|
if task.notify_enabled:
|
|
_notify_schedule_run_wecom(task, run)
|
|
except Exception as wecom_exc:
|
|
current_app.logger.error('[schedule-test-run] wecom notify failed: %s', wecom_exc)
|
|
db.session.commit()
|
|
return jsonify({'run_no': run.run_no, 'run_id': run.id, 'sql': '', 'limit': 0, 'total_count': 0, 'success_count': 0, 'failed_count': 0, 'skipped_count': 0, 'details': [], 'errors': [], 'step_logs': [{'step': 'no_fetch_sql', 'status': 'skipped', 'detail': '无抓取SQL,跳过外部系统数据抓取'}], 'dify_agent_id': dify_agent_id})
|
|
|
|
def _test_fetch_fn(conn_str_arg):
|
|
return _fetch_records(conn_str_arg, test_sql)
|
|
|
|
def _test_writeback_fn(conn_str_arg, *, row_id, run_no, dify_result, dify_message):
|
|
_execute_writeback(conn_str_arg, cfg.writeback_sql, (run_no, dify_result, dify_message, str(row_id)))
|
|
test_pre_dify = None
|
|
test_build_record = None
|
|
if cfg.detail_sql:
|
|
|
|
def _test_pre_dify(conn_str_arg, item, row_id_value):
|
|
try:
|
|
detail_rows = _fetch_records(conn_str_arg, cfg.detail_sql, params=(str(row_id_value),))
|
|
except Exception as detail_exc:
|
|
return {'dify_result': '人工判定', 'dify_message': f'查询成分明细失败:{detail_exc}', 'writeback_srm': False, 'writeback_err': str(detail_exc)}
|
|
detail_lines = []
|
|
for dr in detail_rows:
|
|
parts = [f"{cfg.header_labels.get(dk, dk)}: {dr.get(dk, '')}" for dk in cfg.detail_alias_order]
|
|
detail_lines.append(', '.join(parts))
|
|
item['detail_text'] = '; '.join(detail_lines) if detail_lines else ''
|
|
item['_detail_rows'] = detail_rows
|
|
return None
|
|
test_pre_dify = _test_pre_dify
|
|
|
|
def _test_build_with_detail(conn_str_arg, item, row_id_value):
|
|
detail_rows = item.get('_detail_rows', [])
|
|
text = _build_record_text(item, cfg.alias_order, cfg.header_labels, detail_rows, cfg.detail_alias_order)
|
|
return (text, item.get('attachment'))
|
|
test_build_record = _test_build_with_detail
|
|
else:
|
|
|
|
def _test_build_simple(conn_str_arg, item, row_id_value):
|
|
text = _build_record_text(item, cfg.alias_order, cfg.header_labels)
|
|
return (text, item.get('attachment'))
|
|
test_build_record = _test_build_simple
|
|
start_ts = _time.time()
|
|
try:
|
|
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = _run_check_job_loop(conn_str=conn_str, run_no=run.run_no, agent=agent, user=user, wait_seconds=wait_seconds, run_id=run.id, fetch_fn=_test_fetch_fn, build_record_fn=test_build_record, writeback_fn=_test_writeback_fn, writeback_sql=cfg.writeback_sql, row_id_key=cfg.row_id_key, log_prefix=cfg.log_prefix, fetch_sql=test_sql, max_rows=limit, pre_dify_fn=test_pre_dify, dify_system_prompt=cfg.dify_system_prompt)
|
|
duration_ms = int((_time.time() - start_ts) * 1000)
|
|
if total_count == 0 and (not errors):
|
|
status = 'success'
|
|
elif failed_count == 0:
|
|
status = 'success'
|
|
elif success_count == 0:
|
|
status = 'failed'
|
|
else:
|
|
status = 'partial_failed'
|
|
header_order = cfg.alias_order if cfg.alias_order else None
|
|
header_labels = cfg.header_labels if cfg.header_labels else None
|
|
detail_alias_order = cfg.detail_alias_order or []
|
|
try:
|
|
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:
|
|
current_app.logger.error('[schedule-test-run] excel export failed: %s', excel_exc, exc_info=True)
|
|
file_data, file_name, file_size = (None, None, 0)
|
|
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
|
|
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
|
|
db.session.commit()
|
|
if test_kb_sync_enabled:
|
|
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, enabled=True, process_inline=True)
|
|
db.session.refresh(run)
|
|
except Exception as kb_exc:
|
|
db.session.rollback()
|
|
db.session.refresh(run)
|
|
current_app.logger.error('[schedule-test-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:
|
|
current_app.logger.error('[schedule-test-run] wecom notify failed: %s', wecom_exc)
|
|
import decimal, datetime as dt
|
|
|
|
def _safe(v):
|
|
if isinstance(v, decimal.Decimal):
|
|
return float(v)
|
|
if isinstance(v, (dt.date, dt.datetime)):
|
|
return v.isoformat()
|
|
if isinstance(v, dt.timedelta):
|
|
return str(v)
|
|
return v
|
|
safe_details = []
|
|
for item in details:
|
|
safe_item = {k: _safe(v) for k, v in item.items()}
|
|
safe_details.append(safe_item)
|
|
return jsonify({'run_no': run.run_no, 'run_id': run.id, 'sql': test_sql, 'limit': limit, 'total_count': total_count, 'success_count': success_count, 'failed_count': failed_count, 'skipped_count': skipped_count, 'details': safe_details, 'errors': errors, 'step_logs': step_logs, 'dify_agent_id': dify_agent_id, 'dify_execution_snapshot': run.dify_execution_snapshot, 'kb_sync_status': run.kb_sync_status, 'kb_sync_error': run.kb_sync_error, 'kb_document_id': run.kb_document_id})
|
|
except Exception as e:
|
|
db.session.rollback()
|
|
run = db.session.get(ScheduleRun, run.id)
|
|
duration_ms = int((_time.time() - start_ts) * 1000)
|
|
run.finished_at = datetime.utcnow()
|
|
run.duration_ms = duration_ms
|
|
run.status = 'failed'
|
|
run.error_message = str(e)
|
|
db.session.commit()
|
|
import traceback
|
|
raise AppError(code='SYSTEM.HTTP_ERROR', message=str(e), http_status=400, details={'sql': test_sql, 'traceback': traceback.format_exc()})
|
|
|
|
@schedule_admin_bp.route('/schedules', methods=['GET'])
|
|
@require_admin
|
|
def get_schedules():
|
|
return jsonify(list_tasks())
|
|
|
|
@schedule_admin_bp.route('/schedules/<int:task_id>/export', methods=['GET'])
|
|
@require_admin
|
|
def export_schedule(task_id: int):
|
|
task = db.session.get(ScheduleTask, task_id)
|
|
if not task:
|
|
raise NotFoundError('Not found')
|
|
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
|
payload = {'schema_version': 1, 'exported_at': datetime.utcnow().isoformat(), 'schedules': [_serialize_task_for_export(task, cfg_model)]}
|
|
body = json.dumps(payload, ensure_ascii=False, indent=2)
|
|
filename = f"{task.schedule_no or f'schedule_{task.id}'}_export_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.json"
|
|
return Response(body, mimetype='application/json; charset=utf-8', headers={'Content-Disposition': f'attachment; filename="{filename}"'})
|
|
|
|
@schedule_admin_bp.route('/schedules/import', methods=['POST'])
|
|
@require_admin
|
|
def import_schedules():
|
|
data = request.get_json(silent=True) or {}
|
|
schedules = data.get('schedules')
|
|
if not isinstance(schedules, list):
|
|
raise ValidationError('Invalid import file: schedules missing')
|
|
user = get_current_user()
|
|
imported = 0
|
|
skipped = 0
|
|
errors: list[str] = []
|
|
for item in schedules:
|
|
if not isinstance(item, dict):
|
|
skipped += 1
|
|
continue
|
|
try:
|
|
name = str(item.get('name') or '').strip()
|
|
cron_expr = str(item.get('cron_expr') or '').strip()
|
|
owner_user_id = int(item.get('owner_user_id'))
|
|
if not name or not cron_expr:
|
|
raise ValueError('name or cron_expr missing')
|
|
existing = None
|
|
schedule_no = str(item.get('schedule_no') or '').strip()
|
|
if schedule_no:
|
|
existing = db.session.query(ScheduleTask).filter_by(schedule_no=schedule_no).first()
|
|
task_payload = {'name': name, 'schedule_type': str(item.get('schedule_type') or 'platform_app'), 'owner_user_id': owner_user_id, 'cron_expr': cron_expr, 'wait_seconds': int(item.get('wait_seconds') or 0), 'dify_agent_id': item.get('dify_agent_id'), 'platform_api_path': item.get('platform_api_path'), 'notify_user_ids_json': item.get('notify_user_ids_json') if isinstance(item.get('notify_user_ids_json'), list) else [], 'notify_enabled': bool(item.get('notify_enabled', True)), 'enabled': bool(item.get('enabled', True)), 'data_source_type': str(item.get('data_source_type') or 'database'), 'kb_sync_enabled': bool(item.get('kb_sync_enabled', False)), 'kb_group_id': item.get('kb_group_id')}
|
|
cfg = item.get('config') if isinstance(item.get('config'), dict) else None
|
|
if existing:
|
|
update_task(existing, payload=task_payload, actor_id=getattr(user, 'id', None))
|
|
existing.data_source_type = task_payload['data_source_type']
|
|
if cfg:
|
|
upsert_schedule_task_config(existing.id, cfg)
|
|
else:
|
|
task = create_task(name=name, schedule_type=task_payload['schedule_type'], owner_user_id=owner_user_id, cron_expr=cron_expr, wait_seconds=task_payload['wait_seconds'], dify_agent_id=task_payload['dify_agent_id'], platform_api_path=task_payload['platform_api_path'], notify_user_ids_json=task_payload['notify_user_ids_json'], notify_enabled=task_payload['notify_enabled'], enabled=task_payload['enabled'], actor_id=getattr(user, 'id', None))
|
|
task.data_source_type = task_payload['data_source_type']
|
|
task.kb_sync_enabled = task_payload['kb_sync_enabled']
|
|
task.kb_group_id = int(task_payload['kb_group_id']) if task_payload.get('kb_group_id') not in (None, '', 0, '0') else None
|
|
db.session.commit()
|
|
if cfg:
|
|
upsert_schedule_task_config(task.id, cfg)
|
|
imported += 1
|
|
except Exception as exc:
|
|
errors.append(str(exc))
|
|
skipped += 1
|
|
db.session.commit()
|
|
return jsonify({'ok': True, 'imported': imported, 'skipped': skipped, 'errors': errors[:20]})
|
|
|
|
@schedule_admin_bp.route('/schedules', methods=['POST'])
|
|
@require_admin
|
|
def post_schedule():
|
|
data = request.get_json(silent=True) or {}
|
|
user = get_current_user()
|
|
data_source_type = str(data.get('data_source_type') or 'database')
|
|
task = create_task(name=str(data.get('name') or '').strip(), schedule_type='platform_app', owner_user_id=int(data.get('owner_user_id')), cron_expr=str(data.get('cron_expr') or '').strip(), wait_seconds=int(data.get('wait_seconds') or 0), dify_agent_id=int(data.get('dify_agent_id')) if data.get('dify_agent_id') is not None else None, platform_api_path=str(data.get('platform_api_path') or '').strip() or None, notify_user_ids_json=data.get('notify_user_ids_json') if isinstance(data.get('notify_user_ids_json'), list) else [], notify_enabled=bool(data.get('notify_enabled', True)), enabled=bool(data.get('enabled', True)), actor_id=getattr(user, 'id', None))
|
|
task.data_source_type = data_source_type
|
|
task.kb_sync_enabled = bool(data.get('kb_sync_enabled', False))
|
|
raw_kb_group_id = data.get('kb_group_id')
|
|
task.kb_group_id = int(raw_kb_group_id) if raw_kb_group_id not in (None, '', 0, '0') else None
|
|
task.platform_api_path = f'/{task.id}'
|
|
db.session.commit()
|
|
db.session.refresh(task)
|
|
config_data = data.get('config')
|
|
if config_data:
|
|
upsert_schedule_task_config(task.id, config_data)
|
|
if not task.dify_agent_id:
|
|
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task.id).first()
|
|
if cfg_model and cfg_model.dify_system_prompt:
|
|
cfg_model.dify_system_prompt = None
|
|
db.session.commit()
|
|
return (jsonify(serialize_task(task)), 201)
|
|
|
|
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['GET'])
|
|
@require_admin
|
|
def get_schedule(task_id: int):
|
|
task = db.session.get(ScheduleTask, task_id)
|
|
if not task:
|
|
raise NotFoundError('Not found')
|
|
return jsonify(serialize_task(task))
|
|
|
|
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['PATCH'])
|
|
@require_admin
|
|
def patch_schedule(task_id: int):
|
|
task = db.session.get(ScheduleTask, task_id)
|
|
if not task:
|
|
raise NotFoundError('Not found')
|
|
data = request.get_json(silent=True) or {}
|
|
user = get_current_user()
|
|
if 'data_source_type' in data:
|
|
task.data_source_type = str(data['data_source_type'])
|
|
db.session.commit()
|
|
config_data = data.get('config')
|
|
if config_data:
|
|
upsert_schedule_task_config(task_id, config_data)
|
|
task = update_task(task, payload=data, actor_id=getattr(user, 'id', None))
|
|
if not task.dify_agent_id:
|
|
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
|
if cfg_model and cfg_model.dify_system_prompt:
|
|
cfg_model.dify_system_prompt = None
|
|
db.session.commit()
|
|
return jsonify(serialize_task(task))
|
|
|
|
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['DELETE'])
|
|
@require_admin
|
|
def delete_schedule(task_id: int):
|
|
task = db.session.get(ScheduleTask, task_id)
|
|
if not task:
|
|
raise NotFoundError('Not found')
|
|
from app.services.schedule.scheduler_service import request_cancel_run
|
|
running_runs = db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task_id, ScheduleRun.status == 'running').all()
|
|
for rr in running_runs:
|
|
request_cancel_run(rr.id)
|
|
rr.status = 'failed'
|
|
rr.error_message = '排程已被删除,执行中断'
|
|
rr.finished_at = datetime.utcnow()
|
|
if running_runs:
|
|
db.session.commit()
|
|
db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task_id).delete(synchronize_session=False)
|
|
db.session.delete(task)
|
|
db.session.commit()
|
|
return jsonify({'ok': True})
|
|
|
|
@schedule_admin_bp.route('/schedules/<int:task_id>/enable', methods=['POST'])
|
|
@require_admin
|
|
def enable_schedule(task_id: int):
|
|
task = db.session.get(ScheduleTask, task_id)
|
|
if not task:
|
|
raise NotFoundError('Not found')
|
|
task.enabled = True
|
|
if task.cron_expr:
|
|
try:
|
|
from croniter import croniter
|
|
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()
|
|
return jsonify({'ok': True})
|
|
|
|
@schedule_admin_bp.route('/schedules/<int:task_id>/disable', methods=['POST'])
|
|
@require_admin
|
|
def disable_schedule(task_id: int):
|
|
task = db.session.get(ScheduleTask, task_id)
|
|
if not task:
|
|
raise NotFoundError('Not found')
|
|
task.enabled = False
|
|
db.session.commit()
|
|
return jsonify({'ok': True})
|
|
|
|
@schedule_admin_bp.route('/schedules/<int:task_id>/run', methods=['POST'])
|
|
@require_admin
|
|
def run_schedule(task_id: int):
|
|
task = db.session.get(ScheduleTask, task_id)
|
|
if not task:
|
|
raise NotFoundError('Not found')
|
|
user = get_current_user()
|
|
existing = db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task.id, ScheduleRun.status == 'running').first()
|
|
if existing:
|
|
raise ConflictError('该排程正在执行中,请等待完成后再试', details={'run_id': existing.id})
|
|
run = ScheduleRun(run_no=_generate_run_no(), schedule_task_id=task.id, trigger_type='manual', triggered_by_user_id=getattr(user, 'id', None), started_at=datetime.utcnow(), status='running')
|
|
db.session.add(run)
|
|
db.session.commit()
|
|
app = current_app._get_current_object()
|
|
run_id = run.id
|
|
|
|
def _background():
|
|
with app.app_context():
|
|
t = db.session.get(ScheduleTask, task_id)
|
|
r = db.session.get(ScheduleRun, run_id)
|
|
if not t or not r:
|
|
return
|
|
try:
|
|
run_task_now(t, trigger_type='manual', triggered_by_user_id=r.triggered_by_user_id, run=r)
|
|
except Exception as exc:
|
|
try:
|
|
r = db.session.get(ScheduleRun, run_id)
|
|
if r and r.status == 'running':
|
|
r.status = 'failed'
|
|
r.error_message = str(exc)
|
|
r.finished_at = datetime.utcnow()
|
|
db.session.commit()
|
|
except Exception:
|
|
db.session.rollback()
|
|
current_app.logger.error('[schedule-run] run_id=%s failed: %s', run_id, exc, exc_info=True)
|
|
t = threading.Thread(target=_background, daemon=True, name=f'schedule-run-{run_id}')
|
|
t.start()
|
|
fresh = db.session.get(ScheduleRun, run_id)
|
|
return jsonify(serialize_run(fresh))
|
|
|
|
@schedule_admin_bp.route('/schedules/<int:task_id>/runs', methods=['GET'])
|
|
@require_admin
|
|
def get_schedule_runs(task_id: int):
|
|
status = str(request.args.get('status') or '').strip() or None
|
|
limit = int(request.args.get('limit') or 100)
|
|
started_after = None
|
|
started_before = None
|
|
sa = request.args.get('started_after')
|
|
sb = request.args.get('started_before')
|
|
if sa:
|
|
try:
|
|
started_after = datetime.fromisoformat(sa.replace('Z', '+00:00'))
|
|
except (ValueError, TypeError):
|
|
pass
|
|
if sb:
|
|
try:
|
|
started_before = datetime.fromisoformat(sb.replace('Z', '+00:00'))
|
|
except (ValueError, TypeError):
|
|
pass
|
|
return jsonify(list_runs(task_id=task_id, status=status, started_after=started_after, started_before=started_before, limit=limit))
|
|
|
|
@schedule_admin_bp.route('/schedule-runs/<int:run_id>', methods=['GET'])
|
|
@require_admin
|
|
def get_schedule_run(run_id: int):
|
|
run = get_run(run_id)
|
|
if not run:
|
|
raise NotFoundError('Not found')
|
|
return jsonify(serialize_run(run))
|
|
|
|
@schedule_admin_bp.route('/schedule-runs/<int:run_id>/excel', methods=['GET'])
|
|
@require_admin
|
|
def get_schedule_run_excel(run_id: int):
|
|
from io import BytesIO
|
|
run = get_run(run_id)
|
|
if not run:
|
|
raise NotFoundError('Not found')
|
|
if not run.excel_file_data:
|
|
raise NotFoundError('Excel not found')
|
|
buf = BytesIO(run.excel_file_data)
|
|
return send_file(buf, as_attachment=True, download_name=run.excel_file_name or 'result.xlsx', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
|