refactor: only run single instance of server

This commit is contained in:
Kevin Yue 2023-05-14 13:15:57 +08:00
parent 6df9877895
commit 16696e3840
2 changed files with 14 additions and 2 deletions

View File

@ -81,6 +81,7 @@ async fn handle_status_change(
response_tx: mpsc::Sender<Response>,
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<VpnStatus>, response_tx: &mpsc::Sender<Response>) {
let status = *status_rx.borrow();
println!("received = {:?}", status);
if let Err(err) = response_tx
.send(Response::from(ResponseData::Status(status)))
.await

View File

@ -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<dyn std::error::Error>> {
if Path::new(&self.socket_path).exists() {
fs::remove_file(&self.socket_path).await?;
@ -65,6 +72,11 @@ pub async fn run(
) -> Result<(), Box<dyn std::error::Error>> {
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 {