From 6f81fb91b353030047f2195ca0127a84f0939816 Mon Sep 17 00:00:00 2001 From: Tunglies <77394545+Tunglies@users.noreply.github.com> Date: Fri, 4 Dec 2026 13:00:42 +0800 Subject: [PATCH] refactor(core): manage sidecar execution in CVR --- Cargo.lock | 4 +- Cargo.toml | 2 +- Changelog.md | 1 + src-tauri/src/core/manager/lifecycle.rs | 6 +- src-tauri/src/core/manager/state.rs | 129 +++++++--------- src-tauri/src/core/runstate/env.rs | 12 +- src-tauri/src/core/service.rs | 189 +++++++++++++++++++++--- 7 files changed, 228 insertions(+), 115 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 62be2ee95..28fc9a17b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1342,8 +1342,8 @@ dependencies = [ [[package]] name = "clash_verge_service_ipc" -version = "2.8.2" -source = "git+https://github.com/clash-verge-rev/clash-verge-service-ipc.git?branch=main#3e06ff153e9cb19ae20e0a61f861b371d3f7b2aa" +version = "2.8.3" +source = "git+https://github.com/clash-verge-rev/clash-verge-service-ipc.git?rev=31f19403e0077c40e4e9f64589de7bfca05c130d#31f19403e0077c40e4e9f64589de7bfca05c130d" dependencies = [ "anyhow", "kode-bridge", diff --git a/Cargo.toml b/Cargo.toml index db9c4ed0b..090da8845 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -74,7 +74,7 @@ clash-verge-runtime-bundle = { path = "crates/clash-verge-runtime-bundle" } clash-verge-proxy-view = { path = "crates/clash-verge-proxy-view" } clash-verge-profile = { path = "crates/clash-verge-profile" } clash-verge-backup-archive = { path = "crates/clash-verge-backup-archive" } -clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verge-service-ipc.git", branch = "main", version = "2.8.2", default-features = false } +clash_verge_service_ipc = { git = "https://github.com/clash-verge-rev/clash-verge-service-ipc.git", rev = "31f19403e0077c40e4e9f64589de7bfca05c130d", version = "2.8.3", default-features = false } tracing-estuary = { git = "https://github.com/Tunglies/tracing-estuary.git", branch = "main" } tauri-plugin-clash-verge-sysinfo = { path = "crates/tauri-plugin-clash-verge-sysinfo" } tracing = "0.1.44" diff --git a/Changelog.md b/Changelog.md index 3d500e11d..ddd551893 100644 --- a/Changelog.md +++ b/Changelog.md @@ -49,6 +49,7 @@ **🖥️ Windows** +- 修复 Windows 服务启动失败后自动切换内核,现显示原因并等待用户选择 - 修复 Windows 普通用户因权限不足无法开启「开机自启」 **🍎 macOS** diff --git a/src-tauri/src/core/manager/lifecycle.rs b/src-tauri/src/core/manager/lifecycle.rs index 073f2cb8e..af38e506f 100644 --- a/src-tauri/src/core/manager/lifecycle.rs +++ b/src-tauri/src/core/manager/lifecycle.rs @@ -343,11 +343,8 @@ impl CoreManager { if !can_allow_sidecar_for_session(&mode, &status) { anyhow::bail!("Sidecar continuation is not allowed from {mode:?} / {status:?}"); } - #[cfg(target_os = "windows")] if matches!(*mode, RunningMode::NotRunning) { - clash_verge_service_ipc::execution::check_sidecar_available() - .await - .map_err(super::state::explain_core_occupancy)?; + crate::core::service::release_service_core_for_sidecar().await?; } if !matches!(status, ServiceStatus::SidecarAllowed) { SERVICE_MANAGER.allow_sidecar_for_session()?; @@ -416,6 +413,7 @@ impl CoreManager { let _life = self.lifecycle_lock.lock().await; self.controlled_stop_core_inner().await?; + crate::core::service::release_service_core_for_sidecar().await?; let result = run_uninstall_transition( || async { diff --git a/src-tauri/src/core/manager/state.rs b/src-tauri/src/core/manager/state.rs index 57258c41d..660b74c13 100644 --- a/src-tauri/src/core/manager/state.rs +++ b/src-tauri/src/core/manager/state.rs @@ -11,27 +11,14 @@ use crate::{ use anyhow::{Context as _, Result}; use clash_verge_logging::Type; use clash_verge_task::retry::{RetryError, RetryPolicy, retry}; -use futures::{ - FutureExt as _, - future::{Map, Shared}, -}; +use futures::{FutureExt as _, future::Shared}; use log::Level; use std::num::NonZeroUsize; use std::path::Path; -use std::sync::Arc; use tauri_plugin_mihomo::MihomoExt as _; use tauri_plugin_shell::ShellExt as _; use tauri_plugin_shell::process::CommandChild; -use tokio::task::{JoinError, JoinHandle}; - -pub(super) fn explain_core_occupancy(error: anyhow::Error) -> anyhow::Error { - let detail = error.to_string(); - if detail.starts_with("process verge-mihomo") && detail.ends_with("; refusing a second core") { - error.context(clash_verge_i18n::t!("core.alreadyRunning").into_owned()) - } else { - error - } -} +use tokio::sync::oneshot; #[cfg(target_os = "windows")] fn sidecar_config_without_tun(yaml: &str) -> Result { @@ -146,18 +133,10 @@ fn should_clear_terminated_sidecar( matches!(running_mode, RunningMode::Sidecar) && current_generation == Some(terminated_generation) } -type ShareExitResult = fn(Result<(), JoinError>) -> Result<(), Arc>; -type SidecarExit = Shared, ShareExitResult>>; - -fn share_exit(exit: JoinHandle<()>) -> SidecarExit { - let share_error: ShareExitResult = |result| result.map_err(Arc::new); - exit.map(share_error).shared() -} - #[derive(Debug, Default)] pub(super) struct SidecarSession { process: Option, - exit: Option, + exit: Option>>, } #[derive(Debug)] @@ -195,10 +174,7 @@ impl CoreManager { #[tracing::instrument(skip_all, level = "info", fields(pid = tracing::field::Empty))] pub(super) async fn start_core_by_sidecar(&self) -> Result<()> { self.wait_for_sidecar_exit().await?; - let execution = clash_verge_service_ipc::execution::reserve_sidecar() - .await - .inspect_err(service::record_residual_service) - .map_err(explain_core_occupancy)?; + service::require_service_core_released()?; self.core_stopped(); let sidecar_ipc = dirs::sidecar_ipc_path()?; @@ -221,8 +197,6 @@ impl CoreManager { #[cfg(unix)] discard_unwritable_core_cache(&config_dir); - #[cfg(unix)] - let previous_mask = unsafe { tauri_plugin_clash_verge_sysinfo::libc::umask(0o077) }; let command = app_handle .shell() .sidecar(clash_core.as_str()) @@ -244,6 +218,13 @@ impl CoreManager { "LISTEN_NAMEDPIPE_SDDL", crate::core::owner_identity::current_user_pipe_sddl()?, ); + #[cfg(unix)] + let restore_mask = std::mem::DropGuard::new( + unsafe { tauri_plugin_clash_verge_sysinfo::libc::umask(0o077) }, + |mask| { + unsafe { tauri_plugin_clash_verge_sysinfo::libc::umask(mask) }; + }, + ); let (mut rx, child) = command.spawn().map_err(|error| { anyhow::anyhow!( "failed to start sidecar core {clash_core:?} with config {} and data directory {}: {error:#}", @@ -251,35 +232,10 @@ impl CoreManager { config_dir.display() ) })?; - let (terminated, termination) = tokio::sync::oneshot::channel(); - let exit = execution.release_after_exit(child.pid(), termination); - self.sidecar.lock().exit = Some(share_exit(exit)); - #[cfg(target_os = "windows")] - let job = { - match create_and_assign_sidecar_job(child.pid()) { - Ok(job) => job, - Err(job_error) => { - let pid = child.pid(); - - let error = match child.kill() { - Ok(()) => job_error, - Err(kill_error) => anyhow::anyhow!( - "failed to configure Job Object for sidecar PID {pid}: \ - {job_error:#}; failed to terminate child: {kill_error:#}" - ), - }; - - logging!(error, Type::Core, "Failed to start sidecar: {error:#}"); - return Err(error); - } - } - }; - #[cfg(unix)] - unsafe { - tauri_plugin_clash_verge_sysinfo::libc::umask(previous_mask) - }; - + drop(restore_mask); + let (terminated, termination) = oneshot::channel(); + self.sidecar.lock().exit = Some(termination.shared()); let pid = child.pid(); tracing::Span::current().record("pid", pid); @@ -317,6 +273,30 @@ impl CoreManager { } }); + #[cfg(target_os = "windows")] + let job = { + match create_and_assign_sidecar_job(child.pid()) { + Ok(job) => job, + Err(job_error) => { + let pid = child.pid(); + + let error = match child.kill() { + Ok(()) => { + self.sidecar.lock().exit.take(); + job_error + } + Err(kill_error) => anyhow::anyhow!( + "failed to configure Job Object for sidecar PID {pid}: \ + {job_error:#}; failed to terminate child: {kill_error:#}" + ), + }; + + logging!(error, Type::Core, "Failed to start sidecar: {error:#}"); + return Err(error); + } + } + }; + let readiness = poll_sidecar_readiness(SIDECAR_READINESS_ATTEMPTS, SIDECAR_READINESS_INTERVAL, || async { tokio::time::timeout(SIDECAR_READINESS_PROBE_TIMEOUT, async { handle::Handle::mihomo().get_version().await @@ -330,7 +310,10 @@ impl CoreManager { proxy_control::stop_guard().await; self.core_stopped(); return match child.kill() { - Ok(()) => Err(readiness_error), + Ok(()) => { + self.sidecar.lock().exit.take(); + Err(readiness_error) + } Err(kill_error) => Err(anyhow::anyhow!( "{readiness_error:#}; failed to terminate unready sidecar PID {pid}: {kill_error:#}" )), @@ -358,8 +341,11 @@ impl CoreManager { #[cfg(target_os = "windows")] drop(process.job); - if let Err(error) = process.child.kill() { - logging!(warn, Type::Core, "failed to terminate sidecar PID {pid}: {error:#}"); + match process.child.kill() { + Ok(()) => { + self.sidecar.lock().exit.take(); + } + Err(error) => logging!(warn, Type::Core, "failed to terminate sidecar PID {pid}: {error:#}"), } } let result = self.wait_for_sidecar_exit().await; @@ -393,12 +379,13 @@ impl CoreManager { #[tracing::instrument(skip_all, level = "info", fields(config_file = %config_file.display()))] pub(super) async fn start_core_by_service_with_config(&self, config_file: &Path) -> Result<()> { - // 交接时等待 sidecar 释放 ext-controller 通道。 + self.wait_for_sidecar_exit().await?; + let start = tokio::sync::OnceCell::new(); #[cfg(target_os = "windows")] { use crate::constants::timing; retry_service_start(timing::SERVICE_START_RETRIES, timing::SERVICE_START_RETRY_DELAY, || { - service::run_core_by_service(config_file) + service::run_core_by_service(config_file, &start) }) .await?; self.mark_core_ready(); @@ -410,7 +397,7 @@ impl CoreManager { #[cfg(not(target_os = "windows"))] { - service::run_core_by_service(config_file).await?; + service::run_core_by_service(config_file, &start).await?; self.mark_core_ready(); self.core_started(RunningMode::Service); self.restore_selected_nodes().await; @@ -556,20 +543,6 @@ mod readiness_tests { time::Duration, }; - #[test] - fn core_occupancy_explanation_preserves_the_original_error() { - for detail in [ - "process verge-mihomo remains after IPC failure; refusing a second core", - "process verge-mihomo-alpha.exe (PID 123) is still running; refusing a second core", - ] { - let error = super::explain_core_occupancy(anyhow::anyhow!(detail)); - assert_eq!(error.to_string(), clash_verge_i18n::t!("core.alreadyRunning")); - assert_eq!(error.root_cause().to_string(), detail); - } - let error = super::explain_core_occupancy(anyhow::anyhow!("could not inspect remaining cores")); - assert_eq!(error.to_string(), "could not inspect remaining cores"); - } - #[tokio::test] async fn sidecar_readiness_poll_is_bounded_and_accepts_a_real_api_response() -> anyhow::Result<()> { let attempts = Arc::new(AtomicUsize::new(0)); diff --git a/src-tauri/src/core/runstate/env.rs b/src-tauri/src/core/runstate/env.rs index b49bed20a..e7c9b66d4 100644 --- a/src-tauri/src/core/runstate/env.rs +++ b/src-tauri/src/core/runstate/env.rs @@ -67,17 +67,9 @@ impl RunStateEnv for RealEnv { } async fn trusted_install_evidence(&self) -> Result { - let registered = tokio::task::spawn_blocking(crate::core::service::trusted_service_evidence) + tokio::task::spawn_blocking(crate::core::service::trusted_service_evidence) .await - .context("service registration probe did not finish")??; - // A helper that outlived its registration is a broken Service, not an absent one. - #[cfg(unix)] - if !registered && let Err(error) = clash_verge_service_ipc::execution::check_sidecar_available().await { - return Ok(error - .downcast_ref::() - .is_some()); - } - Ok(registered) + .context("service registration probe did not finish")? } fn is_elevated(&self) -> bool { diff --git a/src-tauri/src/core/service.rs b/src-tauri/src/core/service.rs index dc2a353ea..7d690bf4c 100644 --- a/src-tauri/src/core/service.rs +++ b/src-tauri/src/core/service.rs @@ -44,6 +44,7 @@ use std::{ use tokio::{sync::watch, time::Instant}; static OWNER_MONITOR_GENERATION: AtomicU64 = AtomicU64::new(0); +static PENDING_SERVICE_START: Mutex> = Mutex::new(None); static ACTIVE_SERVICE_SESSION: Mutex> = Mutex::new(None); static PENDING_SERVICE_REPAIR_NOTICE: AtomicBool = AtomicBool::new(false); static PENDING_SERVICE_OWNER_NOTICE: Mutex> = Mutex::new(None); @@ -75,6 +76,29 @@ fn app_data_owner_command(credentials: &OwnerCredentials) -> Option { Some(format!("sudo chown -R {uid}:{gid} '{path}'")) } +#[derive(Clone)] +struct PendingServiceStart { + token: String, + service_replaced: bool, +} + +impl PendingServiceStart { + const fn new(token: String) -> Self { + Self { + token, + service_replaced: false, + } + } + + const fn released_after_repair(&self, status: &ServiceStatusSnapshot) -> bool { + self.service_replaced + && !status.is_active + && status.active_generation.is_none() + && status.core_pid.is_none() + && !status.desired_core_should_be_running + } +} + /// Capabilities of the service session that owns the running Core. /// They are discarded with that session rather than cached across service upgrades. #[derive(Clone)] @@ -575,7 +599,26 @@ pub(crate) fn run_privileged_service_action(action: PendingAction) -> Result<()> PendingAction::Reinstall => (reinstall_service, "reinstall service"), PendingAction::ForceReinstall => (force_reinstall_service, "force reinstall service"), }; - tokio::task::block_in_place(operation).with_context(|| format!("{label} failed")) + tokio::task::block_in_place(|| { + let pending_token = match action { + PendingAction::Reinstall | PendingAction::ForceReinstall => PENDING_SERVICE_START + .lock() + .as_ref() + .map(|pending| pending.token.clone()), + PendingAction::Install | PendingAction::Uninstall => None, + }; + operation().with_context(|| format!("{label} failed"))?; + // Full repair acquires the stopped-service guard before replacing the daemon. + if let Some(token) = pending_token + && let Some(pending) = PENDING_SERVICE_START + .lock() + .as_mut() + .filter(|pending| pending.token == token) + { + pending.service_replaced = true; + } + Ok(()) + }) } /// Builds the same runtime bundle description for both service start and staging. @@ -675,27 +718,87 @@ fn record_service_start_refusal( refusal.into() } -/// Sidecar stays blocked until a reinstall replaces the residual helper, so ask for repair. -pub(super) fn record_residual_service(error: &anyhow::Error) { - if let Some(residual) = error.downcast_ref::() { - RUN_STATE.observe(ServiceHealth::Unavailable(residual.to_string())); +pub(super) fn require_service_core_released() -> Result<()> { + anyhow::ensure!( + PENDING_SERVICE_START.lock().is_none() && ACTIVE_SERVICE_SESSION.lock().is_none(), + "the previous Service core has not confirmed exit" + ); + Ok(()) +} + +pub(super) async fn release_service_core_for_sidecar() -> Result<()> { + let pending = PENDING_SERVICE_START.lock().clone(); + if pending.is_none() { + if active_service_session().is_ok() { + return stop_core_by_service().await; + } + if matches!(RUN_STATE.state().health, ServiceHealth::NotInstalled) { + return Ok(()); + } } + let credentials = current_owner_credentials()?; + let status = tokio::time::timeout( + Duration::from_secs(2), + clash_verge_service_ipc::get_status(&credentials), + ) + .await + .context("timed out confirming the previous Service core exited")??; + anyhow::ensure!(status.code == 0, "Service status failed: {}", status.message); + let status = status.data.context("Service omitted owner status")?; + let Some(pending) = pending else { + anyhow::ensure!( + !status.is_active || (status.core_pid.is_none() && !status.desired_core_should_be_running), + "the Service is running or recovering this owner's core; stop it before switching" + ); + return Ok(()); + }; + if pending.released_after_repair(&status) { + PENDING_SERVICE_START.lock().take(); + clear_active_service_session(); + return Ok(()); + } + // A lost Start reply may have committed. Only its proposed token can stop that generation. + let generation = status + .active_generation + .context("the previous Service start has not confirmed exit; repair the Service before switching")?; + let stopped = clash_verge_service_ipc::stop_clash( + &credentials, + &OwnerSessionProof { + generation, + token: pending.token, + }, + ) + .await?; + anyhow::ensure!( + stopped.code == 0, + "could not confirm Service core exit: {}", + stopped.message + ); + PENDING_SERVICE_START.lock().take(); + clear_active_service_session(); + Ok(()) } /// 尝试使用服务启动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<()> { - clear_active_service_session(); - +async fn start_with_existing_service( + config_file: &Path, + start: &tokio::sync::OnceCell, +) -> Result<()> { let credentials = current_owner_credentials()?; - let runtime = collect_service_runtime_bundle(config_file).await?; - let request = StartClashRequest { - runtime, - proposed_session_token: generate_service_session_token()?, - macos_proxy: None, - }; - - let response = match clash_verge_service_ipc::start_clash(&credentials, &request).await { + let request = start + .get_or_try_init(|| async { + Ok::<_, anyhow::Error>(StartClashRequest { + runtime: collect_service_runtime_bundle(config_file).await?, + proposed_session_token: generate_service_session_token()?, + macos_proxy: None, + }) + }) + .await?; + let previous = PENDING_SERVICE_START + .lock() + .replace(PendingServiceStart::new(request.proposed_session_token.clone())); + let response = match clash_verge_service_ipc::start_clash(&credentials, request).await { Ok(response) => response, Err(error) => { tracing::Span::current().record("outcome", "ipc-unreachable"); @@ -707,6 +810,16 @@ pub(super) async fn start_with_existing_service(config_file: &Path) -> Result<() if response.code > 0 { tracing::Span::current().record("code", response.code); tracing::Span::current().record("outcome", "refused"); + if matches!(response.code, + code if code == ServiceErrorCode::InvalidInstallLocation as u16 + || code == ServiceErrorCode::InvalidRuntimeAsset as u16 + || code == ServiceErrorCode::AppDataRootNotOwned as u16 + || code == ServiceErrorCode::UnauthorizedOwner as u16 + || code == ServiceErrorCode::ProtocolMismatch as u16 + || code == ServiceErrorCode::ProxyClearFailed as u16 + ) { + *PENDING_SERVICE_START.lock() = previous; + } let err_msg = response.message; logging!( error, @@ -729,7 +842,7 @@ pub(super) async fn start_with_existing_service(config_file: &Path) -> Result<() &RUN_STATE, ServiceStartRefusal { code: response.code, - core_path: request.runtime.core_path, + core_path: request.runtime.core_path.clone(), message: err_msg, }, )); @@ -742,13 +855,14 @@ pub(super) async fn start_with_existing_service(config_file: &Path) -> Result<() *ACTIVE_SERVICE_SESSION.lock() = Some(ActiveServiceSession { proof: Arc::new(OwnerSessionProof { generation: result.session.generation, - token: request.proposed_session_token, + token: request.proposed_session_token.clone(), }), supports_runtime_staging: capabilities.runtime_staging, supports_runtime_file_read: capabilities.runtime_file_read, supports_runtime_geo_read: capabilities.runtime_geo_read, }); + PENDING_SERVICE_START.lock().take(); // PAC follows the Running Mode; the caller opens it via `core_started(Service)`. start_owner_monitor(); tracing::Span::current().record("outcome", "started"); @@ -764,7 +878,10 @@ pub(super) async fn start_with_existing_service(config_file: &Path) -> Result<() } // 以服务启动core -pub(super) async fn run_core_by_service(config_file: &Path) -> Result<()> { +pub(super) async fn run_core_by_service( + config_file: &Path, + start: &tokio::sync::OnceCell, +) -> Result<()> { SERVICE_MANAGER.refresh().await?; let status = SERVICE_MANAGER.current().await; @@ -773,7 +890,7 @@ pub(super) async fn run_core_by_service(config_file: &Path) -> Result<()> { } logging!(info, Type::Service, "服务已运行且版本匹配,直接使用"); - start_with_existing_service(config_file).await + start_with_existing_service(config_file, start).await } async fn capture_generation_before(generation: &AtomicU64, operation: F) -> (u64, T) @@ -1683,6 +1800,11 @@ async fn recover_after_owner_loss_while_locked(reason: OwnerRecoveryReason) { if policy.reset_system_proxy { clear_proxy_after_owner_loss().await; } + if matches!(reason, OwnerRecoveryReason::TransportFailure) + && let Ok(session) = active_service_session() + { + *PENDING_SERVICE_START.lock() = Some(PendingServiceStart::new(session.token.clone())); + } clear_active_service_session(); CoreManager::global().core_stopped(); // A displaced Service may still run TUN for its new owner, and DNS settings are system-wide. @@ -1969,6 +2091,33 @@ mod tests { ServiceStatus::from_run_state(&store.settled().await) } + #[test] + fn an_idle_snapshot_releases_an_ambiguous_start_only_after_repair() { + let mut pending = super::PendingServiceStart::new("lost-reply".into()); + let mut status = clash_verge_service_ipc::ServiceStatusSnapshot { + is_active: false, + active_generation: None, + core_pid: None, + desired_core_should_be_running: false, + service_state: clash_verge_service_ipc::ServiceLifecycleState::Running, + core_started_at: None, + last_core_exit_reason: None, + restart_count: 0, + last_recovery_at: None, + desired_generation: 0, + desired_updated_at: 0, + desired_persistence_error: None, + }; + assert!(!pending.released_after_repair(&status)); + pending.service_replaced = true; + assert!(pending.released_after_repair(&status)); + status.active_generation = Some(1); + assert!(!pending.released_after_repair(&status)); + status.active_generation = None; + status.desired_core_should_be_running = true; + assert!(!pending.released_after_repair(&status)); + } + #[test] fn mismatched_active_generation_displaces_local_session() { let proof = OwnerSessionProof {