From 169eb4f49f3fd587e9c28f2209b2dd130425d866 Mon Sep 17 00:00:00 2001 From: Eskil Queseth Date: Fri, 26 Mar 2021 01:10:09 +0100 Subject: re-add check for live server --- mumd/src/main.rs | 36 ++++++++++++++++++++++-------------- 1 file changed, 22 insertions(+), 14 deletions(-) (limited to 'mumd/src/main.rs') diff --git a/mumd/src/main.rs b/mumd/src/main.rs index d4151e3..5b22089 100644 --- a/mumd/src/main.rs +++ b/mumd/src/main.rs @@ -5,12 +5,12 @@ mod network; mod notify; mod state; -use futures_util::StreamExt; +use futures_util::{SinkExt, StreamExt}; //use ipc_channel::ipc::{self, IpcOneShotServer, IpcSender}; use log::*; use mumlib::command::{Command, CommandResponse}; use mumlib::setup_logger; -use tokio::{join, net::UnixListener, sync::{mpsc, oneshot}}; +use tokio::{join, net::{UnixListener, UnixStream}, sync::{mpsc, oneshot}}; use tokio_util::codec::{FramedRead, FramedWrite, LengthDelimitedCodec}; use bytes::{BufMut, BytesMut}; @@ -25,24 +25,32 @@ async fn main() { notify::init(); // check if another instance is live - /*let (tx_client, rx_client) = - ipc::channel::>>().unwrap(); - if let Ok(server_name) = fs::read_to_string(mumlib::SOCKET_PATH) { - if let Ok(tx0) = IpcSender::connect(server_name) { - if tx0.send((Command::Ping, tx_client)).is_ok() { - match rx_client.recv() { - Ok(Ok(Some(CommandResponse::Pong))) => { + let connection = UnixStream::connect("/tmp/mumd").await; + match connection { + Ok(stream) => { + let (reader, writer) = stream.into_split(); + let mut reader = FramedRead::new(reader, LengthDelimitedCodec::new()); + let mut writer = FramedWrite::new(writer, LengthDelimitedCodec::new()); + let mut command = BytesMut::new(); + bincode::serialize_into((&mut command).writer(), &Command::Ping).unwrap(); + if let Ok(()) = writer.send(command.freeze()).await { + if let Some(Ok(buf)) = reader.next().await { + if let Ok(Ok::, mumlib::error::Error>(Some(CommandResponse::Pong))) = bincode::deserialize(&buf) { error!("Another instance of mumd is already running"); return; - }, - resp => { - warn!("Ping with weird response. Continuing..."); - debug!("Response was {:?}", resp); } } } + debug!("a dead socket was found, removing"); + tokio::fs::remove_file("/tmp/mumd").await.unwrap(); } - }*/ + Err(e) => { + if matches!(e.kind(), std::io::ErrorKind::ConnectionRefused) { + debug!("a dead socket was found, removing"); + tokio::fs::remove_file("/tmp/mumd").await.unwrap(); + } + } + } let (command_sender, command_receiver) = mpsc::unbounded_channel(); -- cgit v1.2.1