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,412 @@
|
|
|
1
|
+
"""通知引擎:规则来源 DB、事件匹配与异步投递、missed 巡检。
|
|
2
|
+
|
|
3
|
+
emit 全部 fire-and-forget:内部 spawn asyncio task,任何失败只记 warning,
|
|
4
|
+
绝不影响主流程。
|
|
5
|
+
|
|
6
|
+
防环说明:本模块被 executor/orchestrator 引用,反向 import
|
|
7
|
+
flowdeck.config / flowdeck.database 必须延迟到函数内;
|
|
8
|
+
``run_missed_patrol`` 对 orchestrator 同样函数内延迟 import,
|
|
9
|
+
确保 ``import flowdeck`` 及任意子模块导入无环。
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import asyncio
|
|
13
|
+
import json
|
|
14
|
+
import logging
|
|
15
|
+
import re
|
|
16
|
+
import threading
|
|
17
|
+
from datetime import datetime, timedelta
|
|
18
|
+
from typing import Any, Coroutine, Dict, List
|
|
19
|
+
|
|
20
|
+
import httpx
|
|
21
|
+
|
|
22
|
+
from flowdeck.notifications.rules import NotificationRuleSchema
|
|
23
|
+
from flowdeck.notifications.templates import render_email, render_payload
|
|
24
|
+
|
|
25
|
+
_logger = logging.getLogger(__name__)
|
|
26
|
+
|
|
27
|
+
# 回看窗口 65 分钟(> 1 小时),容忍巡检 job 本身几分钟的延迟
|
|
28
|
+
MISSED_PATROL_WINDOW_MINUTES = 65
|
|
29
|
+
_MAX_EXPECTED_FIRES = 10_000
|
|
30
|
+
|
|
31
|
+
# 保持 fire-and-forget task 的强引用,防止 task 被 GC 中途消失
|
|
32
|
+
_pending_tasks: set = set()
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _spawn(coro: Coroutine) -> None:
|
|
36
|
+
"""安全地 create_task;无运行中的事件循环时丢弃并记日志。"""
|
|
37
|
+
try:
|
|
38
|
+
task = asyncio.create_task(coro)
|
|
39
|
+
except RuntimeError:
|
|
40
|
+
_logger.warning("No running event loop, notification dropped")
|
|
41
|
+
coro.close()
|
|
42
|
+
return
|
|
43
|
+
|
|
44
|
+
_pending_tasks.add(task)
|
|
45
|
+
task.add_done_callback(_pending_tasks.discard)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
async def _send(webhook_url: str, payload: Dict[str, Any]) -> None:
|
|
49
|
+
"""POST 到 webhook;任何异常只记 warning。"""
|
|
50
|
+
try:
|
|
51
|
+
async with httpx.AsyncClient() as client:
|
|
52
|
+
response = await client.post(webhook_url, json=payload, timeout=10)
|
|
53
|
+
if response.status_code >= 300:
|
|
54
|
+
_logger.warning(
|
|
55
|
+
"Notification webhook %s returned HTTP %s",
|
|
56
|
+
webhook_url,
|
|
57
|
+
response.status_code,
|
|
58
|
+
)
|
|
59
|
+
except Exception:
|
|
60
|
+
_logger.warning("Failed to send notification to %s", webhook_url, exc_info=True)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
async def _send_many(webhook_url: str, payloads: list) -> None:
|
|
64
|
+
"""按顺序逐条投递(图片需先于正文到达,避免「见上图」出现在图之前)。"""
|
|
65
|
+
async with httpx.AsyncClient() as client:
|
|
66
|
+
for payload in payloads:
|
|
67
|
+
try:
|
|
68
|
+
response = await client.post(webhook_url, json=payload, timeout=10)
|
|
69
|
+
if response.status_code >= 300:
|
|
70
|
+
_logger.warning(
|
|
71
|
+
"Notification webhook %s returned HTTP %s",
|
|
72
|
+
webhook_url,
|
|
73
|
+
response.status_code,
|
|
74
|
+
)
|
|
75
|
+
except Exception:
|
|
76
|
+
_logger.warning(
|
|
77
|
+
"Failed to send notification to %s", webhook_url, exc_info=True
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def send_webhook(webhook_url: str, payload: Dict[str, Any]) -> None:
|
|
82
|
+
"""fire-and-forget 投递单条 webhook(任务结果直发等场景复用,失败只记 warning)。
|
|
83
|
+
|
|
84
|
+
有运行中的事件循环(正常调度)时走 create_task;无循环的同步上下文
|
|
85
|
+
(脚本 / 测试 / CLI)退化为后台线程自建 loop,仍然不阻塞调用方。
|
|
86
|
+
"""
|
|
87
|
+
|
|
88
|
+
def _run_in_thread() -> None:
|
|
89
|
+
asyncio.run(_send(webhook_url, payload))
|
|
90
|
+
|
|
91
|
+
try:
|
|
92
|
+
asyncio.get_running_loop()
|
|
93
|
+
except RuntimeError:
|
|
94
|
+
threading.Thread(target=_run_in_thread, daemon=True).start()
|
|
95
|
+
return
|
|
96
|
+
_spawn(_send(webhook_url, payload))
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def send_webhooks(webhook_url: str, payloads: list) -> None:
|
|
100
|
+
"""fire-and-forget 投递多条 webhook,保证发送顺序(图片在前、正文在后)。"""
|
|
101
|
+
payloads = [item for item in payloads if item]
|
|
102
|
+
if not payloads:
|
|
103
|
+
return
|
|
104
|
+
|
|
105
|
+
def _run_in_thread() -> None:
|
|
106
|
+
asyncio.run(_send_many(webhook_url, payloads))
|
|
107
|
+
|
|
108
|
+
try:
|
|
109
|
+
asyncio.get_running_loop()
|
|
110
|
+
except RuntimeError:
|
|
111
|
+
threading.Thread(target=_run_in_thread, daemon=True).start()
|
|
112
|
+
return
|
|
113
|
+
_spawn(_send_many(webhook_url, payloads))
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _row_to_schema(row) -> NotificationRuleSchema:
|
|
117
|
+
"""DB 规则行 → NotificationRuleSchema(解析失败抛异常由调用方处理)。"""
|
|
118
|
+
events = json.loads(row.events) if row.events else []
|
|
119
|
+
mentioned_list = json.loads(row.mentioned_list) if row.mentioned_list else []
|
|
120
|
+
recipients = json.loads(row.recipients) if getattr(row, "recipients", None) else []
|
|
121
|
+
return NotificationRuleSchema(
|
|
122
|
+
name=row.name,
|
|
123
|
+
events=events,
|
|
124
|
+
pipeline_pattern=row.pipeline_pattern or "",
|
|
125
|
+
webhook_url=row.webhook_url or "",
|
|
126
|
+
template=row.template or "json",
|
|
127
|
+
mentioned_list=mentioned_list,
|
|
128
|
+
channel=getattr(row, "channel", None) or "webhook",
|
|
129
|
+
recipients=recipients,
|
|
130
|
+
enabled=row.enabled,
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
async def _dispatch_email(rule: NotificationRuleSchema, event: str, context: dict) -> None:
|
|
135
|
+
"""email 渠道投递:SMTP 未配置时跳过并记 warning(配置门控)。"""
|
|
136
|
+
from flowdeck.database import repository
|
|
137
|
+
from flowdeck.notifications.email_sender import send_email
|
|
138
|
+
|
|
139
|
+
cfg = repository.get_smtp_config()
|
|
140
|
+
if cfg is None:
|
|
141
|
+
_logger.warning(
|
|
142
|
+
"Email notification channel is not enabled (configure SMTP in "
|
|
143
|
+
"settings); rule %s skipped",
|
|
144
|
+
rule.name,
|
|
145
|
+
)
|
|
146
|
+
return
|
|
147
|
+
|
|
148
|
+
recipients = [r for r in (rule.recipients or []) if r]
|
|
149
|
+
if not recipients:
|
|
150
|
+
_logger.warning("Email rule %s has no recipients, skipped", rule.name)
|
|
151
|
+
return
|
|
152
|
+
|
|
153
|
+
subject, body = render_email(rule, event, context)
|
|
154
|
+
await send_email(cfg, recipients, subject, body)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _db_rules() -> List[NotificationRuleSchema]:
|
|
158
|
+
"""DB 规则 → NotificationRuleSchema(坏行跳过并记日志)。"""
|
|
159
|
+
from flowdeck.database import repository
|
|
160
|
+
|
|
161
|
+
rules: List[NotificationRuleSchema] = []
|
|
162
|
+
for row in repository.list_rules_db():
|
|
163
|
+
try:
|
|
164
|
+
rules.append(_row_to_schema(row))
|
|
165
|
+
except Exception:
|
|
166
|
+
_logger.warning(
|
|
167
|
+
"Skipping invalid notification rule %s (%s)",
|
|
168
|
+
row.id,
|
|
169
|
+
row.name,
|
|
170
|
+
exc_info=True,
|
|
171
|
+
)
|
|
172
|
+
return rules
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
class RuleManager:
|
|
176
|
+
"""规则来源:repository DB 规则(UI/API 创建,即时生效)。"""
|
|
177
|
+
|
|
178
|
+
def list_rules(self) -> List[Dict[str, Any]]:
|
|
179
|
+
"""DB 规则列表(dict 形式,含 id/source 供 UI/API 使用)。"""
|
|
180
|
+
from flowdeck.database import repository
|
|
181
|
+
|
|
182
|
+
rules: List[Dict[str, Any]] = []
|
|
183
|
+
|
|
184
|
+
for row in repository.list_rules_db():
|
|
185
|
+
try:
|
|
186
|
+
rule = _row_to_schema(row)
|
|
187
|
+
except Exception:
|
|
188
|
+
_logger.warning(
|
|
189
|
+
"Skipping invalid notification rule %s (%s)",
|
|
190
|
+
row.id,
|
|
191
|
+
row.name,
|
|
192
|
+
exc_info=True,
|
|
193
|
+
)
|
|
194
|
+
continue
|
|
195
|
+
|
|
196
|
+
rules.append(
|
|
197
|
+
{**rule.model_dump(), "id": row.id, "source": row.source or "ui"}
|
|
198
|
+
)
|
|
199
|
+
|
|
200
|
+
return rules
|
|
201
|
+
|
|
202
|
+
def _matching_rules(self, event: str, pipeline_id: str) -> List[NotificationRuleSchema]:
|
|
203
|
+
"""enabled 且 events 命中且 pipeline_pattern 正则 fullmatch(空串匹配全部)。"""
|
|
204
|
+
candidates: List[NotificationRuleSchema] = _db_rules()
|
|
205
|
+
|
|
206
|
+
matched: List[NotificationRuleSchema] = []
|
|
207
|
+
for rule in candidates:
|
|
208
|
+
if not rule.enabled:
|
|
209
|
+
continue
|
|
210
|
+
if event not in rule.events:
|
|
211
|
+
continue
|
|
212
|
+
|
|
213
|
+
pattern = rule.pipeline_pattern or ""
|
|
214
|
+
if pattern:
|
|
215
|
+
try:
|
|
216
|
+
if not re.fullmatch(pattern, pipeline_id):
|
|
217
|
+
continue
|
|
218
|
+
except re.error:
|
|
219
|
+
_logger.warning(
|
|
220
|
+
"Invalid pipeline_pattern %r in rule %s, skipped",
|
|
221
|
+
pattern,
|
|
222
|
+
rule.name,
|
|
223
|
+
)
|
|
224
|
+
continue
|
|
225
|
+
|
|
226
|
+
matched.append(rule)
|
|
227
|
+
|
|
228
|
+
return matched
|
|
229
|
+
|
|
230
|
+
# ------------------------------------------------------------------
|
|
231
|
+
# 事件入口
|
|
232
|
+
# ------------------------------------------------------------------
|
|
233
|
+
|
|
234
|
+
def emit_run_event(self, event: str, run, pipeline, trigger=None) -> None:
|
|
235
|
+
"""run 结束事件(succeeded/failed/timeout/skipped),异步分发到匹配规则。
|
|
236
|
+
|
|
237
|
+
通知内容附带该次运行的详情链接:基地址取 DB 设置项 base_url,
|
|
238
|
+
未配置时 run_url 退化为相对路径(由模板显式提示,不生成错误链接)。
|
|
239
|
+
失败/超时事件额外定位首个失败任务。
|
|
240
|
+
"""
|
|
241
|
+
from flowdeck.database import repository
|
|
242
|
+
|
|
243
|
+
context = {
|
|
244
|
+
"pipeline_id": run.pipeline_id,
|
|
245
|
+
"pipeline_name": pipeline.name if pipeline is not None else None,
|
|
246
|
+
"trigger_id": run.trigger_id,
|
|
247
|
+
"trigger_name": trigger.name if trigger is not None else None,
|
|
248
|
+
"run_id": run.id,
|
|
249
|
+
"status": run.status,
|
|
250
|
+
"start_time": run.start_time,
|
|
251
|
+
"duration_seconds": run.duration,
|
|
252
|
+
"error": run.error,
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
if run.id is not None:
|
|
256
|
+
base_url = repository.get_effective_base_url()
|
|
257
|
+
context["base_url"] = base_url
|
|
258
|
+
context["run_url"] = (
|
|
259
|
+
f"{base_url}/runs/{run.id}" if base_url else f"/runs/{run.id}"
|
|
260
|
+
)
|
|
261
|
+
|
|
262
|
+
if event in ("failed", "timeout"):
|
|
263
|
+
try:
|
|
264
|
+
failed_task = repository.get_first_failed_task(run.id)
|
|
265
|
+
except Exception:
|
|
266
|
+
failed_task = None
|
|
267
|
+
if failed_task is not None:
|
|
268
|
+
context["failed_task_id"] = failed_task.task_id
|
|
269
|
+
context["failed_task_error"] = failed_task.error
|
|
270
|
+
|
|
271
|
+
self._emit(event, context)
|
|
272
|
+
|
|
273
|
+
def emit_custom(self, event: str, context: dict) -> None:
|
|
274
|
+
"""自定义事件(missed 巡检等,run 可能为 None)。"""
|
|
275
|
+
context = dict(context)
|
|
276
|
+
context.setdefault("status", event)
|
|
277
|
+
self._emit(event, context)
|
|
278
|
+
|
|
279
|
+
def _emit(self, event: str, context: dict) -> None:
|
|
280
|
+
try:
|
|
281
|
+
rules = self._matching_rules(event, context.get("pipeline_id") or "")
|
|
282
|
+
except Exception:
|
|
283
|
+
_logger.warning("Failed to match notification rules", exc_info=True)
|
|
284
|
+
return
|
|
285
|
+
|
|
286
|
+
for rule in rules:
|
|
287
|
+
try:
|
|
288
|
+
if rule.channel == "email":
|
|
289
|
+
_spawn(_dispatch_email(rule, event, context))
|
|
290
|
+
continue
|
|
291
|
+
|
|
292
|
+
payload = render_payload(rule, event, context)
|
|
293
|
+
except Exception:
|
|
294
|
+
_logger.warning(
|
|
295
|
+
"Failed to render notification payload for rule %s",
|
|
296
|
+
rule.name,
|
|
297
|
+
exc_info=True,
|
|
298
|
+
)
|
|
299
|
+
continue
|
|
300
|
+
|
|
301
|
+
_spawn(_send(rule.webhook_url, payload))
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def _count_expected_fires(schedule, window_start: datetime, now: datetime) -> int:
|
|
305
|
+
"""迭代 trigger 的 get_next_fire_time,统计 (window_start, now] 内预期触发次数。
|
|
306
|
+
|
|
307
|
+
APScheduler trigger 返回带本地时区的 aware datetime,
|
|
308
|
+
window_start / now 也必须是 aware(本地时区)。
|
|
309
|
+
"""
|
|
310
|
+
count = 0
|
|
311
|
+
fire_time = schedule.get_next_fire_time(None, window_start)
|
|
312
|
+
|
|
313
|
+
while fire_time is not None and fire_time <= now and count < _MAX_EXPECTED_FIRES:
|
|
314
|
+
count += 1
|
|
315
|
+
fire_time = schedule.get_next_fire_time(fire_time, fire_time)
|
|
316
|
+
|
|
317
|
+
return count
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
async def run_missed_patrol() -> None:
|
|
321
|
+
"""每小时(minute=10)巡检:每个活跃 trigger,回看 65 分钟窗口
|
|
322
|
+
(起点不早于该 trigger 首次 run 时间),窗口内预期有触发却没有任何
|
|
323
|
+
run 记录(含 SKIPPED)→ emit missed 事件。
|
|
324
|
+
|
|
325
|
+
判定用「零记录」而非次数对比,原因:
|
|
326
|
+
- 新注册 pipeline 的窗口会覆盖其注册前的时间段(次数对比必误报);
|
|
327
|
+
- 调度器 coalesce=True 会把密集触发合并为一次执行(次数对比必误报);
|
|
328
|
+
- 暂停/禁用期间的触发会留 SKIPPED 记录,视为已处理不算漏跑。
|
|
329
|
+
「窗口内零记录」只抓真正的漏跑(服务宕机、进程被杀等)。
|
|
330
|
+
"""
|
|
331
|
+
from flowdeck.database import repository
|
|
332
|
+
from flowdeck.orchestrator import orchestrator
|
|
333
|
+
|
|
334
|
+
try:
|
|
335
|
+
now_naive = datetime.now()
|
|
336
|
+
window_start_naive = now_naive - timedelta(
|
|
337
|
+
minutes=MISSED_PATROL_WINDOW_MINUTES
|
|
338
|
+
)
|
|
339
|
+
now_aware = now_naive.astimezone()
|
|
340
|
+
window_start_aware = window_start_naive.astimezone()
|
|
341
|
+
|
|
342
|
+
for job_id, (pipeline, trigger) in list(orchestrator._all_triggers.items()):
|
|
343
|
+
try:
|
|
344
|
+
if trigger.paused:
|
|
345
|
+
# 代码级暂停:从未进调度器,不参与巡检
|
|
346
|
+
continue
|
|
347
|
+
if repository.is_pipeline_paused(pipeline.id):
|
|
348
|
+
continue
|
|
349
|
+
if repository.is_trigger_disabled(pipeline.id, trigger.id):
|
|
350
|
+
continue
|
|
351
|
+
|
|
352
|
+
first_run = repository.first_run_time(pipeline.id, trigger.id)
|
|
353
|
+
if first_run is None:
|
|
354
|
+
# 该 trigger 从未有 run 记录(新注册/从未触发):没有历史
|
|
355
|
+
# 基线可比对,跳过本次巡检,避免新任务首个巡检周期误报
|
|
356
|
+
continue
|
|
357
|
+
# 窗口起点不早于首次 run 时间:pipeline 注册前的时间段不计入
|
|
358
|
+
effective_start_naive = max(window_start_naive, first_run)
|
|
359
|
+
effective_start_aware = effective_start_naive.astimezone()
|
|
360
|
+
|
|
361
|
+
expected = _count_expected_fires(
|
|
362
|
+
trigger.schedule, effective_start_aware, now_aware
|
|
363
|
+
)
|
|
364
|
+
actual = repository.count_runs_in_window(
|
|
365
|
+
pipeline.id, trigger.id, effective_start_naive, now_naive
|
|
366
|
+
)
|
|
367
|
+
|
|
368
|
+
# 判定条件用「零记录」而非次数对比:coalesce 会把密集触发合并
|
|
369
|
+
# 为一次执行;暂停/禁用期间的触发也留有 SKIPPED 记录。只有预期
|
|
370
|
+
# 有触发却一条记录都没有,才是真正的漏跑(服务宕机等)。
|
|
371
|
+
if expected >= 1 and actual == 0:
|
|
372
|
+
effective_minutes = max(
|
|
373
|
+
1,
|
|
374
|
+
round((now_naive - effective_start_naive).total_seconds() / 60),
|
|
375
|
+
)
|
|
376
|
+
_logger.warning(
|
|
377
|
+
"Missed runs: pipeline=%s trigger=%s expected=%d actual=%d "
|
|
378
|
+
"in window (%s, %s]",
|
|
379
|
+
pipeline.id,
|
|
380
|
+
trigger.id,
|
|
381
|
+
expected,
|
|
382
|
+
actual,
|
|
383
|
+
effective_start_naive,
|
|
384
|
+
now_naive,
|
|
385
|
+
)
|
|
386
|
+
notification_manager.emit_custom(
|
|
387
|
+
"missed",
|
|
388
|
+
{
|
|
389
|
+
"pipeline_id": pipeline.id,
|
|
390
|
+
"pipeline_name": pipeline.name,
|
|
391
|
+
"trigger_id": trigger.id,
|
|
392
|
+
"trigger_name": trigger.name,
|
|
393
|
+
"expected_count": expected,
|
|
394
|
+
"actual_count": actual,
|
|
395
|
+
"window_start": effective_start_naive.strftime(
|
|
396
|
+
"%Y-%m-%d %H:%M:%S"
|
|
397
|
+
),
|
|
398
|
+
"window_end": now_naive.strftime("%Y-%m-%d %H:%M:%S"),
|
|
399
|
+
"status": "missed",
|
|
400
|
+
"detail": (
|
|
401
|
+
f"过去 {effective_minutes} 分钟窗口内"
|
|
402
|
+
f"预期运行 {expected} 次,实际 {actual} 次"
|
|
403
|
+
),
|
|
404
|
+
},
|
|
405
|
+
)
|
|
406
|
+
except Exception:
|
|
407
|
+
_logger.warning("Missed patrol failed for %s", job_id, exc_info=True)
|
|
408
|
+
except Exception:
|
|
409
|
+
_logger.error("Missed patrol job failed", exc_info=True)
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
notification_manager = RuleManager()
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
from typing import List, Literal
|
|
2
|
+
|
|
3
|
+
from pydantic import BaseModel
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class NotificationRuleSchema(BaseModel):
|
|
7
|
+
"""通知规则(yaml 配置与 UI 共用的 schema)。"""
|
|
8
|
+
|
|
9
|
+
name: str
|
|
10
|
+
events: List[Literal["failed", "succeeded", "timeout", "missed", "skipped", "alert"]]
|
|
11
|
+
pipeline_pattern: str = ""
|
|
12
|
+
"""pipeline id 的正则匹配,空字符串匹配全部"""
|
|
13
|
+
webhook_url: str = ""
|
|
14
|
+
template: Literal["json", "wecom_text", "wecom_markdown"] = "json"
|
|
15
|
+
mentioned_list: List[str] = []
|
|
16
|
+
"""@ 提醒的成员 userid 列表(仅 wecom 模板生效;text 用 mentioned_list,
|
|
17
|
+
markdown 用 <@userid> 语法)"""
|
|
18
|
+
channel: Literal["webhook", "email"] = "webhook"
|
|
19
|
+
"""投递渠道:webhook(企微等通用 webhook)/ email(需在设置页启用 SMTP)"""
|
|
20
|
+
recipients: List[str] = []
|
|
21
|
+
"""email 渠道的收件人地址列表(webhook 渠道忽略)"""
|
|
22
|
+
enabled: bool = True
|