更新文件说明
This commit is contained in:
@@ -61,3 +61,5 @@ COLLECTOR_SCRIPT = os.getenv("HOTEL_COLLECTOR_SCRIPT", "酒店详情.py")
|
||||
COLLECTOR_PYTHON = os.getenv("HOTEL_COLLECTOR_PYTHON") or sys.executable
|
||||
COLLECTOR_PID_FILE = COLLECTOR_DIR / "logs" / "collector.pid"
|
||||
COLLECTOR_LOG_FILE = COLLECTOR_DIR / "logs" / "collector.out.log"
|
||||
# 采集脚本自己写的状态文件(最近一次退出原因:城市 / 平台返回 / 异常)
|
||||
COLLECTOR_STATE_FILE = COLLECTOR_DIR / "logs" / "collector_state.json"
|
||||
|
||||
@@ -9,7 +9,9 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
@@ -21,8 +23,12 @@ from ..config import (
|
||||
COLLECTOR_PID_FILE,
|
||||
COLLECTOR_PYTHON,
|
||||
COLLECTOR_SCRIPT,
|
||||
COLLECTOR_STATE_FILE,
|
||||
)
|
||||
|
||||
# 运行中超过这么久没有日志输出,判定为“疑似卡住”(典型是代理不回包)
|
||||
STALL_SECONDS = 180
|
||||
|
||||
# Windows 进程创建标志
|
||||
CREATE_NEW_PROCESS_GROUP = 0x00000200
|
||||
CREATE_NO_WINDOW = 0x08000000
|
||||
@@ -65,6 +71,39 @@ def _pid_alive(pid: int | None) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def read_state() -> dict:
|
||||
"""读采集脚本写的状态文件(最近一次启动/退出原因)。读不到返回空 dict。"""
|
||||
try:
|
||||
data = json.loads(COLLECTOR_STATE_FILE.read_text(encoding="utf-8"))
|
||||
return data if isinstance(data, dict) else {}
|
||||
except (OSError, ValueError):
|
||||
return {}
|
||||
|
||||
|
||||
def _mark_user_stop() -> None:
|
||||
"""看板点「停止」时进程是被 taskkill 的,脚本来不及写 state —— 这里补一条,
|
||||
否则页面上会一直挂着上一次崩溃的原因。"""
|
||||
state = read_state()
|
||||
now = datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
|
||||
state["last_exit"] = {
|
||||
"at": now,
|
||||
"reason": "stopped_by_user",
|
||||
"city": None,
|
||||
"city_name": None,
|
||||
"hd_id": None,
|
||||
"package_cities": None,
|
||||
"error": None,
|
||||
"platform_response": None,
|
||||
"traceback": None,
|
||||
}
|
||||
state["updated_at"] = now
|
||||
try:
|
||||
COLLECTOR_STATE_FILE.parent.mkdir(parents=True, exist_ok=True)
|
||||
COLLECTOR_STATE_FILE.write_text(json.dumps(state, ensure_ascii=False), encoding="utf-8")
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def read_pid() -> int | None:
|
||||
"""读 collector.pid(不存在 / 内容非法都返回 None)。"""
|
||||
try:
|
||||
@@ -93,27 +132,62 @@ def current_pid() -> int | None:
|
||||
return None
|
||||
|
||||
|
||||
def tail(lines: int = 12) -> list[str]:
|
||||
_ANSI = re.compile(r"\x1b\[[0-9;]*m")
|
||||
|
||||
|
||||
def tail(lines: int = 12, max_chars: int = 300) -> list[str]:
|
||||
"""只读日志末尾 128KB(日志可能几百 MB,不能整个读进内存),并去掉 ANSI 颜色码。"""
|
||||
try:
|
||||
with COLLECTOR_LOG_FILE.open("r", encoding="utf-8", errors="replace") as f:
|
||||
return [ln.rstrip() for ln in f.readlines()[-lines:]]
|
||||
size = COLLECTOR_LOG_FILE.stat().st_size
|
||||
with COLLECTOR_LOG_FILE.open("rb") as f:
|
||||
chunk = min(size, 128 * 1024)
|
||||
f.seek(size - chunk)
|
||||
data = f.read(chunk)
|
||||
text = data.decode("utf-8", errors="replace")
|
||||
out: list[str] = []
|
||||
for line in text.splitlines()[-lines:]:
|
||||
s = _ANSI.sub("", line).strip()
|
||||
if len(s) > max_chars:
|
||||
s = s[:max_chars] + "…"
|
||||
out.append(s)
|
||||
return out
|
||||
except OSError:
|
||||
return []
|
||||
|
||||
|
||||
def _state_started_at(state: dict) -> float | None:
|
||||
raw = state.get("started_at")
|
||||
if not raw:
|
||||
return None
|
||||
try:
|
||||
return time.mktime(time.strptime(str(raw), "%Y-%m-%dT%H:%M:%S"))
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def status() -> dict:
|
||||
pid = current_pid()
|
||||
state = read_state()
|
||||
started: float | None = None
|
||||
if pid:
|
||||
if _proc is not None and _proc.pid == pid and _proc.poll() is None:
|
||||
started = _started_at
|
||||
else:
|
||||
if started is None:
|
||||
started = _state_started_at(state) # 控制台手动起的,脚本自己写了启动时间
|
||||
if started is None:
|
||||
try:
|
||||
started = COLLECTOR_PID_FILE.stat().st_mtime
|
||||
except OSError:
|
||||
started = None
|
||||
|
||||
try:
|
||||
log_age = int(time.time() - COLLECTOR_LOG_FILE.stat().st_mtime)
|
||||
except OSError:
|
||||
log_age = None
|
||||
|
||||
running = bool(pid)
|
||||
return {
|
||||
"running": bool(pid),
|
||||
"running": running,
|
||||
"pid": pid,
|
||||
"source": "api" if (pid and _proc is not None and _proc.pid == pid) else ("manual" if pid else None),
|
||||
"started_at": datetime.fromtimestamp(started).strftime("%Y-%m-%d %H:%M:%S") if started else None,
|
||||
@@ -123,6 +197,12 @@ def status() -> dict:
|
||||
"python": COLLECTOR_PYTHON,
|
||||
"log_file": str(COLLECTOR_LOG_FILE),
|
||||
"log_tail": tail(),
|
||||
# 诊断:最近一次启动/退出原因(脚本自己写 collector_state.json)
|
||||
"state_updated_at": state.get("updated_at"),
|
||||
"last_exit": state.get("last_exit"),
|
||||
# 卡死判定:还在跑,但日志已经 STALL_SECONDS 秒没动静
|
||||
"log_age_seconds": log_age,
|
||||
"stalled": bool(running and log_age is not None and log_age > STALL_SECONDS),
|
||||
}
|
||||
|
||||
|
||||
@@ -217,4 +297,5 @@ def stop() -> dict:
|
||||
COLLECTOR_PID_FILE.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
_mark_user_stop()
|
||||
return status()
|
||||
|
||||
@@ -412,6 +412,23 @@ audit_write({..., "new_is_ok": None})
|
||||
启动后等 2 秒,脚本若立刻退出(import 报错等)直接返回 500 + 日志尾。
|
||||
- 配置项:`HOTEL_COLLECTOR_DIR` / `HOTEL_COLLECTOR_SCRIPT` / `HOTEL_COLLECTOR_PYTHON`(默认取项目根、`酒店详情.py`、当前解释器)。
|
||||
|
||||
**诊断字段(采集为什么停了 / 卡在哪)**
|
||||
|
||||
采集脚本会把最近一次启动/退出写进 `logs/collector_state.json`,`status` 直接透出:
|
||||
|
||||
```json
|
||||
{"state_updated_at":"2026-10-27T13:40:00",
|
||||
"last_exit":{"at":"2026-10-27T13:40:00","reason":"no_matching_package","city":"合肥",
|
||||
"city_name":"合肥市","hd_id":null,"package_cities":["青岛"],
|
||||
"error":"IndexError: list index out of range",
|
||||
"platform_response":"{\"code\":0,...}","traceback":"Traceback ..."},
|
||||
"log_age_seconds":433,"stalled":false}
|
||||
```
|
||||
|
||||
- `reason`:`no_matching_package`(任务城市没有匹配的包)/ `platform_returned_error`(平台返回里没有 data)/ `exception`(其它异常)/ `stopped_by_user`(手动停止);
|
||||
- `stalled`:还在跑但日志超过 180 秒没动 → 疑似卡死(典型是代理不回包);
|
||||
- 前端顶栏下方据此显示红色"采集已自动停止"或黄色"疑似卡住"提示条,点「详情」看城市、平台返回、日志尾。
|
||||
|
||||
### 4.17 `GET /api/hotel/stats/failures?date=`
|
||||
|
||||
当天"拿任务失败"(埋点 `fetch_empty`)的城市清单,供**改/加城市的下拉框过滤**:
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
<script setup lang="ts">
|
||||
/** 应用外壳:顶栏 + 两页切换(账号池 / 查询)+ 自动刷新(不再展示健康度条) */
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { storeToRefs } from 'pinia'
|
||||
import FilterBar from './components/FilterBar.vue'
|
||||
import NavTabs, { type NavKey } from './components/NavTabs.vue'
|
||||
import AccountsView from './views/AccountsView.vue'
|
||||
import QueryView from './views/QueryView.vue'
|
||||
import api from './api'
|
||||
import type { CollectorStatus } from './api/types'
|
||||
import { useAutoRefresh } from './composables/useAutoRefresh'
|
||||
import { useHotelStore } from './stores/hotel'
|
||||
|
||||
@@ -36,15 +37,65 @@ async function pingBackend() {
|
||||
|
||||
watch(tick, pingBackend)
|
||||
|
||||
// ── 采集状态:停了/卡住了要能立刻看出“哪个城市、平台回了什么” ──
|
||||
const collector = ref<CollectorStatus | null>(null)
|
||||
const detailOpen = ref(false)
|
||||
let collectorTimer: number | null = null
|
||||
|
||||
const REASON_TEXT: Record<string, string> = {
|
||||
no_matching_package: '任务城市没有匹配的包',
|
||||
platform_returned_error: '平台返回错误(没有 data 字段)',
|
||||
exception: '运行异常',
|
||||
stopped_by_user: '手动停止',
|
||||
}
|
||||
|
||||
async function loadCollector() {
|
||||
try {
|
||||
collector.value = await api.collectorStatus()
|
||||
} catch {
|
||||
collector.value = null
|
||||
}
|
||||
}
|
||||
|
||||
const exitDetail = computed(() => collector.value?.last_exit ?? null)
|
||||
|
||||
const collectorAlert = computed(() => {
|
||||
const s = collector.value
|
||||
if (!s) return null
|
||||
if (s.running && s.stalled) {
|
||||
const mins = Math.max(1, Math.round((s.log_age_seconds ?? 0) / 60))
|
||||
return {
|
||||
tone: 'warn',
|
||||
title: '采集疑似卡住',
|
||||
text: `已经 ${mins} 分钟没有日志输出(多半是代理不回包)· pid ${s.pid}`,
|
||||
}
|
||||
}
|
||||
if (!s.running && s.last_exit && s.last_exit.reason !== 'stopped_by_user') {
|
||||
const e = s.last_exit
|
||||
const city = e.city ? `城市 ${e.city}` : '城市未记录'
|
||||
const reason = REASON_TEXT[e.reason] || e.reason
|
||||
return { tone: 'danger', title: '采集已自动停止', text: `${e.at} · ${city} · ${reason}` }
|
||||
}
|
||||
return null
|
||||
})
|
||||
|
||||
onMounted(async () => {
|
||||
await store.loadMeta()
|
||||
await pingBackend()
|
||||
await loadCollector()
|
||||
collectorTimer = window.setInterval(() => {
|
||||
if (!document.hidden) void loadCollector()
|
||||
}, 10000)
|
||||
|
||||
const mq = window.matchMedia('(prefers-reduced-motion: reduce)')
|
||||
const apply = () => document.documentElement.classList.toggle('reduced-motion', mq.matches)
|
||||
apply()
|
||||
mq.addEventListener('change', apply)
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (collectorTimer !== null) window.clearInterval(collectorTimer)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -57,11 +108,65 @@ onMounted(async () => {
|
||||
|
||||
<div v-if="bootError" class="app__error">{{ bootError }}</div>
|
||||
|
||||
<div
|
||||
v-if="collectorAlert"
|
||||
class="app__notice"
|
||||
:class="`app__notice--${collectorAlert.tone}`"
|
||||
role="alert"
|
||||
>
|
||||
<i class="app__notice-dot" />
|
||||
<b class="app__notice-title">{{ collectorAlert.title }}</b>
|
||||
<span class="app__notice-text">{{ collectorAlert.text }}</span>
|
||||
<button class="app__notice-btn" type="button" @click="detailOpen = true">详情</button>
|
||||
</div>
|
||||
|
||||
<main class="app__main">
|
||||
<KeepAlive>
|
||||
<component :is="currentView" :key="activeTab" />
|
||||
</KeepAlive>
|
||||
</main>
|
||||
|
||||
<el-dialog v-model="detailOpen" title="采集停止详情" width="680px" append-to-body>
|
||||
<div v-if="exitDetail" class="diag">
|
||||
<div class="diag__row">
|
||||
<span class="diag__k">时间</span>
|
||||
<span class="diag__v">{{ exitDetail.at }}</span>
|
||||
</div>
|
||||
<div class="diag__row">
|
||||
<span class="diag__k">原因</span>
|
||||
<span class="diag__v">{{ REASON_TEXT[exitDetail.reason] || exitDetail.reason }}</span>
|
||||
</div>
|
||||
<div class="diag__row">
|
||||
<span class="diag__k">城市</span>
|
||||
<span class="diag__v">
|
||||
{{ exitDetail.city || '未记录' }}
|
||||
<template v-if="exitDetail.city_name">(任务城市 {{ exitDetail.city_name }})</template>
|
||||
</span>
|
||||
</div>
|
||||
<div class="diag__row">
|
||||
<span class="diag__k">包</span>
|
||||
<span class="diag__v">
|
||||
{{ exitDetail.hd_id ?? '—' }}
|
||||
<template v-if="exitDetail.package_cities?.length">
|
||||
· 手上的包城市:{{ exitDetail.package_cities.join('、') }}
|
||||
</template>
|
||||
</span>
|
||||
</div>
|
||||
<div v-if="exitDetail.error" class="diag__row">
|
||||
<span class="diag__k">报错</span>
|
||||
<span class="diag__v diag__v--err">{{ exitDetail.error }}</span>
|
||||
</div>
|
||||
<div v-if="exitDetail.platform_response" class="diag__block">
|
||||
<div class="diag__label">平台返回</div>
|
||||
<pre class="diag__pre">{{ exitDetail.platform_response }}</pre>
|
||||
</div>
|
||||
<div class="diag__block">
|
||||
<div class="diag__label">日志最后 10 行</div>
|
||||
<pre class="diag__pre">{{ (collector?.log_tail ?? []).slice(-10).join('\n') || '(暂无)' }}</pre>
|
||||
</div>
|
||||
</div>
|
||||
<div v-else class="diag__empty">没有记录到退出原因(可能是正常停止或状态文件缺失)</div>
|
||||
</el-dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -91,4 +196,106 @@ onMounted(async () => {
|
||||
border: 1px solid var(--accent);
|
||||
border-radius: var(--radius-element);
|
||||
}
|
||||
|
||||
/* ── 采集状态提示条 ── */
|
||||
.app__notice {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
max-width: 1400px;
|
||||
width: calc(100% - 48px);
|
||||
margin: 8px auto 0;
|
||||
padding: 7px 12px;
|
||||
font-size: 13px;
|
||||
border-radius: var(--radius-element);
|
||||
}
|
||||
.app__notice--danger {
|
||||
color: #b3261e;
|
||||
background: rgba(224, 64, 44, 0.1);
|
||||
border: 1px solid var(--accent);
|
||||
}
|
||||
.app__notice--warn {
|
||||
color: #8a5a00;
|
||||
background: rgba(217, 164, 36, 0.14);
|
||||
border: 1px solid rgba(217, 164, 36, 0.6);
|
||||
}
|
||||
.app__notice-dot {
|
||||
flex: none;
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background: currentColor;
|
||||
}
|
||||
.app__notice-title {
|
||||
flex: none;
|
||||
font-weight: 600;
|
||||
}
|
||||
.app__notice-text {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.app__notice-btn {
|
||||
flex: none;
|
||||
margin-left: auto;
|
||||
padding: 2px 10px;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 12px;
|
||||
color: inherit;
|
||||
background: var(--bg-card);
|
||||
border: 1px solid currentColor;
|
||||
border-radius: var(--radius-element);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/* ── 停止详情弹窗 ── */
|
||||
.diag {
|
||||
font-size: 13px;
|
||||
}
|
||||
.diag__row {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
padding: 4px 0;
|
||||
border-bottom: 1px dashed rgba(51, 48, 42, 0.16);
|
||||
}
|
||||
.diag__k {
|
||||
flex: none;
|
||||
width: 64px;
|
||||
color: var(--text-weak);
|
||||
}
|
||||
.diag__v {
|
||||
min-width: 0;
|
||||
color: var(--text-primary);
|
||||
word-break: break-all;
|
||||
}
|
||||
.diag__v--err {
|
||||
color: var(--accent);
|
||||
}
|
||||
.diag__block {
|
||||
margin-top: 12px;
|
||||
}
|
||||
.diag__label {
|
||||
margin-bottom: 4px;
|
||||
color: var(--text-weak);
|
||||
}
|
||||
.diag__pre {
|
||||
max-height: 220px;
|
||||
margin: 0;
|
||||
padding: 8px 10px;
|
||||
overflow: auto;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
color: var(--text-secondary);
|
||||
white-space: pre-wrap;
|
||||
word-break: break-all;
|
||||
background: var(--bg-page);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--radius-element);
|
||||
}
|
||||
.diag__empty {
|
||||
padding: 12px 2px;
|
||||
color: var(--text-weak);
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -327,6 +327,26 @@ export interface CollectorStatus {
|
||||
python: string
|
||||
log_file: string
|
||||
log_tail: string[]
|
||||
/** 采集脚本状态文件最后更新时间 */
|
||||
state_updated_at?: string | null
|
||||
/** 最近一次退出原因(城市 / 平台返回 / 异常),手动停止也会记 */
|
||||
last_exit?: CollectorExit | null
|
||||
/** 日志最后一条距今秒数 */
|
||||
log_age_seconds?: number | null
|
||||
/** 还在跑但日志长时间没动(疑似卡死) */
|
||||
stalled?: boolean
|
||||
}
|
||||
|
||||
export interface CollectorExit {
|
||||
at: string
|
||||
reason: 'no_matching_package' | 'platform_returned_error' | 'exception' | 'stopped_by_user' | string
|
||||
city: string | null
|
||||
city_name: string | null
|
||||
hd_id: number | null
|
||||
package_cities: string[] | null
|
||||
error: string | null
|
||||
platform_response: string | null
|
||||
traceback: string | null
|
||||
}
|
||||
|
||||
/** /api/hotel/stats/failures —— 当天拿任务失败(fetch_empty)的城市 */
|
||||
|
||||
Reference in New Issue
Block a user