天气:后台一键连通自检 + 说清断在网络哪一层
- weather.probe():把一次请求拆成 DNS/TCP/TLS/HTTP 四步计时,返回解析到的 IP、 Key 类型、代理来源与结论。排查时不必再登服务器猜。 - explain_error():ConnectTimeout 不再只丢类名,指出可能走了代理/出网被限, 并区分 ConnectError(DNS)、ReadTimeout(链路慢)。 - 新增 QWEATHER_PROXY(可选,服务器出不了网时指定代理)。 - 管理端 POST /admin/settings/weather/test + 平台设置页「测试连通」按钮。main
parent
96dbdaa714
commit
81a369b845
|
|
@ -17,7 +17,7 @@ from app.models import Device, Firmware, Fortune, PlatformSetting, Region, User,
|
|||
from app.schemas.auth import AdminSettingIn, DeviceOut, OkOut, UserOut, user_out
|
||||
from app.schemas.catalog import FortuneIn, FortuneOut, FortunePatch, RegionIn, RegionPatch, ZodiacIn, ZodiacPatch
|
||||
from app.schemas.firmware import DeviceUpgradeOut, FirmwareOut, FirmwarePatch, RolloutIn, UpgradeIn
|
||||
from app.services import catalog, firmware, redis_store
|
||||
from app.services import catalog, firmware, redis_store, weather
|
||||
|
||||
router = APIRouter(prefix="/admin", tags=["admin"])
|
||||
|
||||
|
|
@ -464,6 +464,16 @@ async def put_setting(body: AdminSettingIn, admin: CurrentAdmin, db: SessionDep)
|
|||
return OkOut(ok=True)
|
||||
|
||||
|
||||
@router.post("/settings/weather/test")
|
||||
async def test_weather(admin: CurrentAdmin, db: SessionDep, city: str | None = None) -> dict:
|
||||
"""一键自检:DNS → TCP → TLS → HTTP 各跑一遍并计时。
|
||||
|
||||
天气取不到时,设备只有一个"暂无数据",人只能登服务器敲命令。把这几步搬到
|
||||
这里,网页上点一下就知道是出网断了、证书被拦,还是 Key/Host 不匹配。
|
||||
"""
|
||||
return await weather.probe(db, city)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ 城市码表
|
||||
@router.get("/regions")
|
||||
async def list_regions(
|
||||
|
|
|
|||
|
|
@ -34,6 +34,10 @@ class Settings(BaseSettings):
|
|||
# 和风:Key 与 Host 都只在服务端;Host 是账号专属域名,缺了会 403 Invalid Host
|
||||
qweather_key: str = ""
|
||||
qweather_host: str = "p52yvqedka.re.qweatherapi.com"
|
||||
# 可选:和风请求走指定代理(服务器本身出不了网时用,如 http://10.0.0.2:3128)。
|
||||
# 留空则跟随 HTTP(S)_PROXY / ALL_PROXY 环境变量——httpx 默认就是这种行为,
|
||||
# 而容器里继承到的失效代理正是"连不上和风"最常见的原因之一。
|
||||
qweather_proxy: str = ""
|
||||
|
||||
session_ttl_seconds: int = 7 * 24 * 3600
|
||||
pair_code_ttl_seconds: int = 600
|
||||
|
|
|
|||
|
|
@ -6,7 +6,14 @@
|
|||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import socket
|
||||
import ssl
|
||||
import sys
|
||||
import time
|
||||
from typing import Any
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import httpx
|
||||
from sqlalchemy import select
|
||||
|
|
@ -50,6 +57,54 @@ async def _conf(db: AsyncSession) -> tuple[str, str]:
|
|||
return key, h
|
||||
|
||||
|
||||
PROXY_ENV_KEYS = ("http_proxy", "https_proxy", "all_proxy", "no_proxy")
|
||||
|
||||
|
||||
def proxy_env() -> dict[str, str]:
|
||||
"""httpx 默认 trust_env=True,会读这几个环境变量。
|
||||
|
||||
容器里常见的是继承了一个早已失效的代理地址(``ALL_PROXY=http://127.0.0.1:7890``),
|
||||
表现和"服务器连不出去"一模一样——都是 TCP 建连超时。诊断时必须把它列出来,
|
||||
否则会一直在服务器防火墙/安全组上找原因。
|
||||
"""
|
||||
return {k: v for k, v in os.environ.items() if k.lower() in PROXY_ENV_KEYS}
|
||||
|
||||
|
||||
def effective_proxy() -> str:
|
||||
"""httpx 实际会用的代理:显式配置 QWEATHER_PROXY 优先,其次环境变量。
|
||||
|
||||
不用 httpx 的内部函数(私有 API 换版本就没了),按大小写各读一遍即可。
|
||||
"""
|
||||
if settings.qweather_proxy.strip():
|
||||
return settings.qweather_proxy.strip()
|
||||
for k in ("https_proxy", "all_proxy", "http_proxy"):
|
||||
v = os.environ.get(k) or os.environ.get(k.upper()) or ""
|
||||
if v.strip():
|
||||
return v.strip()
|
||||
return ""
|
||||
|
||||
|
||||
def explain_error(exc: BaseException, host: str) -> str:
|
||||
"""把 httpx 的异常翻成"下一步该查什么",别只丢个 ConnectTimeout。"""
|
||||
name = exc.__class__.__name__
|
||||
if isinstance(exc, httpx.ConnectTimeout):
|
||||
px = effective_proxy()
|
||||
via = f",当前走代理 {px}" if px else ",未走代理(直连)"
|
||||
return (
|
||||
f"连不上和风 {host}:TCP 建连超时{via}。"
|
||||
"这不是 Key/Host 配错(那会是 401/403),而是服务端到目标的网络不通:"
|
||||
"查服务器/容器出网策略(安全组出站、iptables FORWARD、代理是否失效),"
|
||||
"或用「测试连通」看卡在 DNS 还是 TCP。"
|
||||
)
|
||||
if isinstance(exc, httpx.ConnectError):
|
||||
return f"连不上和风 {host}:{exc}(DNS 解析失败或端口被拒,先看域名能不能解析)"
|
||||
if isinstance(exc, httpx.ReadTimeout):
|
||||
return f"和风 {host} 响应超时:连接通了但迟迟不回数据(链路慢或被中间设备拦截)"
|
||||
if isinstance(exc, httpx.HTTPError):
|
||||
return f"和风 {host} 请求失败:{name} {exc}"
|
||||
return f"和风 {host} 请求失败:{name}"
|
||||
|
||||
|
||||
async def _get(http: httpx.AsyncClient, url: str, params: dict[str, Any], key: str = "") -> dict[str, Any]:
|
||||
# 和风新版:API Key 走 X-QW-Api-Key 头;JWT 走 Authorization: Bearer。
|
||||
# 早期文档里的 ?key= 查询参数对新建项目已不再生效(会返回 401),这里不再用。
|
||||
|
|
@ -121,7 +176,7 @@ async def now(db: AsyncSession, city: str) -> dict[str, Any]:
|
|||
return cached
|
||||
|
||||
key, host = await _conf(db)
|
||||
timeout = httpx.Timeout(8.0, connect=5.0)
|
||||
timeout = httpx.Timeout(8.0, connect=6.0)
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=timeout, headers={"Accept-Encoding": "gzip"}) as http:
|
||||
loc_id, name = await _location_id(http, host, key, city)
|
||||
|
|
@ -140,10 +195,126 @@ async def now(db: AsyncSession, city: str) -> dict[str, Any]:
|
|||
last["cached"] = True
|
||||
last["stale"] = True
|
||||
return last
|
||||
raise WeatherUpstreamError(
|
||||
f"和风请求失败:{exc.__class__.__name__}({host})"
|
||||
) from exc
|
||||
raise WeatherUpstreamError(explain_error(exc, host)) from exc
|
||||
|
||||
payload = _slim(name or city, loc_id, current.get("now") or {}, hourly)
|
||||
await redis_store.set_weather(city, payload)
|
||||
return payload
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- 连通性自检
|
||||
# 设备上只能看到"取不到天气",真要定位就得登服务器敲命令。这个函数把排查搬到
|
||||
# 网页上:DNS → TCP → TLS → HTTP 各跑一遍并计时,断在哪一步一目了然。
|
||||
# 只读、无副作用(不会写天气缓存),后台点多少次都行。
|
||||
|
||||
|
||||
async def _tcp(ip: str, port: int, timeout: float = 6.0) -> float:
|
||||
"""返回建连耗时(秒);失败抛 OSError。用线程池跑,别占事件循环。"""
|
||||
|
||||
def _do() -> float:
|
||||
t0 = time.perf_counter()
|
||||
with socket.create_connection((ip, port), timeout=timeout):
|
||||
return time.perf_counter() - t0
|
||||
|
||||
return await asyncio.to_thread(_do)
|
||||
|
||||
|
||||
async def probe(db: AsyncSession, city: str | None = None) -> dict[str, Any]:
|
||||
city = (city or "").strip() or settings.default_city
|
||||
out: dict[str, Any] = {
|
||||
"ok": False,
|
||||
"city": city,
|
||||
"steps": [],
|
||||
"proxy": effective_proxy(),
|
||||
"proxy_env": proxy_env(),
|
||||
"python": sys.version.split()[0],
|
||||
"httpx": httpx.__version__,
|
||||
}
|
||||
|
||||
def step(name: str, ok: bool, ms: float | None, detail: str) -> None:
|
||||
out["steps"].append({"name": name, "ok": ok, "ms": None if ms is None else round(ms * 1000), "detail": detail})
|
||||
|
||||
try:
|
||||
key, base = await _conf(db)
|
||||
except WeatherNotConfigured as exc:
|
||||
step("config", False, None, str(exc))
|
||||
out["hint"] = "还没配 Key/Host:到和风控制台「设置」复制账号专属 API Host 填进来"
|
||||
return out
|
||||
|
||||
parts = urlsplit(base)
|
||||
host = parts.hostname or ""
|
||||
port = parts.port or (443 if parts.scheme == "https" else 80)
|
||||
kind = "JWT" if key.count(".") == 2 and len(key) > 80 else "API Key"
|
||||
out["host"], out["port"], out["key_kind"] = host, port, kind
|
||||
step("config", True, 0, f"{parts.scheme}://{host}:{port} {kind} {key[:6]}…{key[-4:]}")
|
||||
|
||||
# 1) DNS:解析失败一般是容器没 DNS / 域名写错,与出网无关
|
||||
t0 = time.perf_counter()
|
||||
try:
|
||||
infos = await asyncio.to_thread(socket.getaddrinfo, host, port, type=socket.SOCK_STREAM)
|
||||
ips = sorted({i[4][0] for i in infos})
|
||||
out["resolved"] = ips
|
||||
step("dns", True, time.perf_counter() - t0, " ".join(ips))
|
||||
except OSError as exc:
|
||||
step("dns", False, time.perf_counter() - t0, f"{exc.__class__.__name__}: {exc}")
|
||||
out["hint"] = f"DNS 解析失败:容器里没有可用 DNS,或 Host 写错({host} 解析不到任何 IP)"
|
||||
return out
|
||||
|
||||
# 2) TCP:这一步通过说明网络通,后面出问题都跟 Key/证书有关
|
||||
ip = ips[0]
|
||||
try:
|
||||
ms = await _tcp(ip, port)
|
||||
step("tcp", True, ms, f"{ip}:{port} 建连 {ms * 1000:.0f}ms")
|
||||
except OSError as exc:
|
||||
step("tcp", False, None, f"{ip}:{port} {exc.__class__.__name__}: {exc}")
|
||||
px = out["proxy"]
|
||||
out["hint"] = (
|
||||
f"服务器到 {ip}:{port} 连不上——这是网络问题,不是配置问题。"
|
||||
+ (f"当前所有请求都发往代理 {px},先确认这个代理在服务器上活着(或删掉 *_PROXY 环境变量改成直连)。"
|
||||
if px else
|
||||
"确认服务器/容器能出网 443(安全组出站、iptables FORWARD、docker 网络),"
|
||||
"可以在宿主机上 `curl -sv https://" + host + "/` 对比一下:宿主机通、容器不通就是容器 NAT 的问题。")
|
||||
)
|
||||
return out
|
||||
|
||||
# 3) TLS:能把 TCP 建起来但握手失败,多半是中间设备劫持或证书链缺失
|
||||
if parts.scheme == "https":
|
||||
t0 = time.perf_counter()
|
||||
try:
|
||||
reader, writer = await asyncio.wait_for(
|
||||
asyncio.open_connection(ip, port, ssl=ssl.create_default_context(), server_hostname=host), 8
|
||||
)
|
||||
ssock = writer.get_extra_info("ssl_object")
|
||||
detail = f"{ssock.version()} {ssock.cipher()[0] if ssock else ''}"
|
||||
writer.close()
|
||||
step("tls", True, time.perf_counter() - t0, detail.strip())
|
||||
except Exception as exc: # noqa: BLE001 - 自检要兜住一切
|
||||
step("tls", False, time.perf_counter() - t0, f"{exc.__class__.__name__}: {exc}")
|
||||
out["hint"] = "TLS 握手失败:中间设备可能在做 HTTPS 拦截,或缺 CA 证书(容器里 update-ca-certificates)"
|
||||
return out
|
||||
|
||||
# 4) 真正打一次和风接口:401/403 才是 Key/Host 的问题
|
||||
t0 = time.perf_counter()
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=httpx.Timeout(8.0, connect=6.0)) as http:
|
||||
data = await _get(http, f"{base}/geo/v2/city/lookup",
|
||||
{"location": city, "number": 1, "lang": "zh"}, key)
|
||||
except (WeatherUpstreamError, httpx.HTTPError) as exc:
|
||||
msg = str(exc) if isinstance(exc, WeatherUpstreamError) else explain_error(exc, base)
|
||||
step("http", False, time.perf_counter() - t0, msg)
|
||||
out["hint"] = (
|
||||
"能连上和风但被拒绝:Key 与 Host 不匹配,或 Key 已过期/项目未启用"
|
||||
if "401" in msg or "403" in msg else msg
|
||||
)
|
||||
return out
|
||||
|
||||
items = data.get("location") or []
|
||||
step("http", True, time.perf_counter() - t0,
|
||||
f"HTTP 200,{city} → {items[0].get('name') if items else '(无结果)'} / {items[0].get('id') if items else '-'}")
|
||||
if not items:
|
||||
out["hint"] = f"接口通了,但查不到城市「{city}」:把常住地改成标准地名再试"
|
||||
return out
|
||||
|
||||
out["ok"] = True
|
||||
out["hint"] = "一切正常:DNS、出网、证书、Key/Host 都对。设备侧没数据就是别的原因(没绑定 / 没联网 / 缓存)。"
|
||||
return out
|
||||
|
|
|
|||
|
|
@ -107,6 +107,20 @@ export type FortuneRow = {
|
|||
|
||||
export type AdminUser = User & { devices: Device[] }
|
||||
|
||||
// 天气连通性自检:后端把一次请求拆成 DNS/TCP/TLS/HTTP 四步各自计时
|
||||
export type WeatherProbeStep = { name: string; ok: boolean; ms: number | null; detail: string }
|
||||
export type WeatherProbe = {
|
||||
ok: boolean
|
||||
city: string
|
||||
host?: string
|
||||
port?: number
|
||||
key_kind?: string
|
||||
resolved?: string[]
|
||||
proxy?: string
|
||||
steps: WeatherProbeStep[]
|
||||
hint?: string
|
||||
}
|
||||
|
||||
export type Firmware = {
|
||||
id: string
|
||||
model: string
|
||||
|
|
@ -337,6 +351,8 @@ export const api = {
|
|||
req<{ items: { key: string; value: unknown; updated_at?: string | null }[] }>('/api/admin/settings'),
|
||||
saveSetting: (key: string, value: string) =>
|
||||
req<{ ok: boolean }>('/api/admin/settings', { method: 'PUT', body: JSON.stringify({ key, value }) }),
|
||||
testWeather: (city?: string) =>
|
||||
req<WeatherProbe>(`/api/admin/settings/weather/test${qs({ city })}`, { method: 'POST' }),
|
||||
regions: (params: { q?: string; level?: number; page?: number; page_size?: number }) =>
|
||||
req<{ total: number; page: number; page_size: number; items: RegionRow[] }>(`/api/admin/regions${qs(params)}`),
|
||||
createRegion: (body: Omit<RegionRow, 'sort_order'> & { sort_order?: number }) =>
|
||||
|
|
|
|||
|
|
@ -222,6 +222,9 @@ export default {
|
|||
keyTip: 'The API Key under Project → Credentials; a JWT also works',
|
||||
host: 'API Host',
|
||||
hostTip: 'Your account-specific host, from Console → Settings',
|
||||
test: 'Test connection',
|
||||
testOk: 'Connection OK',
|
||||
testFail: 'Connection failed',
|
||||
},
|
||||
fw: {
|
||||
statDevices: 'Devices',
|
||||
|
|
|
|||
|
|
@ -222,6 +222,9 @@ export default {
|
|||
keyTip: '控制台「项目管理 → 凭据」里的 API Key;也可以直接贴 JWT',
|
||||
host: 'API Host',
|
||||
hostTip: '账号专属域名,控制台「设置」里复制',
|
||||
test: '测试连通',
|
||||
testOk: '连通正常',
|
||||
testFail: '连通异常',
|
||||
},
|
||||
fw: {
|
||||
statDevices: '设备总数',
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { useCallback, useEffect, useState } from 'react'
|
||||
import {
|
||||
Alert,
|
||||
App,
|
||||
Button,
|
||||
Card,
|
||||
|
|
@ -22,7 +23,7 @@ import type { ColumnsType } from 'antd/es/table'
|
|||
import { useNavigate } from 'react-router-dom'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import dayjs from 'dayjs'
|
||||
import { api, auth, type AdminUser, type Device, type FortuneRow, type RegionRow, type Zodiac, type Zodiac as ZodiacType } from '../api'
|
||||
import { api, auth, type AdminUser, type Device, type FortuneRow, type RegionRow, type WeatherProbe, type Zodiac, type Zodiac as ZodiacType } from '../api'
|
||||
import TopBar from '../components/TopBar'
|
||||
import {
|
||||
ChipIcon,
|
||||
|
|
@ -964,6 +965,8 @@ function SettingsPanel() {
|
|||
const [loading, setLoading] = useState(false)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [ready, setReady] = useState<boolean | null>(null)
|
||||
const [probe, setProbe] = useState<WeatherProbe | null>(null)
|
||||
const [probing, setProbing] = useState(false)
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true)
|
||||
|
|
@ -1003,6 +1006,18 @@ function SettingsPanel() {
|
|||
}
|
||||
}
|
||||
|
||||
// 一键自检:DNS → TCP → TLS → HTTP,哪步断了一眼看得出,不用登服务器
|
||||
async function testConn() {
|
||||
setProbing(true)
|
||||
try {
|
||||
setProbe(await api.admin.testWeather())
|
||||
} catch (e) {
|
||||
message.error((e as Error).message)
|
||||
} finally {
|
||||
setProbing(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Card
|
||||
className="panel"
|
||||
|
|
@ -1033,11 +1048,34 @@ function SettingsPanel() {
|
|||
<Button type="primary" htmlType="submit" loading={saving} icon={<SaveIcon size={15} />}>
|
||||
{t('common.save')}
|
||||
</Button>
|
||||
<Button onClick={load} icon={<RefreshIcon size={15} />}>
|
||||
<Button onClick={testConn} loading={probing} icon={<RefreshIcon size={15} />}>
|
||||
{t('admin.settings.test')}
|
||||
</Button>
|
||||
<Button type="text" onClick={load}>
|
||||
{t('common.refresh')}
|
||||
</Button>
|
||||
</Space>
|
||||
</Form>
|
||||
|
||||
{probe && (
|
||||
<div className="probe-box">
|
||||
<Alert
|
||||
type={probe.ok ? 'success' : 'warning'}
|
||||
showIcon
|
||||
message={probe.ok ? t('admin.settings.testOk') : t('admin.settings.testFail')}
|
||||
description={probe.hint}
|
||||
/>
|
||||
<ul className="probe-steps">
|
||||
{probe.steps.map((s) => (
|
||||
<li key={s.name} className={s.ok ? 'is-ok' : 'is-bad'}>
|
||||
<span className="probe-name">{s.name.toUpperCase()}</span>
|
||||
<span className="probe-ms">{s.ms === null ? '—' : `${s.ms} ms`}</span>
|
||||
<span className="probe-detail">{s.detail}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</Spin>
|
||||
</Card>
|
||||
)
|
||||
|
|
|
|||
|
|
@ -918,3 +918,49 @@ body {
|
|||
animation: none !important;
|
||||
}
|
||||
}
|
||||
|
||||
/* 平台设置 · 天气连通性自检(.probe-box 只在点过「测试连通」后出现) */
|
||||
.probe-box {
|
||||
margin-top: 20px;
|
||||
max-width: 480px;
|
||||
}
|
||||
.probe-steps {
|
||||
list-style: none;
|
||||
margin: 12px 0 0;
|
||||
padding: 0;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 10px;
|
||||
overflow: hidden;
|
||||
background: var(--panel);
|
||||
}
|
||||
.probe-steps li {
|
||||
display: grid;
|
||||
grid-template-columns: 52px 64px 1fr;
|
||||
gap: 8px;
|
||||
align-items: baseline;
|
||||
padding: 8px 12px;
|
||||
font-size: 12px;
|
||||
border-top: 1px solid var(--line-soft);
|
||||
}
|
||||
.probe-steps li:first-child {
|
||||
border-top: none;
|
||||
}
|
||||
.probe-name {
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.04em;
|
||||
color: var(--muted);
|
||||
}
|
||||
.probe-steps li.is-ok .probe-name {
|
||||
color: #12a150;
|
||||
}
|
||||
.probe-steps li.is-bad .probe-name {
|
||||
color: #d92d20;
|
||||
}
|
||||
.probe-ms {
|
||||
color: var(--muted);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.probe-detail {
|
||||
color: var(--ink);
|
||||
word-break: break-word;
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue