flowdeck 0.2.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- flowdeck/__init__.py +65 -0
- flowdeck/_version.py +1 -0
- flowdeck/api/__init__.py +216 -0
- flowdeck/api/routers/__init__.py +1 -0
- flowdeck/api/routers/dashboard.py +73 -0
- flowdeck/api/routers/health.py +26 -0
- flowdeck/api/routers/notifications.py +92 -0
- flowdeck/api/routers/pipelines.py +274 -0
- flowdeck/api/routers/runs.py +227 -0
- flowdeck/api/routers/schedule_exceptions.py +141 -0
- flowdeck/api/routers/system.py +386 -0
- flowdeck/api/routers/ui_pipelines.py +507 -0
- flowdeck/api/routers/ui_task_tools.py +275 -0
- flowdeck/api/routers/webhooks.py +115 -0
- flowdeck/auth/__init__.py +0 -0
- flowdeck/auth/basic.py +65 -0
- flowdeck/cli.py +40 -0
- flowdeck/config.py +240 -0
- flowdeck/database/__init__.py +0 -0
- flowdeck/database/base.py +91 -0
- flowdeck/database/models.py +218 -0
- flowdeck/database/repository.py +1231 -0
- flowdeck/logger/__init__.py +122 -0
- flowdeck/logger/formatter.py +112 -0
- flowdeck/logger/web_socket_handler.py +85 -0
- flowdeck/notifications/__init__.py +13 -0
- flowdeck/notifications/email_sender.py +79 -0
- flowdeck/notifications/engine.py +412 -0
- flowdeck/notifications/rules.py +22 -0
- flowdeck/notifications/table_image.py +273 -0
- flowdeck/notifications/task_result.py +478 -0
- flowdeck/notifications/templates.py +224 -0
- flowdeck/orchestrator/__init__.py +380 -0
- flowdeck/orchestrator/executor.py +661 -0
- flowdeck/pipeline/__init__.py +5 -0
- flowdeck/pipeline/_utils.py +11 -0
- flowdeck/pipeline/context.py +13 -0
- flowdeck/pipeline/pipeline.py +40 -0
- flowdeck/pipeline/schedule.py +125 -0
- flowdeck/pipeline/task.py +104 -0
- flowdeck/pipeline/trigger.py +22 -0
- flowdeck/schemas.py +11 -0
- flowdeck/static/assets/BackfillModal-BViyo-00.js +1 -0
- flowdeck/static/assets/BackfillModal-D6je7CRx.css +1 -0
- flowdeck/static/assets/Btn-B77BQZvQ.js +1 -0
- flowdeck/static/assets/Btn-D6G_tsbF.css +1 -0
- flowdeck/static/assets/DashboardView-BM-S5j64.js +1 -0
- flowdeck/static/assets/DashboardView-CBu0kYw6.css +1 -0
- flowdeck/static/assets/DatePickerField-IOKwxOwp.js +830 -0
- flowdeck/static/assets/Empty-B5kRTX_h.css +1 -0
- flowdeck/static/assets/Empty-ScitfHnD.js +1 -0
- flowdeck/static/assets/Modal-7xA4aZKG.js +1 -0
- flowdeck/static/assets/Modal-BNFhtIvK.css +1 -0
- flowdeck/static/assets/NotificationsView-BTkWFeLt.css +1 -0
- flowdeck/static/assets/NotificationsView-BkofWdjj.js +1 -0
- flowdeck/static/assets/NotifySettings-BFdtzy6K.js +1 -0
- flowdeck/static/assets/NotifySettings-D9Nn2RLl.css +1 -0
- flowdeck/static/assets/NumInput--MSEekvd.js +582 -0
- flowdeck/static/assets/NumInput-DfqPA-uG.css +1 -0
- flowdeck/static/assets/PageHeader-3D30Zbvm.js +1 -0
- flowdeck/static/assets/PageHeader-BULVGwbD.css +1 -0
- flowdeck/static/assets/PipelineDetailView-89815vAO.js +1 -0
- flowdeck/static/assets/PipelineDetailView-B_iVBCYT.css +1 -0
- flowdeck/static/assets/PipelinesView-CtDub3qu.js +1 -0
- flowdeck/static/assets/PipelinesView-DC9QO4Wr.css +1 -0
- flowdeck/static/assets/PrettyJson-DjAv38hk.css +1 -0
- flowdeck/static/assets/PrettyJson-_gjY71Cb.js +1 -0
- flowdeck/static/assets/RecentFailuresView-CruW_Dj8.js +1 -0
- flowdeck/static/assets/RecentFailuresView-DjQsiRv9.css +1 -0
- flowdeck/static/assets/RunDetailView--NojY8JX.css +1 -0
- flowdeck/static/assets/RunDetailView-2ZVPmVgW.js +5 -0
- flowdeck/static/assets/ScheduleExceptionsView-DdccyMcD.js +2 -0
- flowdeck/static/assets/ScheduleExceptionsView-pWTB9mSE.css +1 -0
- flowdeck/static/assets/SettingsView-BwlizulV.js +4 -0
- flowdeck/static/assets/SettingsView-D4ybFG31.css +1 -0
- flowdeck/static/assets/StatCard-CdPYF8jZ.js +1 -0
- flowdeck/static/assets/StatCard-D06FdLL9.css +1 -0
- flowdeck/static/assets/StatsView-88bkL-AN.css +1 -0
- flowdeck/static/assets/StatsView-DONGQHCc.js +18 -0
- flowdeck/static/assets/StatusBadge-BDBPRgRa.css +1 -0
- flowdeck/static/assets/StatusBadge-DzUDQ0X_.js +1 -0
- flowdeck/static/assets/ToggleSwitch-KMgLwPsM.js +1 -0
- flowdeck/static/assets/ToggleSwitch-UNHeNS9K.css +1 -0
- flowdeck/static/assets/UiPipelinesView-BgzBgUYR.css +1 -0
- flowdeck/static/assets/UiPipelinesView-WTYqKxB5.js +2 -0
- flowdeck/static/assets/UiTaskEditorView-BgYyqqgT.js +10 -0
- flowdeck/static/assets/UiTaskEditorView-Dl6zmLDP.css +1 -0
- flowdeck/static/assets/_plugin-vue_export-helper-OBKhRxFI.js +12 -0
- flowdeck/static/assets/chakra-petch-latin-400-normal-D7EtbySE.woff +0 -0
- flowdeck/static/assets/chakra-petch-latin-400-normal-SafcrIr2.woff2 +0 -0
- flowdeck/static/assets/chakra-petch-latin-500-normal-BR1ody1F.woff2 +0 -0
- flowdeck/static/assets/chakra-petch-latin-500-normal-CnUQnZ4D.woff +0 -0
- flowdeck/static/assets/chakra-petch-latin-600-normal-DQKfcdKo.woff +0 -0
- flowdeck/static/assets/chakra-petch-latin-600-normal-DVQm9bgb.woff2 +0 -0
- flowdeck/static/assets/chakra-petch-latin-700-normal-CnDBPjkL.woff2 +0 -0
- flowdeck/static/assets/chakra-petch-latin-700-normal-D1s_c2du.woff +0 -0
- flowdeck/static/assets/chakra-petch-latin-ext-400-normal-C8u6EFkq.woff2 +0 -0
- flowdeck/static/assets/chakra-petch-latin-ext-400-normal-MNNNbyh_.woff +0 -0
- flowdeck/static/assets/chakra-petch-latin-ext-500-normal-BCHeNDEx.woff +0 -0
- flowdeck/static/assets/chakra-petch-latin-ext-500-normal-gA6791b0.woff2 +0 -0
- flowdeck/static/assets/chakra-petch-latin-ext-600-normal-CdGvbdDU.woff2 +0 -0
- flowdeck/static/assets/chakra-petch-latin-ext-600-normal-nL80L4xU.woff +0 -0
- flowdeck/static/assets/chakra-petch-latin-ext-700-normal-BeviJPUl.woff +0 -0
- flowdeck/static/assets/chakra-petch-latin-ext-700-normal-DAkvJhej.woff2 +0 -0
- flowdeck/static/assets/chakra-petch-thai-400-normal-Bw1Q-fVY.woff2 +0 -0
- flowdeck/static/assets/chakra-petch-thai-400-normal-KdzBjiWs.woff +0 -0
- flowdeck/static/assets/chakra-petch-thai-500-normal-CJG_V2_m.woff +0 -0
- flowdeck/static/assets/chakra-petch-thai-500-normal-DeexCGiz.woff2 +0 -0
- flowdeck/static/assets/chakra-petch-thai-600-normal-BiM5MXH8.woff +0 -0
- flowdeck/static/assets/chakra-petch-thai-600-normal-C620THcd.woff2 +0 -0
- flowdeck/static/assets/chakra-petch-thai-700-normal-B7WL5pBr.woff2 +0 -0
- flowdeck/static/assets/chakra-petch-thai-700-normal-vZLZ_5L8.woff +0 -0
- flowdeck/static/assets/chakra-petch-vietnamese-400-normal-Cn7ya5On.woff +0 -0
- flowdeck/static/assets/chakra-petch-vietnamese-500-normal-BVzUBLGs.woff +0 -0
- flowdeck/static/assets/chakra-petch-vietnamese-600-normal-Pvj4qcw_.woff +0 -0
- flowdeck/static/assets/chakra-petch-vietnamese-700-normal-gQuUA8Wu.woff +0 -0
- flowdeck/static/assets/index-DpymzEZv.css +1 -0
- flowdeck/static/assets/index-DuXbXiXo.js +2 -0
- flowdeck/static/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
- flowdeck/static/assets/jetbrains-mono-cyrillic-400-normal-ugxPyKxw.woff +0 -0
- flowdeck/static/assets/jetbrains-mono-cyrillic-500-normal-DJqRU3vO.woff +0 -0
- flowdeck/static/assets/jetbrains-mono-cyrillic-500-normal-DmUKJPL_.woff2 +0 -0
- flowdeck/static/assets/jetbrains-mono-cyrillic-700-normal-BWTpRfYl.woff2 +0 -0
- flowdeck/static/assets/jetbrains-mono-cyrillic-700-normal-CEoEElIJ.woff +0 -0
- flowdeck/static/assets/jetbrains-mono-greek-400-normal-B9oWc5Lo.woff +0 -0
- flowdeck/static/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
- flowdeck/static/assets/jetbrains-mono-greek-500-normal-D7SFKleX.woff +0 -0
- flowdeck/static/assets/jetbrains-mono-greek-500-normal-JpySY46c.woff2 +0 -0
- flowdeck/static/assets/jetbrains-mono-greek-700-normal-C6CZE3T8.woff2 +0 -0
- flowdeck/static/assets/jetbrains-mono-greek-700-normal-DEigVDxa.woff +0 -0
- flowdeck/static/assets/jetbrains-mono-latin-400-normal-6-qcROiO.woff +0 -0
- flowdeck/static/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
- flowdeck/static/assets/jetbrains-mono-latin-500-normal-BWZEU5yA.woff2 +0 -0
- flowdeck/static/assets/jetbrains-mono-latin-500-normal-CJOVTJB7.woff +0 -0
- flowdeck/static/assets/jetbrains-mono-latin-700-normal-BYuf6tUa.woff2 +0 -0
- flowdeck/static/assets/jetbrains-mono-latin-700-normal-D3wTyLJW.woff +0 -0
- flowdeck/static/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
- flowdeck/static/assets/jetbrains-mono-latin-ext-400-normal-fXTG6kC5.woff +0 -0
- flowdeck/static/assets/jetbrains-mono-latin-ext-500-normal-Cut-4mMH.woff2 +0 -0
- flowdeck/static/assets/jetbrains-mono-latin-ext-500-normal-ckzbgY84.woff +0 -0
- flowdeck/static/assets/jetbrains-mono-latin-ext-700-normal-CZipNAKV.woff2 +0 -0
- flowdeck/static/assets/jetbrains-mono-latin-ext-700-normal-CxPITLHs.woff +0 -0
- flowdeck/static/assets/jetbrains-mono-vietnamese-400-normal-CqNFfHCs.woff +0 -0
- flowdeck/static/assets/jetbrains-mono-vietnamese-500-normal-DNRqzVM1.woff +0 -0
- flowdeck/static/assets/jetbrains-mono-vietnamese-700-normal-BDLVIk2r.woff +0 -0
- flowdeck/static/assets/light-B0F-b5Z6.js +20 -0
- flowdeck/static/assets/runtime-dom.esm-bundler-DESsN8Jj.js +2 -0
- flowdeck/static/favicon.svg +13 -0
- flowdeck/static/index.html +18 -0
- flowdeck/storage.py +145 -0
- flowdeck/tasks/__init__.py +1 -0
- flowdeck/tasks/http_executor.py +985 -0
- flowdeck/tasks/paramdefs.py +170 -0
- flowdeck/tasks/paramextract.py +185 -0
- flowdeck/tasks/python_executor.py +234 -0
- flowdeck/tasks/sql_executor.py +683 -0
- flowdeck/tasks/timevars.py +125 -0
- flowdeck/tasks/ui_registry.py +394 -0
- flowdeck-0.2.1.dist-info/METADATA +228 -0
- flowdeck-0.2.1.dist-info/RECORD +163 -0
- flowdeck-0.2.1.dist-info/WHEEL +4 -0
- flowdeck-0.2.1.dist-info/entry_points.txt +2 -0
- flowdeck-0.2.1.dist-info/licenses/LICENSE +293 -0
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
"""通知 payload 模板:json / wecom_text / wecom_markdown 三种格式 + 邮件 HTML。"""
|
|
2
|
+
|
|
3
|
+
from datetime import datetime
|
|
4
|
+
from html import escape
|
|
5
|
+
from typing import Any, Dict
|
|
6
|
+
|
|
7
|
+
from flowdeck.notifications.rules import NotificationRuleSchema
|
|
8
|
+
|
|
9
|
+
EVENT_DESCRIPTIONS = {
|
|
10
|
+
"succeeded": "任务成功",
|
|
11
|
+
"failed": "任务失败",
|
|
12
|
+
"timeout": "任务超时",
|
|
13
|
+
"missed": "任务漏跑",
|
|
14
|
+
"skipped": "任务跳过",
|
|
15
|
+
"alert": "业务告警",
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
_TIME_FORMAT = "%Y-%m-%d %H:%M:%S"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _fmt_time(value: Any) -> Any:
|
|
22
|
+
"""datetime → ``%Y-%m-%d %H:%M:%S``,其余原样返回。"""
|
|
23
|
+
if isinstance(value, datetime):
|
|
24
|
+
return value.strftime(_TIME_FORMAT)
|
|
25
|
+
return value
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _truncate(value: Any, limit: int = 200) -> Any:
|
|
29
|
+
if not isinstance(value, str) or len(value) <= limit:
|
|
30
|
+
return value
|
|
31
|
+
return value[:limit] + "…"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _error_summary(error: Any, limit: int = 200) -> Any:
|
|
35
|
+
"""给人看的错误摘要:traceback 取最后一行(异常类型与消息,信息量最大,
|
|
36
|
+
截头部只会剩文件路径);单行或超长时退化为普通截断。"""
|
|
37
|
+
if not isinstance(error, str) or not error:
|
|
38
|
+
return error
|
|
39
|
+
lines = [line for line in error.strip().splitlines() if line.strip()]
|
|
40
|
+
if len(lines) >= 2 and len(lines[-1]) <= limit:
|
|
41
|
+
return lines[-1]
|
|
42
|
+
return _truncate(error, limit)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _mention_text(rule: NotificationRuleSchema) -> list:
|
|
46
|
+
"""@ 名单(userid 列表),去空并保序去重。"""
|
|
47
|
+
seen: list = []
|
|
48
|
+
for user in rule.mentioned_list or []:
|
|
49
|
+
if user and user not in seen:
|
|
50
|
+
seen.append(user)
|
|
51
|
+
return seen
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _run_link(context: dict) -> tuple:
|
|
55
|
+
"""运行详情链接:(url, 基地址是否已配置)。
|
|
56
|
+
|
|
57
|
+
``run_url`` 由通知引擎按 DB 设置项 base_url 生成;未配置时是相对路径
|
|
58
|
+
``/runs/{id}``,模板必须显式提示而不是伪装成可点击的绝对地址。
|
|
59
|
+
"""
|
|
60
|
+
url = context.get("run_url")
|
|
61
|
+
if not url:
|
|
62
|
+
return "", False
|
|
63
|
+
return str(url), bool(context.get("base_url"))
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def render_payload(
|
|
67
|
+
rule: NotificationRuleSchema, event: str, context: dict
|
|
68
|
+
) -> Dict[str, Any]:
|
|
69
|
+
"""按 rule.template 渲染 webhook payload(JSON 可直接 POST)。"""
|
|
70
|
+
pipeline_id = context.get("pipeline_id")
|
|
71
|
+
run_id = context.get("run_id")
|
|
72
|
+
status = context.get("status")
|
|
73
|
+
start_time = _fmt_time(context.get("start_time"))
|
|
74
|
+
duration = context.get("duration_seconds")
|
|
75
|
+
error = _truncate(context.get("error"))
|
|
76
|
+
error_summary = _error_summary(context.get("error"))
|
|
77
|
+
detail = context.get("detail")
|
|
78
|
+
failed_task_id = context.get("failed_task_id")
|
|
79
|
+
run_url, base_configured = _run_link(context)
|
|
80
|
+
event_cn = EVENT_DESCRIPTIONS.get(event, event)
|
|
81
|
+
|
|
82
|
+
if rule.template == "wecom_text":
|
|
83
|
+
lines = [f"[FlowDeck] {event_cn}:{pipeline_id}"]
|
|
84
|
+
if run_id is not None:
|
|
85
|
+
lines.append(f"Run:{run_id}")
|
|
86
|
+
lines.append(f"状态:{status if status is not None else event}")
|
|
87
|
+
if start_time is not None:
|
|
88
|
+
lines.append(f"开始时间:{start_time}")
|
|
89
|
+
if duration is not None:
|
|
90
|
+
lines.append(f"耗时:{duration}秒")
|
|
91
|
+
if failed_task_id:
|
|
92
|
+
lines.append(f"失败任务:{failed_task_id}")
|
|
93
|
+
if error_summary:
|
|
94
|
+
lines.append(f"错误:{error_summary}")
|
|
95
|
+
if detail:
|
|
96
|
+
lines.append(f"详情:{detail}")
|
|
97
|
+
if run_url:
|
|
98
|
+
if base_configured:
|
|
99
|
+
lines.append(f"详情链接:{run_url}")
|
|
100
|
+
else:
|
|
101
|
+
lines.append(f"详情链接:{run_url}(相对路径,未配置站点地址)")
|
|
102
|
+
text: Dict[str, Any] = {"content": "\n".join(lines)}
|
|
103
|
+
# 企微 text 模板的 @ 走 mentioned_list(特殊值 "@all" 表示全员)
|
|
104
|
+
mentioned = _mention_text(rule)
|
|
105
|
+
if mentioned:
|
|
106
|
+
text["mentioned_list"] = mentioned
|
|
107
|
+
return {"msgtype": "text", "text": text}
|
|
108
|
+
|
|
109
|
+
if rule.template == "wecom_markdown":
|
|
110
|
+
content = (
|
|
111
|
+
"**任务通知**\n"
|
|
112
|
+
f"> 事件:{event_cn}\n"
|
|
113
|
+
f"> Pipeline:{pipeline_id}\n"
|
|
114
|
+
f"> Run:{run_id if run_id is not None else '无'}\n"
|
|
115
|
+
f"> 状态:{status if status is not None else event}\n"
|
|
116
|
+
f"> 耗时:{duration if duration is not None else '无'}"
|
|
117
|
+
)
|
|
118
|
+
if failed_task_id:
|
|
119
|
+
content += f"\n> 失败任务:{failed_task_id}"
|
|
120
|
+
content += f"\n> 错误:{error_summary if error_summary else '无'}"
|
|
121
|
+
if detail:
|
|
122
|
+
content += f"\n> 详情:{detail}"
|
|
123
|
+
if run_url:
|
|
124
|
+
# 企微 markdown 链接语法 [文本](url);未配置基地址时只给路径并提示
|
|
125
|
+
if base_configured:
|
|
126
|
+
content += f"\n> 详情:[查看运行详情]({run_url})"
|
|
127
|
+
else:
|
|
128
|
+
content += f"\n> 详情:{run_url}(相对路径,未配置站点地址)"
|
|
129
|
+
# 企微 markdown 模板的 @ 走 <@userid> 内联语法
|
|
130
|
+
mentions = "".join(f"<@{user}>" for user in _mention_text(rule))
|
|
131
|
+
if mentions:
|
|
132
|
+
content += f"\n{mentions}"
|
|
133
|
+
return {"msgtype": "markdown", "markdown": {"content": content}}
|
|
134
|
+
|
|
135
|
+
# 默认 json
|
|
136
|
+
return {
|
|
137
|
+
"event": event,
|
|
138
|
+
"pipeline_id": pipeline_id,
|
|
139
|
+
"run_id": run_id,
|
|
140
|
+
"status": status,
|
|
141
|
+
"start_time": start_time,
|
|
142
|
+
"duration_seconds": duration,
|
|
143
|
+
"error": error,
|
|
144
|
+
"failed_task_id": failed_task_id,
|
|
145
|
+
"run_url": run_url or None,
|
|
146
|
+
"detail": detail,
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def render_email(
|
|
151
|
+
rule: NotificationRuleSchema, event: str, context: dict
|
|
152
|
+
) -> tuple:
|
|
153
|
+
"""渲染邮件渠道的 (subject, html_body)。
|
|
154
|
+
|
|
155
|
+
邮件正文使用 HTML,配置了站点基地址时运行详情链接可直接点击;
|
|
156
|
+
未配置时明确提示「未配置站点地址」,只展示相对路径(避免发错误链接)。
|
|
157
|
+
"""
|
|
158
|
+
pipeline_id = context.get("pipeline_id")
|
|
159
|
+
run_id = context.get("run_id")
|
|
160
|
+
status = context.get("status")
|
|
161
|
+
start_time = _fmt_time(context.get("start_time"))
|
|
162
|
+
duration = context.get("duration_seconds")
|
|
163
|
+
error_summary = _error_summary(context.get("error"), limit=1500)
|
|
164
|
+
failed_task_id = context.get("failed_task_id")
|
|
165
|
+
detail = context.get("detail")
|
|
166
|
+
run_url, base_configured = _run_link(context)
|
|
167
|
+
event_cn = EVENT_DESCRIPTIONS.get(event, event)
|
|
168
|
+
|
|
169
|
+
subject = f"[FlowDeck] {event_cn}:{pipeline_id or '-'}"
|
|
170
|
+
if run_id is not None:
|
|
171
|
+
subject += f" #{run_id}"
|
|
172
|
+
|
|
173
|
+
rows = [("事件", event_cn)]
|
|
174
|
+
if pipeline_id is not None:
|
|
175
|
+
rows.append(("Pipeline", str(pipeline_id)))
|
|
176
|
+
if run_id is not None:
|
|
177
|
+
rows.append(("Run", str(run_id)))
|
|
178
|
+
if status is not None:
|
|
179
|
+
rows.append(("状态", str(status)))
|
|
180
|
+
if start_time is not None:
|
|
181
|
+
rows.append(("开始时间", str(start_time)))
|
|
182
|
+
if duration is not None:
|
|
183
|
+
rows.append(("耗时", f"{duration} 秒"))
|
|
184
|
+
if failed_task_id:
|
|
185
|
+
rows.append(("失败任务", str(failed_task_id)))
|
|
186
|
+
if error_summary:
|
|
187
|
+
rows.append(("错误", str(error_summary)))
|
|
188
|
+
if detail:
|
|
189
|
+
rows.append(("详情", str(detail)))
|
|
190
|
+
|
|
191
|
+
body_rows = "".join(
|
|
192
|
+
f'<tr><th align="left" style="padding:4px 12px 4px 0;color:#555;">'
|
|
193
|
+
f"{escape(label)}</th><td style=\"padding:4px 0;\">{escape(value)}</td></tr>"
|
|
194
|
+
for label, value in rows
|
|
195
|
+
)
|
|
196
|
+
|
|
197
|
+
if run_url and base_configured:
|
|
198
|
+
link_html = (
|
|
199
|
+
f'<a href="{escape(run_url, quote=True)}">{escape(run_url)}</a>'
|
|
200
|
+
)
|
|
201
|
+
elif run_url:
|
|
202
|
+
link_html = (
|
|
203
|
+
f"{escape(run_url)}"
|
|
204
|
+
"(相对路径,未配置站点地址,无法生成可点击链接)"
|
|
205
|
+
)
|
|
206
|
+
else:
|
|
207
|
+
link_html = ""
|
|
208
|
+
|
|
209
|
+
link_row = (
|
|
210
|
+
f'<tr><th align="left" style="padding:4px 12px 4px 0;color:#555;">'
|
|
211
|
+
f"详情链接</th><td style=\"padding:4px 0;\">{link_html}</td></tr>"
|
|
212
|
+
if link_html
|
|
213
|
+
else ""
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
html_body = (
|
|
217
|
+
'<div style="font-family:-apple-system,Segoe UI,Helvetica,Arial,sans-serif;'
|
|
218
|
+
'font-size:14px;color:#222;">'
|
|
219
|
+
'<h3 style="margin:0 0 12px;">FlowDeck 任务通知</h3>'
|
|
220
|
+
f'<table style="border-collapse:collapse;">{body_rows}{link_row}</table>'
|
|
221
|
+
"</div>"
|
|
222
|
+
)
|
|
223
|
+
|
|
224
|
+
return subject, html_body
|
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
"""调度核心:pipeline 注册、手动触发、暂停/禁用 override、系统级 job。
|
|
2
|
+
|
|
3
|
+
系统级 job(orchestrator.start() 时注册,异常全部吞掉只记日志):
|
|
4
|
+
- ``__flowdeck_retention``:每日 01:00 清理超过 retention_days 的 runs 与文件产物;
|
|
5
|
+
- ``__flowdeck_missed_patrol``:每小时(minute=10)巡检漏跑,
|
|
6
|
+
由 notifications.engine.run_missed_patrol 实现。
|
|
7
|
+
|
|
8
|
+
启动时执行崩溃恢复(recover_interrupted_runs):把上次进程中断遗留的
|
|
9
|
+
PENDING/RUNNING run 标记为 FAILED,供重跑/断点续跑。
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import logging
|
|
13
|
+
from datetime import datetime, timedelta
|
|
14
|
+
from typing import Dict, List, Optional, Tuple
|
|
15
|
+
|
|
16
|
+
from apscheduler.executors.asyncio import AsyncIOExecutor
|
|
17
|
+
from apscheduler.job import Job
|
|
18
|
+
from apscheduler.schedulers.asyncio import AsyncIOScheduler
|
|
19
|
+
from apscheduler.triggers.cron import CronTrigger
|
|
20
|
+
from apscheduler.triggers.date import DateTrigger
|
|
21
|
+
|
|
22
|
+
from flowdeck.database import repository
|
|
23
|
+
from flowdeck.database.models import PipelineRun
|
|
24
|
+
from flowdeck.notifications.engine import run_missed_patrol
|
|
25
|
+
from flowdeck.pipeline._utils import get_job_id
|
|
26
|
+
from flowdeck.pipeline.pipeline import Pipeline
|
|
27
|
+
from flowdeck.pipeline.trigger import Trigger
|
|
28
|
+
from flowdeck.schemas import PipelineRunStatus
|
|
29
|
+
from flowdeck.storage import cleanup_files_before, delete_run_artifacts
|
|
30
|
+
|
|
31
|
+
from .executor import (
|
|
32
|
+
MANUAL_TRIGGER_ID,
|
|
33
|
+
cancel_run as _cancel_run,
|
|
34
|
+
recover_interrupted_runs,
|
|
35
|
+
run,
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
_logger = logging.getLogger(__name__)
|
|
39
|
+
|
|
40
|
+
RETENTION_JOB_ID = "__flowdeck_retention"
|
|
41
|
+
MISSED_PATROL_JOB_ID = "__flowdeck_missed_patrol"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _retention_cleanup() -> None:
|
|
45
|
+
"""定时清理任务(每日 01:00):run_retention_cleanup 的异常兜底包装。"""
|
|
46
|
+
try:
|
|
47
|
+
run_retention_cleanup()
|
|
48
|
+
except Exception:
|
|
49
|
+
_logger.error("Retention cleanup job failed", exc_info=True)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def run_retention_cleanup(days: int | None = None) -> Dict[str, int]:
|
|
53
|
+
"""执行一次保留期清理,返回统计(供定时任务与「立即清理」API 复用)。
|
|
54
|
+
|
|
55
|
+
days=0 时全量清空(初始化):删除全部 runs 与全部文件产物,不受保留
|
|
56
|
+
策略开关影响;days=None 时按配置的 retention_days(<=0 跳过);
|
|
57
|
+
days>=1 时以该天数为准(设置页「删除 N 天前数据」)。
|
|
58
|
+
先按 cutoff 删过期 runs(连文件产物),再按 mtime 兜底清扫孤儿文件
|
|
59
|
+
(DB 已无对应 run 的日志/数据残留)。
|
|
60
|
+
"""
|
|
61
|
+
retention_days = days if days is not None else repository.get_retention_days()
|
|
62
|
+
result = {
|
|
63
|
+
"retention_days": retention_days,
|
|
64
|
+
"deleted_runs": 0,
|
|
65
|
+
"deleted_files": 0,
|
|
66
|
+
}
|
|
67
|
+
if days != 0 and (not retention_days or retention_days <= 0):
|
|
68
|
+
return result
|
|
69
|
+
|
|
70
|
+
if days == 0:
|
|
71
|
+
cutoff = datetime.now() + timedelta(seconds=1)
|
|
72
|
+
else:
|
|
73
|
+
cutoff = datetime.now() - timedelta(days=retention_days)
|
|
74
|
+
run_ids = repository.delete_runs_before(cutoff)
|
|
75
|
+
|
|
76
|
+
for run_id in run_ids:
|
|
77
|
+
try:
|
|
78
|
+
delete_run_artifacts(run_id)
|
|
79
|
+
except Exception:
|
|
80
|
+
_logger.warning("Can't delete artifacts of run %s", run_id, exc_info=True)
|
|
81
|
+
|
|
82
|
+
result["deleted_runs"] = len(run_ids)
|
|
83
|
+
|
|
84
|
+
try:
|
|
85
|
+
# 孤儿文件兜底:DB 已无对应 run 的文件产物按 mtime 清扫
|
|
86
|
+
result["deleted_files"] = cleanup_files_before(cutoff)
|
|
87
|
+
except Exception:
|
|
88
|
+
_logger.warning("Orphan file sweep failed", exc_info=True)
|
|
89
|
+
|
|
90
|
+
if result["deleted_runs"] or result["deleted_files"]:
|
|
91
|
+
_logger.info(
|
|
92
|
+
"Retention cleanup removed %d runs / %d orphan files before %s",
|
|
93
|
+
result["deleted_runs"],
|
|
94
|
+
result["deleted_files"],
|
|
95
|
+
cutoff,
|
|
96
|
+
)
|
|
97
|
+
return result
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class _Orchestrator:
|
|
101
|
+
def __init__(self) -> None:
|
|
102
|
+
self.scheduler = AsyncIOScheduler()
|
|
103
|
+
self._all_pipelines: Dict[str, Pipeline] = {}
|
|
104
|
+
self._all_triggers: Dict[str, Tuple[Pipeline, Trigger]] = {}
|
|
105
|
+
|
|
106
|
+
def _check_timezone(self) -> None:
|
|
107
|
+
"""时区防漂移自检:实际 UTC 偏移与期望不符时显式告警(防静默错位)。
|
|
108
|
+
|
|
109
|
+
在 start()(init_db 之后)调用,期望值走 DB 优先(设置页可改)。
|
|
110
|
+
"""
|
|
111
|
+
offset = datetime.now().astimezone().strftime("%z")
|
|
112
|
+
expected = repository.get_expected_utc_offset().replace(":", "").strip()
|
|
113
|
+
if expected and offset != expected:
|
|
114
|
+
_logger.error(
|
|
115
|
+
"Timezone mismatch: server UTC offset is %s but expected %s "
|
|
116
|
+
"(settings expected_utc_offset). Scheduled fire times and stored "
|
|
117
|
+
"naive datetimes will be misaligned until the OS timezone is fixed.",
|
|
118
|
+
offset,
|
|
119
|
+
expected,
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
def register_pipeline(self, pipeline: Pipeline) -> None:
|
|
123
|
+
"""注册 pipeline(幂等:重复 id print 后返回)。"""
|
|
124
|
+
if pipeline.id in self._all_pipelines:
|
|
125
|
+
print(f"Pipeline {pipeline.id} already registered")
|
|
126
|
+
return
|
|
127
|
+
|
|
128
|
+
self._all_pipelines[pipeline.id] = pipeline
|
|
129
|
+
|
|
130
|
+
for trigger in pipeline.triggers:
|
|
131
|
+
job_id = get_job_id(pipeline.id, trigger.id)
|
|
132
|
+
self._all_triggers[job_id] = (pipeline, trigger)
|
|
133
|
+
|
|
134
|
+
if trigger.paused:
|
|
135
|
+
# 代码级暂停:完全不进调度器,但仍记入 _all_triggers(UI 可见)
|
|
136
|
+
continue
|
|
137
|
+
|
|
138
|
+
if self.scheduler.get_job(job_id):
|
|
139
|
+
print(f"Job {job_id} already added")
|
|
140
|
+
continue
|
|
141
|
+
|
|
142
|
+
self.scheduler.add_job(
|
|
143
|
+
id=job_id,
|
|
144
|
+
name=job_id,
|
|
145
|
+
func=run,
|
|
146
|
+
trigger=trigger.schedule,
|
|
147
|
+
kwargs=dict(pipeline=pipeline, trigger=trigger),
|
|
148
|
+
# run once instead of many times if the scheduler determines that the
|
|
149
|
+
# job should be run more than once in succession
|
|
150
|
+
coalesce=True,
|
|
151
|
+
# Jobs will be run even if they arrive 1 min late
|
|
152
|
+
misfire_grace_time=60,
|
|
153
|
+
max_instances=10_000,
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
def get_pipeline(self, pipeline_id: str) -> Optional[Pipeline]:
|
|
157
|
+
"""按 id 查找已注册 pipeline,未找到返回 None。"""
|
|
158
|
+
return self._all_pipelines.get(pipeline_id)
|
|
159
|
+
|
|
160
|
+
def unregister_pipeline(self, pipeline_id: str) -> bool:
|
|
161
|
+
"""注销 pipeline:移除调度器 job 与注册表(UI 任务改/删后重建用)。
|
|
162
|
+
|
|
163
|
+
幂等:未注册时返回 False 不报错。
|
|
164
|
+
"""
|
|
165
|
+
pipeline = self._all_pipelines.pop(pipeline_id, None)
|
|
166
|
+
if pipeline is None:
|
|
167
|
+
return False
|
|
168
|
+
|
|
169
|
+
for trigger in pipeline.triggers:
|
|
170
|
+
job_id = get_job_id(pipeline.id, trigger.id)
|
|
171
|
+
self._all_triggers.pop(job_id, None)
|
|
172
|
+
if self.scheduler.get_job(job_id):
|
|
173
|
+
self.scheduler.remove_job(job_id)
|
|
174
|
+
|
|
175
|
+
return True
|
|
176
|
+
|
|
177
|
+
@property
|
|
178
|
+
def pipelines(self) -> Dict[str, Pipeline]:
|
|
179
|
+
return self._all_pipelines
|
|
180
|
+
|
|
181
|
+
def get_pipeline_from_job_id(self, job_id: str) -> Pipeline:
|
|
182
|
+
return self._all_triggers[job_id][0]
|
|
183
|
+
|
|
184
|
+
def get_trigger_from_job_id(self, job_id: str) -> Trigger:
|
|
185
|
+
return self._all_triggers[job_id][1]
|
|
186
|
+
|
|
187
|
+
def get_job(self, pipeline_id: str, trigger_id: str) -> Optional[Job]:
|
|
188
|
+
return self.scheduler.get_job(get_job_id(pipeline_id, trigger_id))
|
|
189
|
+
|
|
190
|
+
# ------------------------------------------------------------------
|
|
191
|
+
# 手动触发
|
|
192
|
+
# ------------------------------------------------------------------
|
|
193
|
+
|
|
194
|
+
def run_pipeline_now(
|
|
195
|
+
self,
|
|
196
|
+
pipeline: Pipeline,
|
|
197
|
+
trigger: Optional[Trigger] = None,
|
|
198
|
+
params: Optional[dict] = None,
|
|
199
|
+
reason: str = "api",
|
|
200
|
+
source_run_id: Optional[int] = None,
|
|
201
|
+
resume_from: Optional[str] = None,
|
|
202
|
+
) -> PipelineRun:
|
|
203
|
+
"""立即手动触发一次运行(不检查 UI 暂停状态),返回 PENDING run。
|
|
204
|
+
|
|
205
|
+
校验失败抛 ValueError(API 层转 422)。投递方式沿用 plombery:
|
|
206
|
+
executor.submit_job + DateTrigger —— 走 APScheduler 执行通道,
|
|
207
|
+
在 async 上下文与 sync 线程(如 FastAPI 线程池端点)里都能投递,
|
|
208
|
+
且统一 job 执行/异常日志路径。要求 scheduler 已 start。
|
|
209
|
+
|
|
210
|
+
- ``source_run_id``:重跑/断点续跑来源 run(记入 runs 表供追溯);
|
|
211
|
+
- ``resume_from``:断点续跑起始 task id(其前任务记 SKIPPED,
|
|
212
|
+
输出数据从 source_run_id 的产物文件复用)。
|
|
213
|
+
"""
|
|
214
|
+
if pipeline.params is not None and params:
|
|
215
|
+
if not isinstance(params, dict):
|
|
216
|
+
raise ValueError(
|
|
217
|
+
f"Invalid params for pipeline {pipeline.id}: "
|
|
218
|
+
f"expected dict, got {type(params).__name__}"
|
|
219
|
+
)
|
|
220
|
+
try:
|
|
221
|
+
pipeline.params(**params)
|
|
222
|
+
except Exception as exc:
|
|
223
|
+
raise ValueError(
|
|
224
|
+
f"Invalid params for pipeline {pipeline.id}: {exc}"
|
|
225
|
+
) from exc
|
|
226
|
+
|
|
227
|
+
trigger_id = trigger.id if trigger else MANUAL_TRIGGER_ID
|
|
228
|
+
pipeline_run = repository.create_pipeline_run(
|
|
229
|
+
pipeline_id=pipeline.id,
|
|
230
|
+
trigger_id=trigger_id,
|
|
231
|
+
status=PipelineRunStatus.PENDING,
|
|
232
|
+
start_time=datetime.now(),
|
|
233
|
+
reason=reason,
|
|
234
|
+
input_params=params or None,
|
|
235
|
+
source_run_id=source_run_id,
|
|
236
|
+
)
|
|
237
|
+
|
|
238
|
+
executor: AsyncIOExecutor = self.scheduler._lookup_executor("default")
|
|
239
|
+
executor.submit_job(
|
|
240
|
+
Job(
|
|
241
|
+
self.scheduler,
|
|
242
|
+
id=get_job_id(pipeline.id, trigger_id),
|
|
243
|
+
func=run,
|
|
244
|
+
args=[],
|
|
245
|
+
kwargs={
|
|
246
|
+
"pipeline": pipeline,
|
|
247
|
+
"trigger": trigger,
|
|
248
|
+
"params": params,
|
|
249
|
+
"pipeline_run": pipeline_run,
|
|
250
|
+
"reason": reason,
|
|
251
|
+
"resume_from": resume_from,
|
|
252
|
+
},
|
|
253
|
+
max_instances=10_000,
|
|
254
|
+
misfire_grace_time=None,
|
|
255
|
+
trigger=DateTrigger(),
|
|
256
|
+
),
|
|
257
|
+
[datetime.now()],
|
|
258
|
+
)
|
|
259
|
+
|
|
260
|
+
return pipeline_run
|
|
261
|
+
|
|
262
|
+
# ------------------------------------------------------------------
|
|
263
|
+
# 暂停 / 禁用(仅写 repository override,不操作调度器)
|
|
264
|
+
# ------------------------------------------------------------------
|
|
265
|
+
|
|
266
|
+
def pause_pipeline(
|
|
267
|
+
self, pipeline_id: str, resume_at: Optional[datetime] = None
|
|
268
|
+
) -> None:
|
|
269
|
+
repository.set_override(pipeline_id, "", resume_at=resume_at)
|
|
270
|
+
|
|
271
|
+
def resume_pipeline(self, pipeline_id: str) -> None:
|
|
272
|
+
repository.clear_override(pipeline_id, "")
|
|
273
|
+
|
|
274
|
+
def disable_trigger(self, pipeline_id: str, trigger_id: str) -> None:
|
|
275
|
+
repository.set_override(pipeline_id, trigger_id)
|
|
276
|
+
|
|
277
|
+
def enable_trigger(self, pipeline_id: str, trigger_id: str) -> None:
|
|
278
|
+
repository.clear_override(pipeline_id, trigger_id)
|
|
279
|
+
|
|
280
|
+
# ------------------------------------------------------------------
|
|
281
|
+
# 未来的运行时间
|
|
282
|
+
# ------------------------------------------------------------------
|
|
283
|
+
|
|
284
|
+
def get_next_run_times(
|
|
285
|
+
self, pipeline_id: str, trigger_id: str, count: int = 5
|
|
286
|
+
) -> List[datetime]:
|
|
287
|
+
"""迭代 trigger.get_next_fire_time 计算 count 个未来触发时间。"""
|
|
288
|
+
job = self.scheduler.get_job(get_job_id(pipeline_id, trigger_id))
|
|
289
|
+
if job is None:
|
|
290
|
+
return []
|
|
291
|
+
|
|
292
|
+
fire_times: List[datetime] = []
|
|
293
|
+
fire_time = None
|
|
294
|
+
search_from = datetime.now().astimezone()
|
|
295
|
+
|
|
296
|
+
for _ in range(count):
|
|
297
|
+
fire_time = job.trigger.get_next_fire_time(fire_time, search_from)
|
|
298
|
+
if fire_time is None:
|
|
299
|
+
break
|
|
300
|
+
fire_times.append(fire_time)
|
|
301
|
+
search_from = fire_time
|
|
302
|
+
|
|
303
|
+
return fire_times
|
|
304
|
+
|
|
305
|
+
# ------------------------------------------------------------------
|
|
306
|
+
# 运行管控:kill
|
|
307
|
+
# ------------------------------------------------------------------
|
|
308
|
+
|
|
309
|
+
def cancel_run(self, run_id: int) -> bool:
|
|
310
|
+
"""请求停止正在执行的 run(委托 executor 的 kill 实现)。"""
|
|
311
|
+
return _cancel_run(run_id)
|
|
312
|
+
|
|
313
|
+
# ------------------------------------------------------------------
|
|
314
|
+
# 生命周期
|
|
315
|
+
# ------------------------------------------------------------------
|
|
316
|
+
|
|
317
|
+
def start(self) -> None:
|
|
318
|
+
repository.init_db()
|
|
319
|
+
try:
|
|
320
|
+
recovered = recover_interrupted_runs()
|
|
321
|
+
if recovered["runs"]:
|
|
322
|
+
_logger.warning(
|
|
323
|
+
"Crash recovery: marked %d interrupted run(s) as failed "
|
|
324
|
+
"(%d task run(s))",
|
|
325
|
+
recovered["runs"],
|
|
326
|
+
recovered["task_runs"],
|
|
327
|
+
)
|
|
328
|
+
except Exception:
|
|
329
|
+
_logger.error("Crash recovery failed", exc_info=True)
|
|
330
|
+
self._check_timezone()
|
|
331
|
+
self._register_system_jobs()
|
|
332
|
+
self.scheduler.start()
|
|
333
|
+
|
|
334
|
+
def stop(self) -> None:
|
|
335
|
+
self.scheduler.shutdown(wait=False)
|
|
336
|
+
|
|
337
|
+
def _register_system_jobs(self) -> None:
|
|
338
|
+
if not self.scheduler.get_job(RETENTION_JOB_ID):
|
|
339
|
+
self.scheduler.add_job(
|
|
340
|
+
id=RETENTION_JOB_ID,
|
|
341
|
+
name=RETENTION_JOB_ID,
|
|
342
|
+
func=_retention_cleanup,
|
|
343
|
+
trigger=CronTrigger(hour=1, minute=0),
|
|
344
|
+
coalesce=True,
|
|
345
|
+
misfire_grace_time=3600,
|
|
346
|
+
max_instances=1,
|
|
347
|
+
)
|
|
348
|
+
|
|
349
|
+
if not self.scheduler.get_job(MISSED_PATROL_JOB_ID):
|
|
350
|
+
self.scheduler.add_job(
|
|
351
|
+
id=MISSED_PATROL_JOB_ID,
|
|
352
|
+
name=MISSED_PATROL_JOB_ID,
|
|
353
|
+
func=run_missed_patrol,
|
|
354
|
+
trigger=CronTrigger(minute=10),
|
|
355
|
+
coalesce=True,
|
|
356
|
+
misfire_grace_time=600,
|
|
357
|
+
max_instances=1,
|
|
358
|
+
)
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
orchestrator = _Orchestrator()
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def run_pipeline_now(
|
|
365
|
+
pipeline: Pipeline,
|
|
366
|
+
trigger: Optional[Trigger] = None,
|
|
367
|
+
params: Optional[dict] = None,
|
|
368
|
+
reason: str = "api",
|
|
369
|
+
source_run_id: Optional[int] = None,
|
|
370
|
+
resume_from: Optional[str] = None,
|
|
371
|
+
) -> PipelineRun:
|
|
372
|
+
"""模块级便捷封装(plombery 兼容),委托给 orchestrator 单例。"""
|
|
373
|
+
return orchestrator.run_pipeline_now(
|
|
374
|
+
pipeline, trigger, params, reason, source_run_id, resume_from
|
|
375
|
+
)
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
def cancel_run(run_id: int) -> bool:
|
|
379
|
+
"""模块级便捷封装:请求停止正在执行的 run,委托给 orchestrator 单例。"""
|
|
380
|
+
return orchestrator.cancel_run(run_id)
|