From 16696e3840528936b2ce3fd3904efc255fc403ed Mon Sep 17 00:00:00 2001 From: Kevin Yue Date: Sun, 14 May 2023 13:15:57 +0800 Subject: [PATCH] refactor: only run single instance of server --- common/src/connection.rs | 2 +- common/src/server.rs | 14 +++++++++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/common/src/connection.rs b/common/src/connection.rs index d228055..0bd71ab 100644 --- a/common/src/connection.rs +++ b/common/src/connection.rs @@ -81,6 +81,7 @@ async fn handle_status_change( response_tx: mpsc::Sender, cancel_token: CancellationToken, ) { + // Send the initial status send_status(&status_rx, &response_tx).await; println!("Waiting for status change"); let start_time = std::time::Instant::now(); @@ -104,7 +105,6 @@ async fn handle_status_change( async fn send_status(status_rx: &watch::Receiver, response_tx: &mpsc::Sender) { let status = *status_rx.borrow(); - println!("received = {:?}", status); if let Err(err) = response_tx .send(Response::from(ResponseData::Status(status))) .await diff --git a/common/src/server.rs b/common/src/server.rs index fd30bd9..b881643 100644 --- a/common/src/server.rs +++ b/common/src/server.rs @@ -1,6 +1,7 @@ use crate::{connection::handle_connection, vpn::Vpn}; use std::{future::Future, os::unix::prelude::PermissionsExt, path::Path, sync::Arc}; -use tokio::{fs, net::UnixListener}; +use tokio::fs; +use tokio::net::{UnixListener, UnixStream}; #[derive(Debug, Default)] pub(crate) struct ServerContext { @@ -26,6 +27,12 @@ impl Server { } } + // Check if an instance of the server is already running. + // by trying to connect to the socket. + async fn is_running(&self) -> bool { + UnixStream::connect(&self.socket_path).await.is_ok() + } + async fn start(&self) -> Result<(), Box> { if Path::new(&self.socket_path).exists() { fs::remove_file(&self.socket_path).await?; @@ -65,6 +72,11 @@ pub async fn run( ) -> Result<(), Box> { let server = Server::new(socket_path.to_string()); + if server.is_running().await { + println!("Server is already running"); + return Ok(()); + } + tokio::select! { res = server.start() => { if let Err(err) = res {