fix: check the cli running state

This commit is contained in:
Kevin Yue 2025-01-22 14:12:14 +08:00
parent 5186e80c6f
commit 2f90b73683
No known key found for this signature in database
GPG Key ID: 4D3A6EE977B15AC4

View File

@ -1,17 +1,21 @@
use std::{env::temp_dir, fs::File}; use std::{env::temp_dir, fs::File, str::FromStr};
use anyhow::bail;
use clap::{Parser, Subcommand}; use clap::{Parser, Subcommand};
use gpapi::{ use gpapi::{
clap::{handle_error, Args, InfoLevelVerbosity}, clap::{handle_error, Args, InfoLevelVerbosity},
utils::openssl, utils::openssl,
}; };
use log::info; use log::info;
use sysinfo::{Pid, System};
use tempfile::NamedTempFile; use tempfile::NamedTempFile;
use tokio::fs;
use crate::{ use crate::{
connect::{ConnectArgs, ConnectHandler}, connect::{ConnectArgs, ConnectHandler},
disconnect::{DisconnectArgs, DisconnectHandler}, disconnect::{DisconnectArgs, DisconnectHandler},
launch_gui::{LaunchGuiArgs, LaunchGuiHandler}, launch_gui::{LaunchGuiArgs, LaunchGuiHandler},
GP_CLIENT_LOCK_FILE,
}; };
const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", compile_time::date_str!(), ")"); const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), " (", compile_time::date_str!(), ")");
@ -77,6 +81,25 @@ impl Args for Cli {
} }
impl Cli { impl Cli {
async fn is_running(&self) -> bool {
let Ok(c) = fs::read_to_string(GP_CLIENT_LOCK_FILE).await else {
return false;
};
let Ok(pid) = Pid::from_str(c.trim()) else {
return false;
};
let s = System::new_all();
let Some(p) = s.process(pid) else {
return false;
};
p.exe()
.map(|exe| exe.to_string_lossy().contains("gpclient"))
.unwrap_or(false)
}
fn fix_openssl(&self) -> anyhow::Result<Option<NamedTempFile>> { fn fix_openssl(&self) -> anyhow::Result<Option<NamedTempFile>> {
if self.fix_openssl { if self.fix_openssl {
let file = openssl::fix_openssl_env()?; let file = openssl::fix_openssl_env()?;
@ -87,6 +110,11 @@ impl Cli {
} }
async fn run(&self) -> anyhow::Result<()> { async fn run(&self) -> anyhow::Result<()> {
// check if an instance is running
if self.is_running().await {
bail!("Another instance of the client is already running");
}
// The temp file will be dropped automatically when the file handle is dropped // The temp file will be dropped automatically when the file handle is dropped
// So, declare it here to ensure it's not dropped // So, declare it here to ensure it's not dropped
let _file = self.fix_openssl()?; let _file = self.fix_openssl()?;