mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-11-23 04:42:08 +08:00
refactor(log): in-place writer lifecycle and span-based core observability (#7889)
* refactor(log): migrate logging to tracing-estuary pipeline Swap flexi_logger + clash-verge-logger wiring for the tracing-estuary crate: buffered file sink with explicit panic/exit drains, live level switching, and tokio-trace/chrome-trace behind crate features. AsyncLogger moves in-house (VecDeque ring); file format and rotation stay unchanged. * fix(log): reset sidecar writer in place and re-pin service-ipc v2.6.7 Rebuilding the sidecar FileLogWriter on config changes leaked flexi's unstoppable flusher thread plus an fd each time; the writer is now flushed and reset in place, matching what the service crate does. get_clash_logs_by_service drops the CompactString conversion layer now that service-ipc v2.6.7 returns plain Vec<String>, and AsyncLogger is renamed LogRing to match. * refactor(log): span-based observability and log noise cleanup Instrument spans carry the structure flat lines never could: the core-start spine (mode, readiness/owner generations, pid, config file), proxy apply and clear routes with guard generations, service IPC sessions with refusal codes and outcomes, profile-switch terminal outcomes, subscription fetch strategies, core upgrades with per-proxy version probes, backup flows, timer tasks, config generation uids, and the startup setup flow; running-mode changes emit one guarded transition event each. ~90 hand-written noise lines are gone or demoted (entry+success pairs, polled getter echoes, phase brackets, window sub-steps, platform install chatter); errors keep their anyhow chain, operation name, and item id, and swallowed retry results surface per attempt.
This commit is contained in:
@@ -23,7 +23,6 @@ use clash_verge_service_ipc::{
|
||||
MacosProxyConfig, OwnerSessionProof, ProxyApplyOutcome, RuntimeBundle, ServiceErrorCode, StageRuntimeOutcome,
|
||||
StartClashRequest, WriterConfig,
|
||||
};
|
||||
use compact_str::CompactString;
|
||||
use once_cell::sync::Lazy;
|
||||
use parking_lot::Mutex;
|
||||
use std::{
|
||||
@@ -74,13 +73,19 @@ pub(crate) fn clear_active_service_session() {
|
||||
}
|
||||
|
||||
/// Probes staging support without failing startup when the fast path is unavailable.
|
||||
#[tracing::instrument(skip_all, level = "info", fields(supported = tracing::field::Empty))]
|
||||
async fn probe_runtime_staging_support() -> bool {
|
||||
match clash_verge_service_ipc::get_version().await {
|
||||
Ok(response) if response.code == 0 => response
|
||||
.data
|
||||
.as_ref()
|
||||
.is_some_and(clash_verge_service_ipc::ProtocolInfo::supports_runtime_staging),
|
||||
Ok(response) if response.code == 0 => {
|
||||
let supported = response
|
||||
.data
|
||||
.as_ref()
|
||||
.is_some_and(clash_verge_service_ipc::ProtocolInfo::supports_runtime_staging);
|
||||
tracing::Span::current().record("supported", supported);
|
||||
supported
|
||||
}
|
||||
Ok(response) => {
|
||||
tracing::Span::current().record("supported", false);
|
||||
logging!(
|
||||
warn,
|
||||
Type::Service,
|
||||
@@ -91,6 +96,7 @@ async fn probe_runtime_staging_support() -> bool {
|
||||
false
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::Span::current().record("supported", false);
|
||||
logging!(
|
||||
warn,
|
||||
Type::Service,
|
||||
@@ -818,7 +824,7 @@ async fn collect_service_runtime_bundle(config_file: &Path) -> Result<RuntimeBun
|
||||
|
||||
/// A staging response whose refusal code tells callers whether a fresh start can help.
|
||||
pub(super) enum StageRequest {
|
||||
Refused { code: u16, message: CompactString },
|
||||
Refused { code: u16, message: String },
|
||||
Answered(StageRuntimeOutcome),
|
||||
}
|
||||
|
||||
@@ -841,7 +847,7 @@ pub(super) async fn stage_runtime_by_service(config_file: &Path) -> Result<Stage
|
||||
if response.code > 0 {
|
||||
return Ok(StageRequest::Refused {
|
||||
code: response.code,
|
||||
message: response.message.into(),
|
||||
message: response.message,
|
||||
});
|
||||
}
|
||||
response
|
||||
@@ -851,8 +857,8 @@ pub(super) async fn stage_runtime_by_service(config_file: &Path) -> Result<Stage
|
||||
}
|
||||
|
||||
/// 尝试使用服务启动core
|
||||
#[tracing::instrument(skip_all, level = "info", fields(generation = tracing::field::Empty, staging = tracing::field::Empty, code = tracing::field::Empty, outcome = tracing::field::Empty))]
|
||||
pub(super) async fn start_with_existing_service(config_file: &Path) -> Result<()> {
|
||||
logging!(info, Type::Service, "尝试使用现有服务启动核心");
|
||||
clear_active_service_session();
|
||||
|
||||
let credentials = current_owner_credentials()?;
|
||||
@@ -867,14 +873,23 @@ pub(super) async fn start_with_existing_service(config_file: &Path) -> Result<()
|
||||
let response = match clash_verge_service_ipc::start_clash(&credentials, &request).await {
|
||||
Ok(response) => response,
|
||||
Err(error) => {
|
||||
tracing::Span::current().record("outcome", "ipc-unreachable");
|
||||
start_owner_monitor();
|
||||
return Err(error).context("无法连接到Clash Verge Service");
|
||||
}
|
||||
};
|
||||
|
||||
if response.code > 0 {
|
||||
tracing::Span::current().record("code", response.code);
|
||||
tracing::Span::current().record("outcome", "refused");
|
||||
let err_msg = response.message;
|
||||
logging!(error, Type::Service, "启动核心失败: {}", err_msg);
|
||||
logging!(
|
||||
error,
|
||||
Type::Service,
|
||||
"启动核心失败 (code {}): {}",
|
||||
response.code,
|
||||
err_msg
|
||||
);
|
||||
start_owner_monitor();
|
||||
bail!(
|
||||
"failed to start Service core at {}: {err_msg}",
|
||||
@@ -883,7 +898,9 @@ pub(super) async fn start_with_existing_service(config_file: &Path) -> Result<()
|
||||
}
|
||||
|
||||
let result = response.data.context("Clash Verge Service 未返回会话信息")?;
|
||||
tracing::Span::current().record("generation", result.session.generation);
|
||||
let supports_runtime_staging = probe_runtime_staging_support().await;
|
||||
tracing::Span::current().record("staging", supports_runtime_staging);
|
||||
*ACTIVE_SERVICE_SESSION.lock() = Some(ActiveServiceSession {
|
||||
proof: OwnerSessionProof {
|
||||
generation: result.session.generation,
|
||||
@@ -894,14 +911,18 @@ pub(super) async fn start_with_existing_service(config_file: &Path) -> Result<()
|
||||
|
||||
// PAC follows the Running Mode; the caller opens it via `core_started(Service)`.
|
||||
start_owner_monitor();
|
||||
logging!(info, Type::Service, "服务成功启动核心");
|
||||
tracing::Span::current().record("outcome", "started");
|
||||
logging!(
|
||||
info,
|
||||
Type::Service,
|
||||
"服务成功启动核心 (session generation {})",
|
||||
result.session.generation
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// 以服务启动core
|
||||
pub(super) async fn run_core_by_service(config_file: &Path) -> Result<()> {
|
||||
logging!(info, Type::Service, "正在尝试通过服务启动核心");
|
||||
|
||||
SERVICE_MANAGER.refresh().await?;
|
||||
|
||||
let status = SERVICE_MANAGER.current().await;
|
||||
@@ -922,9 +943,8 @@ where
|
||||
(captured, operation().await)
|
||||
}
|
||||
|
||||
pub(super) async fn get_clash_logs_by_service() -> Result<Vec<CompactString>> {
|
||||
logging!(info, Type::Service, "正在获取服务模式下的 Clash 日志");
|
||||
|
||||
pub(super) async fn get_clash_logs_by_service() -> Result<Vec<String>> {
|
||||
// Frontend-polled: no per-call logging here.
|
||||
let credentials = current_owner_credentials()?;
|
||||
let (generation, response) = capture_generation_before(&OWNER_MONITOR_GENERATION, || {
|
||||
clash_verge_service_ipc::get_clash_logs(&credentials)
|
||||
@@ -937,11 +957,9 @@ pub(super) async fn get_clash_logs_by_service() -> Result<Vec<CompactString>> {
|
||||
recover_after_owner_loss(generation, OwnerRecoveryReason::Displaced).await;
|
||||
}
|
||||
let err_msg = response.message;
|
||||
logging!(error, Type::Service, "获取服务模式下的 Clash 日志失败: {}", err_msg);
|
||||
bail!(err_msg);
|
||||
}
|
||||
|
||||
logging!(info, Type::Service, "成功获取服务模式下的 Clash 日志");
|
||||
Ok(response.data.unwrap_or_default())
|
||||
}
|
||||
|
||||
@@ -970,8 +988,8 @@ pub(crate) async fn get_clash_log_snapshot_by_service() -> Result<String> {
|
||||
}
|
||||
|
||||
/// 通过服务停止core
|
||||
#[tracing::instrument(skip_all, level = "info", fields(code = tracing::field::Empty, outcome = tracing::field::Empty))]
|
||||
pub(super) async fn stop_core_by_service() -> Result<()> {
|
||||
logging!(info, Type::Service, "通过服务停止核心 (IPC)");
|
||||
cancel_owner_monitors();
|
||||
|
||||
let credentials = match current_owner_credentials() {
|
||||
@@ -1007,11 +1025,20 @@ pub(super) async fn stop_core_by_service() -> Result<()> {
|
||||
start_owner_monitor();
|
||||
}
|
||||
let err_msg = response.message;
|
||||
logging!(error, Type::Service, "停止核心失败: {}", err_msg);
|
||||
tracing::Span::current().record("code", response.code);
|
||||
tracing::Span::current().record("outcome", "refused");
|
||||
logging!(
|
||||
error,
|
||||
Type::Service,
|
||||
"停止核心失败 (code {}): {}",
|
||||
response.code,
|
||||
err_msg
|
||||
);
|
||||
bail!(err_msg);
|
||||
}
|
||||
|
||||
clear_active_service_session();
|
||||
tracing::Span::current().record("outcome", "stopped");
|
||||
logging!(info, Type::Service, "服务成功停止核心");
|
||||
Ok(())
|
||||
}
|
||||
@@ -1023,6 +1050,13 @@ pub(crate) async fn update_writer_by_service(writer: &WriterConfig) -> Result<()
|
||||
.await
|
||||
.context("无法连接到Clash Verge Service")?;
|
||||
if response.code > 0 {
|
||||
logging!(
|
||||
warn,
|
||||
Type::Service,
|
||||
"update writer rejected by service: code={}, {}",
|
||||
response.code,
|
||||
response.message
|
||||
);
|
||||
bail!(response.message);
|
||||
}
|
||||
Ok(())
|
||||
@@ -1042,6 +1076,13 @@ pub(super) async fn set_system_proxy_by_service_with_session(
|
||||
.await
|
||||
.context("无法连接到Clash Verge Service")?;
|
||||
if response.code > 0 {
|
||||
logging!(
|
||||
warn,
|
||||
Type::Service,
|
||||
"set system proxy rejected by service: code={}, {}",
|
||||
response.code,
|
||||
response.message
|
||||
);
|
||||
bail!(response.message);
|
||||
}
|
||||
response.data.context("Clash Verge Service 未返回系统代理结果")
|
||||
@@ -1074,13 +1115,24 @@ const SUSTAINED_OWNER_SAMPLES: u8 = 3;
|
||||
fn start_owner_monitor() {
|
||||
let generation = OWNER_MONITOR_GENERATION.fetch_add(1, Ordering::AcqRel) + 1;
|
||||
AsyncHandler::spawn(move || async move {
|
||||
logging!(debug, Type::Service, "owner monitor started (generation {generation})");
|
||||
let mut watch = OwnerWatch::new();
|
||||
loop {
|
||||
tokio::time::sleep(OWNER_MONITOR_INTERVAL).await;
|
||||
if OWNER_MONITOR_GENERATION.load(Ordering::Acquire) != generation {
|
||||
logging!(
|
||||
debug,
|
||||
Type::Service,
|
||||
"owner monitor superseded (generation {generation})"
|
||||
);
|
||||
break;
|
||||
}
|
||||
if !matches!(*CoreManager::global().get_running_mode(), RunningMode::Service) {
|
||||
logging!(
|
||||
debug,
|
||||
Type::Service,
|
||||
"owner monitor stopped; core no longer in service mode (generation {generation})"
|
||||
);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -1091,7 +1143,7 @@ fn start_owner_monitor() {
|
||||
logging!(
|
||||
warn,
|
||||
Type::Service,
|
||||
"service owner status unavailable for {SUSTAINED_OWNER_SAMPLES} samples; \
|
||||
"service owner status unavailable for {SUSTAINED_OWNER_SAMPLES} samples (generation {generation}); \
|
||||
preserving local proxy state while the core endpoint still answers"
|
||||
);
|
||||
}
|
||||
@@ -1199,6 +1251,7 @@ fn claim_owner_recovery_generation(generation: &AtomicU64, captured_generation:
|
||||
.map(|_| recovery_generation)
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip_all, level = "info", fields(reason = ?reason))]
|
||||
async fn recover_after_owner_loss_while_locked(reason: OwnerRecoveryReason) {
|
||||
logging!(
|
||||
warn,
|
||||
@@ -1215,10 +1268,15 @@ async fn recover_after_owner_loss_while_locked(reason: OwnerRecoveryReason) {
|
||||
}
|
||||
|
||||
let mut last_error = None;
|
||||
for _ in 0..3 {
|
||||
for attempt in 1..=3 {
|
||||
match proxy_control::clear().await {
|
||||
Ok(()) => return,
|
||||
Err(error) => {
|
||||
logging!(
|
||||
warn,
|
||||
Type::Service,
|
||||
"proxy clear attempt {attempt}/3 after owner loss failed: {error:#}"
|
||||
);
|
||||
last_error = Some(error);
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
@@ -1228,24 +1286,35 @@ async fn recover_after_owner_loss_while_locked(reason: OwnerRecoveryReason) {
|
||||
logging!(
|
||||
error,
|
||||
Type::Service,
|
||||
"failed to clear local proxy after owner loss: {error}"
|
||||
"failed to clear local proxy after owner loss: {error:#}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Waits for a repaired service, preserving readable rejection details but classifying sustained
|
||||
/// silence as unavailable.
|
||||
#[tracing::instrument(skip_all, level = "info", fields(attempts = tracing::field::Empty, interval_ms = tracing::field::Empty, outcome = tracing::field::Empty))]
|
||||
async fn wait_for_service_ipc() -> Result<()> {
|
||||
const CONTEXT: &str = "service IPC did not become available";
|
||||
let config = ServiceManager::config();
|
||||
let span = tracing::Span::current();
|
||||
span.record("attempts", config.max_retries);
|
||||
span.record("interval_ms", config.retry_delay.as_millis() as u64);
|
||||
|
||||
match RUN_STATE.await_ready(config.max_retries, config.retry_delay).await {
|
||||
Ok(_) => Ok(()),
|
||||
Ok(_) => {
|
||||
tracing::Span::current().record("outcome", "ready");
|
||||
Ok(())
|
||||
}
|
||||
Err(ReadyWaitError::Unreachable(error)) => {
|
||||
tracing::Span::current().record("outcome", "unreachable");
|
||||
RUN_STATE.observe(ServiceHealth::Unavailable(format!("{CONTEXT}: {error:#}")));
|
||||
Err(error).context(CONTEXT)
|
||||
}
|
||||
Err(ReadyWaitError::Rejected(error)) => Err(error).context(CONTEXT),
|
||||
Err(ReadyWaitError::Rejected(error)) => {
|
||||
tracing::Span::current().record("outcome", "rejected");
|
||||
Err(error).context(CONTEXT)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user