mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-11-22 04:12:08 +08:00
feat(linux): preserve Service state across upgrades and surface failures
Reinstall an existing Service while keeping its enabled, runtime-masked and active state. Detect, from the journal, a running Service removed by a previous deb prerm and reinstall it with its recorded group. Package script output never reaches the app, so leave a /run marker that makes the app offer a reinstall once when the Service is not ready. Hold the core lifecycle until the package manager exits, even after the startup install times out, so no core start overlaps the Service reinstall; restart the app once a late install succeeds. Refs #8515 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
@@ -750,15 +750,18 @@ impl CoreManager {
|
||||
self.controlled_stop_core_inner().await
|
||||
}
|
||||
|
||||
/// Stops the core only when the Service runs it, returning whether it did. Waits for an in-flight start.
|
||||
/// Holds the core lifecycle for a package install, stopping a Service-run core first and returning
|
||||
/// whether it did, so no core start or restart overlaps the package scripts reinstalling the Service.
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(crate) async fn stop_service_core(&self) -> Result<bool> {
|
||||
let _life = self.lifecycle_lock.lock().await;
|
||||
pub(crate) async fn pause_for_package_install(
|
||||
&'static self,
|
||||
) -> Result<(tokio::sync::MutexGuard<'static, ()>, bool)> {
|
||||
let life = self.lifecycle_lock.lock().await;
|
||||
if !matches!(*self.get_running_mode(), RunningMode::Service) {
|
||||
return Ok(false);
|
||||
return Ok((life, false));
|
||||
}
|
||||
self.controlled_stop_core_inner().await?;
|
||||
Ok(true)
|
||||
Ok((life, true))
|
||||
}
|
||||
|
||||
pub(crate) async fn controlled_stop_core_inner(&self) -> Result<()> {
|
||||
|
||||
@@ -22,7 +22,7 @@ pub enum NoticeStatus {
|
||||
#[serde(rename = "service_core::app_data_not_owned")]
|
||||
ServiceCoreAppDataNotOwned,
|
||||
#[serde(rename = "service_core::sidecar_fallback")]
|
||||
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
|
||||
#[cfg_attr(not(any(target_os = "windows", target_os = "linux")), allow(dead_code))]
|
||||
ServiceCoreSidecarFallback,
|
||||
#[serde(rename = "dns_override::auto_disabled")]
|
||||
DnsOverrideAutoDisabled,
|
||||
|
||||
@@ -50,6 +50,7 @@ pub enum ServiceFallbackNotice {
|
||||
Unavailable,
|
||||
CoreRejected(String),
|
||||
NotAutoStarted,
|
||||
UpgradeIncomplete,
|
||||
}
|
||||
|
||||
/// The release installer registers AutoStart.
|
||||
@@ -66,9 +67,46 @@ pub(crate) fn notify_service_fallback(reason: &str) {
|
||||
Handle::notice(NoticeStatus::ServiceCoreSidecarFallback, "");
|
||||
}
|
||||
|
||||
/// Written by the Linux packages when an upgrade found the Service and may not have kept it.
|
||||
#[cfg(target_os = "linux")]
|
||||
const SERVICE_UPGRADE_MARKER: &str = "/run/clash-verge-service-upgrade";
|
||||
const SERVICE_UPGRADE_INCOMPLETE: &str = "the package upgrade did not keep the Service ready";
|
||||
|
||||
/// Offers a reinstall once per package upgrade whose Service is not ready, since package script output never reaches the app.
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(crate) async fn notify_incomplete_service_upgrade() {
|
||||
let Ok(marker) = std::fs::read_to_string(SERVICE_UPGRADE_MARKER) else {
|
||||
return;
|
||||
};
|
||||
let Some(id) = marker.lines().find_map(|line| line.strip_prefix("id=")) else {
|
||||
return;
|
||||
};
|
||||
let ack = match dirs::app_home_dir() {
|
||||
Ok(dir) => dir.join("service-upgrade-ack"),
|
||||
Err(error) => {
|
||||
logging!(warn, Type::Service, "无法定位服务升级确认文件: {error:#}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
if std::fs::read_to_string(&ack).is_ok_and(|seen| seen == id) {
|
||||
return;
|
||||
}
|
||||
let status = SERVICE_MANAGER.current().await;
|
||||
if !matches!(status, ServiceStatus::Ready) {
|
||||
logging!(warn, Type::Service, "安装包升级后服务未就绪: {status:?}");
|
||||
*PENDING_SERVICE_FALLBACK_NOTICE.lock() = Some(SERVICE_UPGRADE_INCOMPLETE.to_owned());
|
||||
Handle::notice(NoticeStatus::ServiceCoreSidecarFallback, "");
|
||||
}
|
||||
if let Err(error) = std::fs::write(&ack, id) {
|
||||
logging!(warn, Type::Service, "无法记录服务升级确认: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn take_service_fallback_notice() -> Option<ServiceFallbackNotice> {
|
||||
let reason = PENDING_SERVICE_FALLBACK_NOTICE.lock().take()?;
|
||||
Some(if reason.starts_with(CORE_REJECTED_PREFIX) {
|
||||
Some(if reason == SERVICE_UPGRADE_INCOMPLETE {
|
||||
ServiceFallbackNotice::UpgradeIncomplete
|
||||
} else if reason.starts_with(CORE_REJECTED_PREFIX) {
|
||||
ServiceFallbackNotice::CoreRejected(reason)
|
||||
} else if is_not_auto_started(&reason) {
|
||||
ServiceFallbackNotice::NotAutoStarted
|
||||
|
||||
@@ -293,35 +293,60 @@ impl SilentUpdater {
|
||||
}
|
||||
|
||||
async fn install(update: Update, bytes: Vec<u8>, timeout: Option<Duration>) -> Result<()> {
|
||||
// The package scripts reinstall an existing Service, killing the core it runs and its session;
|
||||
// stopping it first keeps the post-update restart from failing on that lost session.
|
||||
#[cfg(target_os = "linux")]
|
||||
let stopped_service_core = crate::core::CoreManager::global()
|
||||
.stop_service_core()
|
||||
.await
|
||||
.context("failed to stop the Service core before installing the update")?;
|
||||
|
||||
let install = tokio::task::spawn_blocking(move || update.install(&bytes));
|
||||
let mut install = Self::install_with_core_paused(update, bytes).await?;
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let mut install = tokio::task::spawn_blocking(move || update.install(&bytes));
|
||||
let joined = match timeout {
|
||||
Some(limit) => tokio::time::timeout(limit, install)
|
||||
.await
|
||||
.map_err(|_| anyhow::anyhow!("install timed out ({}s)", limit.as_secs())),
|
||||
Some(limit) => match tokio::time::timeout(limit, &mut install).await {
|
||||
Ok(joined) => Ok(joined),
|
||||
Err(_) => {
|
||||
// The caller resumes the old app; once the package manager succeeds, restart on the new version.
|
||||
#[cfg(target_os = "linux")]
|
||||
tokio::spawn(async move {
|
||||
if matches!(install.await, Ok(Ok(()))) {
|
||||
crate::feat::restart_app().await;
|
||||
}
|
||||
});
|
||||
Err(anyhow::anyhow!("install timed out ({}s)", limit.as_secs()))
|
||||
}
|
||||
},
|
||||
None => Ok(install.await),
|
||||
};
|
||||
let result = joined.and_then(|joined| Ok(joined??));
|
||||
joined.and_then(|joined| {
|
||||
joined??;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
if result.is_err()
|
||||
&& stopped_service_core
|
||||
&& let Err(error) = crate::core::CoreManager::global().start_core().await
|
||||
{
|
||||
logging!(
|
||||
error,
|
||||
Type::System,
|
||||
"Failed to restart the core after the update install failed: {error:#}"
|
||||
);
|
||||
}
|
||||
result
|
||||
/// The package scripts reinstall an existing Service, killing the core it runs and its session, so the
|
||||
/// core stays paused until the package manager exits, even after the caller stops waiting.
|
||||
#[cfg(target_os = "linux")]
|
||||
async fn install_with_core_paused(update: Update, bytes: Vec<u8>) -> Result<tokio::task::JoinHandle<Result<()>>> {
|
||||
let manager = crate::core::CoreManager::global();
|
||||
let (lifecycle, stopped_service_core) = manager
|
||||
.pause_for_package_install()
|
||||
.await
|
||||
.context("failed to stop the Service core before installing the update")?;
|
||||
let install = tokio::task::spawn_blocking(move || update.install(&bytes));
|
||||
Ok(tokio::spawn(async move {
|
||||
let result = match install.await {
|
||||
Ok(result) => result.map_err(anyhow::Error::from),
|
||||
Err(error) => Err(error.into()),
|
||||
};
|
||||
drop(lifecycle);
|
||||
if result.is_err()
|
||||
&& stopped_service_core
|
||||
&& let Err(error) = manager.start_core().await
|
||||
{
|
||||
logging!(
|
||||
error,
|
||||
Type::System,
|
||||
"Failed to restart the core after the update install failed: {error:#}"
|
||||
);
|
||||
}
|
||||
result
|
||||
}))
|
||||
}
|
||||
|
||||
/// Installs a newer cached update before normal startup, if the user confirms.
|
||||
|
||||
@@ -78,6 +78,8 @@ async fn resolve_setup() {
|
||||
|
||||
let core_init = AsyncHandler::spawn(|| async {
|
||||
init_core_manager().await;
|
||||
#[cfg(target_os = "linux")]
|
||||
crate::core::service::notify_incomplete_service_upgrade().await;
|
||||
});
|
||||
|
||||
let _ = futures::join!(
|
||||
|
||||
Reference in New Issue
Block a user