From 04885f0a4c4152500213df82bfdf909e818334d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marcin=20Papie=C5=BC?= Date: Fri, 9 Aug 2024 13:34:08 +0200 Subject: [PATCH 1/8] chore(refactor): reuse more code in adapters --- src-tauri/src/cpu_miner.rs | 2 +- src-tauri/src/merge_mining_adapter.rs | 43 +------------- src-tauri/src/node_adapter.rs | 46 ++------------- src-tauri/src/process_adapter.rs | 48 +++++++++++++--- src-tauri/src/process_killer.rs | 7 +++ src-tauri/src/wallet_adapter.rs | 46 ++------------- src-tauri/src/xmrig_adapter.rs | 81 +++++++++++---------------- 7 files changed, 93 insertions(+), 180 deletions(-) diff --git a/src-tauri/src/cpu_miner.rs b/src-tauri/src/cpu_miner.rs index 2dc0bb05d..fb70e7e54 100644 --- a/src-tauri/src/cpu_miner.rs +++ b/src-tauri/src/cpu_miner.rs @@ -97,7 +97,7 @@ impl CpuMiner { select! { _ = watch_timer.tick() => { println!("watching"); - if xmrig_child.ping().expect("idk") { + if xmrig_child.ping() { println!("xmrig is running"); } else { println!("xmrig is not running"); diff --git a/src-tauri/src/merge_mining_adapter.rs b/src-tauri/src/merge_mining_adapter.rs index 581e3a16f..d99b6bb7f 100644 --- a/src-tauri/src/merge_mining_adapter.rs +++ b/src-tauri/src/merge_mining_adapter.rs @@ -3,13 +3,12 @@ use crate::process_adapter::{ProcessAdapter, ProcessInstance, StatusMonitor}; use anyhow::Error; use async_trait::async_trait; use log::{debug, warn}; +use log::warn; use std::fs; use std::path::PathBuf; use tari_common_types::tari_address::TariAddress; use tari_shutdown::Shutdown; -use tokio::runtime::Handle; use tokio::select; -use tokio::task::JoinHandle; const LOG_TARGET: &str = "tari::universe::merge_mining_proxy_adapter"; @@ -26,13 +25,12 @@ impl MergeMiningProxyAdapter { } impl ProcessAdapter for MergeMiningProxyAdapter { - type Instance = MergeMiningProxyInstance; type StatusMonitor = MergeMiningProxyStatusMonitor; fn spawn_inner( &self, data_dir: PathBuf, - ) -> Result<(Self::Instance, Self::StatusMonitor), Error> { + ) -> Result<(ProcessInstance, Self::StatusMonitor), Error> { let inner_shutdown = Shutdown::new(); let shutdown_signal = inner_shutdown.to_signal(); @@ -55,7 +53,7 @@ impl ProcessAdapter for MergeMiningProxyAdapter { "merge_mining_proxy.wait_for_initial_sync_at_startup=false".to_string(), ]; Ok(( - MergeMiningProxyInstance { + ProcessInstance { shutdown: inner_shutdown, handle: Some(tokio::spawn(async move { let file_path = BinaryResolver::current() @@ -117,41 +115,6 @@ impl ProcessAdapter for MergeMiningProxyAdapter { } } -pub struct MergeMiningProxyInstance { - pub shutdown: Shutdown, - handle: Option>>, -} - pub struct MergeMiningProxyStatusMonitor {} -#[async_trait] -impl ProcessInstance for MergeMiningProxyInstance { - fn ping(&self) -> bool { - self.handle - .as_ref() - .map(|m| !m.is_finished()) - .unwrap_or_else(|| false) - } - - async fn stop(&mut self) -> Result { - self.shutdown.trigger(); - let handle = self.handle.take(); - let res = handle.unwrap().await??; - Ok(res) - } -} -impl Drop for MergeMiningProxyInstance { - fn drop(&mut self) { - println!("Drop being called"); - self.shutdown.trigger(); - if let Some(handle) = self.handle.take() { - Handle::current().block_on(async move { - let _ = handle.await.unwrap().map_err(|e| { - warn!(target: LOG_TARGET, "Error in MergeMiningProxyInstance: {}", e); - }); - }); - } - } -} - impl StatusMonitor for MergeMiningProxyStatusMonitor {} diff --git a/src-tauri/src/node_adapter.rs b/src-tauri/src/node_adapter.rs index 4768015ed..39d918cd7 100644 --- a/src-tauri/src/node_adapter.rs +++ b/src-tauri/src/node_adapter.rs @@ -7,6 +7,10 @@ use async_trait::async_trait; use humantime::format_duration; use log::{debug, info, warn}; use minotari_node_grpc_client::grpc::{Empty, HeightRequest, NewBlockTemplateRequest, PowAlgo}; +use log::{info, warn}; +use minotari_node_grpc_client::grpc::{ + Empty, HeightRequest, NewBlockTemplateRequest, PowAlgo, +}; use minotari_node_grpc_client::BaseNodeGrpcClient; use std::fs; use std::path::PathBuf; @@ -15,7 +19,6 @@ use tari_core::transactions::tari_amount::MicroMinotari; use tari_crypto::ristretto::RistrettoPublicKey; use tari_shutdown::Shutdown; use tari_utilities::ByteArray; -use tokio::runtime::Handle; use tokio::select; use tokio::task::JoinHandle; @@ -32,13 +35,12 @@ impl MinotariNodeAdapter { } impl ProcessAdapter for MinotariNodeAdapter { - type Instance = MinotariNodeInstance; type StatusMonitor = MinotariNodeStatusMonitor; fn spawn_inner( &self, data_dir: PathBuf, - ) -> Result<(Self::Instance, Self::StatusMonitor), Error> { + ) -> Result<(ProcessInstance, Self::StatusMonitor), Error> { let inner_shutdown = Shutdown::new(); let shutdown_signal = inner_shutdown.to_signal(); @@ -76,7 +78,7 @@ impl ProcessAdapter for MinotariNodeAdapter { ); } Ok(( - MinotariNodeInstance { + ProcessInstance { shutdown: inner_shutdown, handle: Some(tokio::spawn(async move { let file_path = BinaryResolver::current() @@ -138,42 +140,6 @@ impl ProcessAdapter for MinotariNodeAdapter { } } -pub struct MinotariNodeInstance { - pub shutdown: Shutdown, - handle: Option>>, -} - -#[async_trait] -impl ProcessInstance for MinotariNodeInstance { - fn ping(&self) -> bool { - self.handle - .as_ref() - .map(|m| !m.is_finished()) - .unwrap_or_else(|| false) - } - - async fn stop(&mut self) -> Result { - self.shutdown.trigger(); - let handle = self.handle.take(); - let res = handle.unwrap().await??; - Ok(res) - } -} - -impl Drop for MinotariNodeInstance { - fn drop(&mut self) { - println!("Drop being called"); - self.shutdown.trigger(); - if let Some(handle) = self.handle.take() { - Handle::current().block_on(async move { - let _ = handle.await.unwrap().map_err(|e| { - warn!(target: LOG_TARGET, "Error stopping minotari node: {:?}", e); - e - }); - }); - } - } -} pub struct MinotariNodeStatusMonitor {} impl StatusMonitor for MinotariNodeStatusMonitor {} diff --git a/src-tauri/src/process_adapter.rs b/src-tauri/src/process_adapter.rs index e460d052a..9844becfb 100644 --- a/src-tauri/src/process_adapter.rs +++ b/src-tauri/src/process_adapter.rs @@ -2,25 +2,28 @@ use crate::process_killer::kill_process; use anyhow::Error; use async_trait::async_trait; use log::{info, warn}; +use log::warn; +use tokio::runtime::Handle; use std::fs; use std::path::PathBuf; +use tari_shutdown::Shutdown; +use tokio::task::JoinHandle; const LOG_TARGET: &str = "tari::universe::process_adapter"; pub trait ProcessAdapter { - type Instance: ProcessInstance; type StatusMonitor: StatusMonitor; // fn spawn(&self) -> Result<(Receiver<()>, TInstance), anyhow::Error>; fn spawn_inner( &self, base_folder: PathBuf, - ) -> Result<(Self::Instance, Self::StatusMonitor), anyhow::Error>; + ) -> Result<(ProcessInstance, Self::StatusMonitor), anyhow::Error>; fn name(&self) -> &str; fn spawn( &self, base_folder: PathBuf, - ) -> Result<(Self::Instance, Self::StatusMonitor), anyhow::Error> { + ) -> Result<(ProcessInstance, Self::StatusMonitor), anyhow::Error> { self.spawn_inner(base_folder) } @@ -34,7 +37,7 @@ pub trait ProcessAdapter { kill_process(pid)?; } Err(e) => { - warn!(target: LOG_TARGET, "Could not read node's pid file: {}", e); + warn!(target: LOG_TARGET, "Could not read {} pid file: {}", self.pid_file_name(), e); } } Ok(()) @@ -43,8 +46,37 @@ pub trait ProcessAdapter { pub trait StatusMonitor {} -#[async_trait] -pub trait ProcessInstance: Send + Sync + 'static { - fn ping(&self) -> bool; - async fn stop(&mut self) -> Result; +pub struct ProcessInstance { + pub shutdown: Shutdown, + pub handle: Option>>, } + +impl ProcessInstance { + pub fn ping(&self) -> bool { + self + .handle + .as_ref() + .map(|m| !m.is_finished()) + .unwrap_or_else(|| false) + } + + pub async fn stop(&mut self) -> Result<(), anyhow::Error> { + self.shutdown.trigger(); + let handle = self.handle.take(); + handle.unwrap().await? + } +} + +impl Drop for ProcessInstance { + fn drop(&mut self) { + println!("Drop being called"); + self.shutdown.trigger(); + if let Some(handle) = self.handle.take() { + Handle::current().block_on(async move { + let _ = handle.await.unwrap().map_err(|e| { + warn!(target: LOG_TARGET, "Error in {}: {}", self.name(), e); + }); + }); + } + } +} \ No newline at end of file diff --git a/src-tauri/src/process_killer.rs b/src-tauri/src/process_killer.rs index d21b9a136..2375f0d99 100644 --- a/src-tauri/src/process_killer.rs +++ b/src-tauri/src/process_killer.rs @@ -4,6 +4,13 @@ use std::process::Command; const LOG_TARGET: &str = "tari::universe::process_killer"; pub fn kill_process(pid: u32) -> Result<(), anyhow::Error> { + #[cfg(target_os = "linux")] + { + let _ = Command::new("kill") + .args(&["-9", &pid.to_string()]) + .output()?; + } + #[cfg(target_os = "windows")] { let output = Command::new("taskkill") diff --git a/src-tauri/src/wallet_adapter.rs b/src-tauri/src/wallet_adapter.rs index bdf03f7c5..e8ae8449b 100644 --- a/src-tauri/src/wallet_adapter.rs +++ b/src-tauri/src/wallet_adapter.rs @@ -3,6 +3,7 @@ use crate::process_adapter::{ProcessAdapter, ProcessInstance, StatusMonitor}; use anyhow::Error; use async_trait::async_trait; use log::{debug, info, warn}; +use log::{info, warn}; use minotari_node_grpc_client::grpc::wallet_client::WalletClient; use minotari_node_grpc_client::grpc::GetBalanceRequest; use serde::Serialize; @@ -12,9 +13,7 @@ use tari_core::transactions::tari_amount::MicroMinotari; use tari_crypto::ristretto::RistrettoPublicKey; use tari_shutdown::Shutdown; use tari_utilities::hex::Hex; -use tokio::runtime::Handle; use tokio::select; -use tokio::task::JoinHandle; const LOG_TARGET: &str = "tari::universe::wallet_adapter"; @@ -39,12 +38,12 @@ impl WalletAdapter { } impl ProcessAdapter for WalletAdapter { - type Instance = WalletInstance; type StatusMonitor = WalletStatusMonitor; + fn spawn_inner( &self, data_dir: PathBuf, - ) -> Result<(Self::Instance, Self::StatusMonitor), Error> { + ) -> Result<(ProcessInstance, Self::StatusMonitor), Error> { // TODO: This was copied from node_adapter. This should be DRY'ed up let inner_shutdown = Shutdown::new(); let shutdown_signal = inner_shutdown.to_signal(); @@ -97,7 +96,7 @@ impl ProcessAdapter for WalletAdapter { args.push("wallet.p2p.transport.tor.proxy_bypass_for_outbound_tcp=false".to_string()) } Ok(( - WalletInstance { + ProcessInstance { shutdown: inner_shutdown, handle: Some(tokio::spawn(async move { let file_path = BinaryResolver::current() @@ -158,43 +157,6 @@ impl ProcessAdapter for WalletAdapter { } } -pub struct WalletInstance { - pub shutdown: Shutdown, - handle: Option>>, -} - -#[async_trait] -impl ProcessInstance for WalletInstance { - fn ping(&self) -> bool { - self.handle - .as_ref() - .map(|m| !m.is_finished()) - .unwrap_or_else(|| false) - } - - async fn stop(&mut self) -> Result { - self.shutdown.trigger(); - let handle = self.handle.take(); - let res = handle.unwrap().await??; - Ok(res) - } -} - -impl Drop for WalletInstance { - fn drop(&mut self) { - println!("Drop being called"); - self.shutdown.trigger(); - if let Some(handle) = self.handle.take() { - Handle::current().block_on(async move { - let _ = handle.await.unwrap().map_err(|e| { - warn!(target: LOG_TARGET, "Error stopping wallet: {:?}", e); - e - }); - }); - } - } -} - pub struct WalletStatusMonitor {} impl StatusMonitor for WalletStatusMonitor {} diff --git a/src-tauri/src/xmrig_adapter.rs b/src-tauri/src/xmrig_adapter.rs index 4fc8b5911..978f923dc 100644 --- a/src-tauri/src/xmrig_adapter.rs +++ b/src-tauri/src/xmrig_adapter.rs @@ -1,6 +1,6 @@ use crate::cpu_miner::CpuMinerEvent; use crate::download_utils::{download_file, extract}; -use crate::process_killer::kill_process; +use crate::process_adapter::{ProcessAdapter, ProcessInstance, StatusMonitor}; use crate::xmrig::http_api::XmrigHttpApiClient; use crate::xmrig::latest_release::fetch_latest_release; use crate::ProgressTracker; @@ -9,9 +9,7 @@ use log::{debug, info, warn}; use std::path::PathBuf; use tari_shutdown::Shutdown; use tokio::fs; -use tokio::runtime::Handle; use tokio::sync::mpsc::Receiver; -use tokio::task::JoinHandle; const LOG_TARGET: &str = "tari::universe::xmrig_adapter"; @@ -46,11 +44,6 @@ pub struct XmrigAdapter { http_api_port: u16, } -pub struct XmrigInstance { - shutdown: Shutdown, - handle: Option>>, -} - impl XmrigAdapter { pub fn new(xmrig_node_connection: XmrigNodeConnection, monero_address: String) -> Self { Self { @@ -67,8 +60,8 @@ impl XmrigAdapter { logs_dir: PathBuf, data_dir: PathBuf, progress_tracker: ProgressTracker, - cpu_max_percentage: usize, - ) -> Result<(Receiver, XmrigInstance, XmrigHttpApiClient), anyhow::Error> { + cpu_max_percentage: u16, + ) -> Result<(Receiver, ProcessInstance, XmrigHttpApiClient), anyhow::Error> { self.kill_previous_instances(data_dir.clone())?; let (_tx, rx) = tokio::sync::mpsc::channel(100); @@ -92,7 +85,7 @@ impl XmrigAdapter { Ok(( rx, - XmrigInstance { + ProcessInstance { shutdown: xmrig_shutdown, handle: Some(tokio::spawn(async move { // TODO: Ensure version string is not malicious @@ -177,52 +170,42 @@ impl XmrigAdapter { Ok(latest_release.version) } - - fn kill_previous_instances(&self, base_folder: PathBuf) -> Result<(), Error> { - match std::fs::read_to_string(base_folder.join("xmrig_pid")) { - Ok(pid) => { - let pid = pid.trim().parse::()?; - kill_process(pid)?; - } - Err(e) => { - warn!(target: LOG_TARGET, "Could not read xmrigs pid file: {}", e); - } - } - Ok(()) - } } -impl XmrigInstance { - pub fn ping(&self) -> Result { - Ok(self - .handle - .as_ref() - .map(|m| !m.is_finished()) - .unwrap_or_else(|| false)) +impl ProcessAdapter for XmrigAdapter { + type StatusMonitor = XmrigStatusMonitor; + + // It's not used, it's just to follow the trait + fn spawn_inner( + &self, + base_folder: PathBuf, + _window: tauri::Window, + ) -> Result<(ProcessInstance, Self::StatusMonitor), anyhow::Error> { + self.kill_previous_instances(base_folder.clone())?; + + // TODO: HOW TO NOT CREATE INSTANCE? + let instance = ProcessInstance { + shutdown: Shutdown::new(), + handle: None, + }; + + Ok((instance, XmrigStatusMonitor {})) } - pub async fn stop(&mut self) -> Result<(), anyhow::Error> { - self.shutdown.trigger(); - let handle = self.handle.take(); - handle.unwrap().await? + fn name(&self) -> &str { + "xmrig" } - pub fn kill(&self) -> Result<(), anyhow::Error> { - todo!() - // Ok(()) + + fn pid_file_name(&self) -> &str { + "xmrig_pid" } } -impl Drop for XmrigInstance { - fn drop(&mut self) { - println!("Drop being called"); - self.shutdown.trigger(); - if let Some(handle) = self.handle.take() { - Handle::current().block_on(async move { - let _ = handle.await.unwrap().map_err(|e| { - warn!(target: LOG_TARGET, "Error in XmrigInstance: {}", e); - }); - }); - } +pub struct XmrigStatusMonitor {} + +impl StatusMonitor for XmrigStatusMonitor { + fn status(&self) -> Result<(), Error> { + todo!() } } From cb69674c358a880a58b85e0c0f48896b4961d136 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marcin=20Papie=C5=BC?= Date: Fri, 9 Aug 2024 13:43:57 +0200 Subject: [PATCH 2/8] cleanup --- src-tauri/src/node_adapter.rs | 1 - src-tauri/src/xmrig_adapter.rs | 5 ++--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/src-tauri/src/node_adapter.rs b/src-tauri/src/node_adapter.rs index 39d918cd7..7b05cc569 100644 --- a/src-tauri/src/node_adapter.rs +++ b/src-tauri/src/node_adapter.rs @@ -3,7 +3,6 @@ use crate::node_manager::NodeIdentity; use crate::process_adapter::{ProcessAdapter, ProcessInstance, StatusMonitor}; use crate::ProgressTracker; use anyhow::{anyhow, Error}; -use async_trait::async_trait; use humantime::format_duration; use log::{debug, info, warn}; use minotari_node_grpc_client::grpc::{Empty, HeightRequest, NewBlockTemplateRequest, PowAlgo}; diff --git a/src-tauri/src/xmrig_adapter.rs b/src-tauri/src/xmrig_adapter.rs index 978f923dc..b70f7f62c 100644 --- a/src-tauri/src/xmrig_adapter.rs +++ b/src-tauri/src/xmrig_adapter.rs @@ -112,8 +112,8 @@ impl XmrigAdapter { match std::fs::remove_file(data_dir.join("xmrig_pid")) { Ok(_) => {} - Err(_e) => { - debug!(target: LOG_TARGET, "Could not clear xmrig's pid file"); + Err(e) => { + warn!(target: LOG_TARGET, "Could not clear xmrig's pid file {:?}", e); } } @@ -179,7 +179,6 @@ impl ProcessAdapter for XmrigAdapter { fn spawn_inner( &self, base_folder: PathBuf, - _window: tauri::Window, ) -> Result<(ProcessInstance, Self::StatusMonitor), anyhow::Error> { self.kill_previous_instances(base_folder.clone())?; From d9a036fffa27feaed693c1043c78fcd1e785321b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marcin=20Papie=C5=BC?= Date: Fri, 9 Aug 2024 13:46:09 +0200 Subject: [PATCH 3/8] fix fmt --- src-tauri/src/node_adapter.rs | 4 +--- src-tauri/src/process_adapter.rs | 7 +++---- 2 files changed, 4 insertions(+), 7 deletions(-) diff --git a/src-tauri/src/node_adapter.rs b/src-tauri/src/node_adapter.rs index 7b05cc569..876bdd2ca 100644 --- a/src-tauri/src/node_adapter.rs +++ b/src-tauri/src/node_adapter.rs @@ -7,9 +7,7 @@ use humantime::format_duration; use log::{debug, info, warn}; use minotari_node_grpc_client::grpc::{Empty, HeightRequest, NewBlockTemplateRequest, PowAlgo}; use log::{info, warn}; -use minotari_node_grpc_client::grpc::{ - Empty, HeightRequest, NewBlockTemplateRequest, PowAlgo, -}; +use minotari_node_grpc_client::grpc::{Empty, HeightRequest, NewBlockTemplateRequest, PowAlgo}; use minotari_node_grpc_client::BaseNodeGrpcClient; use std::fs; use std::path::PathBuf; diff --git a/src-tauri/src/process_adapter.rs b/src-tauri/src/process_adapter.rs index 9844becfb..c1a8a957c 100644 --- a/src-tauri/src/process_adapter.rs +++ b/src-tauri/src/process_adapter.rs @@ -3,10 +3,10 @@ use anyhow::Error; use async_trait::async_trait; use log::{info, warn}; use log::warn; -use tokio::runtime::Handle; use std::fs; use std::path::PathBuf; use tari_shutdown::Shutdown; +use tokio::runtime::Handle; use tokio::task::JoinHandle; const LOG_TARGET: &str = "tari::universe::process_adapter"; @@ -53,8 +53,7 @@ pub struct ProcessInstance { impl ProcessInstance { pub fn ping(&self) -> bool { - self - .handle + self.handle .as_ref() .map(|m| !m.is_finished()) .unwrap_or_else(|| false) @@ -79,4 +78,4 @@ impl Drop for ProcessInstance { }); } } -} \ No newline at end of file +} From 4f405c0e26dabcde0c986c1f9388870cb64a73f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marcin=20Papie=C5=BC?= Date: Fri, 9 Aug 2024 13:47:22 +0200 Subject: [PATCH 4/8] remove linux kill process --- src-tauri/src/process_killer.rs | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/src-tauri/src/process_killer.rs b/src-tauri/src/process_killer.rs index 2375f0d99..83015c0f8 100644 --- a/src-tauri/src/process_killer.rs +++ b/src-tauri/src/process_killer.rs @@ -4,13 +4,6 @@ use std::process::Command; const LOG_TARGET: &str = "tari::universe::process_killer"; pub fn kill_process(pid: u32) -> Result<(), anyhow::Error> { - #[cfg(target_os = "linux")] - { - let _ = Command::new("kill") - .args(&["-9", &pid.to_string()]) - .output()?; - } - #[cfg(target_os = "windows")] { let output = Command::new("taskkill") @@ -27,7 +20,7 @@ pub fn kill_process(pid: u32) -> Result<(), anyhow::Error> { use nix::unistd::Pid; let pid = Pid::from_raw(pid as i32); - signal::kill(pid, Signal::SIGTERM); + let _ = signal::kill(pid, Signal::SIGTERM); } Ok(()) } From 653f6940148f97f30a2d80d1d314f98cf71a5db1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marcin=20Papie=C5=BC?= Date: Fri, 9 Aug 2024 14:02:04 +0200 Subject: [PATCH 5/8] use spawn_inner inside spawn --- src-tauri/src/xmrig_adapter.rs | 74 ++++++++++++++++------------------ 1 file changed, 35 insertions(+), 39 deletions(-) diff --git a/src-tauri/src/xmrig_adapter.rs b/src-tauri/src/xmrig_adapter.rs index b70f7f62c..1521e77ec 100644 --- a/src-tauri/src/xmrig_adapter.rs +++ b/src-tauri/src/xmrig_adapter.rs @@ -62,8 +62,8 @@ impl XmrigAdapter { progress_tracker: ProgressTracker, cpu_max_percentage: u16, ) -> Result<(Receiver, ProcessInstance, XmrigHttpApiClient), anyhow::Error> { - self.kill_previous_instances(data_dir.clone())?; - + let (instance, _) = self.spawn_inner(data_dir.clone())?; + let mut process_instance = instance; let (_tx, rx) = tokio::sync::mpsc::channel(100); let force_download = self.force_download; let xmrig_shutdown = Shutdown::new(); @@ -83,43 +83,42 @@ impl XmrigAdapter { self.http_api_token.clone(), ); - Ok(( - rx, - ProcessInstance { - shutdown: xmrig_shutdown, - handle: Some(tokio::spawn(async move { - // TODO: Ensure version string is not malicious - let version = - Self::ensure_latest(cache_dir.clone(), force_download, progress_tracker) - .await?; - let xmrig_dir = cache_dir - .join("xmrig") - .join(&version) - .join(format!("xmrig-{}", version)); - let xmrig_bin = xmrig_dir.join("xmrig"); - let mut xmrig = tokio::process::Command::new(xmrig_bin) - .args(args) - .kill_on_drop(true) - .spawn()?; - - if let Some(id) = xmrig.id() { - std::fs::write(data_dir.join("xmrig_pid"), id.to_string())?; - } - shutdown_signal.wait().await; - println!("Stopping xmrig"); + process_instance.handle = Some(tokio::spawn(async move { + // TODO: Ensure version string is not malicious + let version = + Self::ensure_latest(cache_dir.clone(), force_download, progress_tracker) + .await?; + let xmrig_dir = cache_dir + .join("xmrig") + .join(&version) + .join(format!("xmrig-{}", version)); + let xmrig_bin = xmrig_dir.join("xmrig"); + let mut xmrig = tokio::process::Command::new(xmrig_bin) + .args(args) + .kill_on_drop(true) + .spawn()?; + + if let Some(id) = xmrig.id() { + std::fs::write(data_dir.join("xmrig_pid"), id.to_string())?; + } + shutdown_signal.wait().await; + println!("Stopping xmrig"); - xmrig.kill().await?; + xmrig.kill().await?; - match std::fs::remove_file(data_dir.join("xmrig_pid")) { - Ok(_) => {} - Err(e) => { - warn!(target: LOG_TARGET, "Could not clear xmrig's pid file {:?}", e); - } - } + match std::fs::remove_file(data_dir.join("xmrig_pid")) { + Ok(_) => {} + Err(e) => { + warn!(target: LOG_TARGET, "Could not clear xmrig's pid file {:?}", e); + } + } + + Ok(()) + })); - Ok(()) - })), - }, + Ok(( + rx, + process_instance, client, )) } @@ -175,14 +174,11 @@ impl XmrigAdapter { impl ProcessAdapter for XmrigAdapter { type StatusMonitor = XmrigStatusMonitor; - // It's not used, it's just to follow the trait fn spawn_inner( &self, base_folder: PathBuf, ) -> Result<(ProcessInstance, Self::StatusMonitor), anyhow::Error> { self.kill_previous_instances(base_folder.clone())?; - - // TODO: HOW TO NOT CREATE INSTANCE? let instance = ProcessInstance { shutdown: Shutdown::new(), handle: None, From 0499ec5ff72275c543969a2169f905145bc35c97 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marcin=20Papie=C5=BC?= Date: Fri, 9 Aug 2024 14:07:01 +0200 Subject: [PATCH 6/8] fix fmt --- src-tauri/src/xmrig_adapter.rs | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/src-tauri/src/xmrig_adapter.rs b/src-tauri/src/xmrig_adapter.rs index 1521e77ec..a72cd600e 100644 --- a/src-tauri/src/xmrig_adapter.rs +++ b/src-tauri/src/xmrig_adapter.rs @@ -86,8 +86,7 @@ impl XmrigAdapter { process_instance.handle = Some(tokio::spawn(async move { // TODO: Ensure version string is not malicious let version = - Self::ensure_latest(cache_dir.clone(), force_download, progress_tracker) - .await?; + Self::ensure_latest(cache_dir.clone(), force_download, progress_tracker).await?; let xmrig_dir = cache_dir .join("xmrig") .join(&version) @@ -116,11 +115,7 @@ impl XmrigAdapter { Ok(()) })); - Ok(( - rx, - process_instance, - client, - )) + Ok((rx, process_instance, client)) } pub async fn ensure_latest( From cd9ddf6dfa03a3dcc974f02ae831eeabe38d29e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marcin=20Papie=C5=BC?= Date: Fri, 9 Aug 2024 18:34:49 +0200 Subject: [PATCH 7/8] move spawn_inner args to the new --- src-tauri/src/cpu_miner.rs | 13 ++- src-tauri/src/xmrig_adapter.rs | 165 ++++++++++++++++++--------------- 2 files changed, 97 insertions(+), 81 deletions(-) diff --git a/src-tauri/src/cpu_miner.rs b/src-tauri/src/cpu_miner.rs index fb70e7e54..b8dbfd801 100644 --- a/src-tauri/src/cpu_miner.rs +++ b/src-tauri/src/cpu_miner.rs @@ -1,4 +1,6 @@ use crate::app_config::MiningMode; +use crate::mm_proxy_manager::MmProxyManager; +use crate::process_adapter::ProcessAdapter; use crate::xmrig::http_api::XmrigHttpApiClient; use crate::xmrig_adapter::{XmrigAdapter, XmrigNodeConnection}; use crate::{ @@ -76,17 +78,14 @@ impl CpuMiner { }; let xmrig = XmrigAdapter::new( xmrig_node_connection, - "44AFFq5kSiGBoZ4NMDwYtN18obc8AemS33DBLWs3H7otXft3XjrpDtQGv7SqSsaBYBb98uNbr2VBBEt7f2wfn3RVGQBEP3A".to_string() - ); - let (mut _rx, mut xmrig_child, client) = xmrig.spawn( + "44AFFq5kSiGBoZ4NMDwYtN18obc8AemS33DBLWs3H7otXft3XjrpDtQGv7SqSsaBYBb98uNbr2VBBEt7f2wfn3RVGQBEP3A".to_string(), cache_dir, log_dir, - base_path, progress_tracker, cpu_max_percentage, - )?; - - self.api_client = Some(client); + ); + let (mut xmrig_child, _xmrig_status_monitor) = xmrig.spawn_inner(base_path.clone())?; + self.api_client = Some(xmrig.client); self.watcher_task = Some(tauri::async_runtime::spawn(async move { println!("Starting process"); diff --git a/src-tauri/src/xmrig_adapter.rs b/src-tauri/src/xmrig_adapter.rs index a72cd600e..5a12b8759 100644 --- a/src-tauri/src/xmrig_adapter.rs +++ b/src-tauri/src/xmrig_adapter.rs @@ -39,84 +39,46 @@ pub struct XmrigAdapter { force_download: bool, node_connection: XmrigNodeConnection, monero_address: String, - // TODO: secure http_api_token: String, http_api_port: u16, + cache_dir: PathBuf, + logs_dir: PathBuf, + cpu_max_percentage: usize, + progress_tracker: ProgressTracker, + rx: Receiver, + pub client: XmrigHttpApiClient, + // TODO: secure } impl XmrigAdapter { - pub fn new(xmrig_node_connection: XmrigNodeConnection, monero_address: String) -> Self { + pub fn new( + xmrig_node_connection: XmrigNodeConnection, + monero_address: String, + cache_dir: PathBuf, + logs_dir: PathBuf, + progress_tracker: ProgressTracker, + cpu_max_percentage: usize, + ) -> Self { + let (_tx, rx) = tokio::sync::mpsc::channel(100); + let http_api_port = 9090; + let http_api_token = "pass".to_string(); Self { force_download: false, node_connection: xmrig_node_connection, monero_address, - http_api_token: "pass".to_string(), - http_api_port: 9090, + http_api_token: http_api_token.clone(), + http_api_port: http_api_port.clone(), + cache_dir, + logs_dir, + cpu_max_percentage, + progress_tracker, + rx, + client: XmrigHttpApiClient::new( + format!("http://127.0.0.1:{}", http_api_port).clone(), + http_api_token.clone(), + ), } } - pub fn spawn( - &self, - cache_dir: PathBuf, - logs_dir: PathBuf, - data_dir: PathBuf, - progress_tracker: ProgressTracker, - cpu_max_percentage: u16, - ) -> Result<(Receiver, ProcessInstance, XmrigHttpApiClient), anyhow::Error> { - let (instance, _) = self.spawn_inner(data_dir.clone())?; - let mut process_instance = instance; - let (_tx, rx) = tokio::sync::mpsc::channel(100); - let force_download = self.force_download; - let xmrig_shutdown = Shutdown::new(); - let mut shutdown_signal = xmrig_shutdown.to_signal(); - let mut args = self.node_connection.generate_args(); - let xmrig_log_file = logs_dir.join("xmrig.log"); - std::fs::create_dir_all(xmrig_log_file.parent().unwrap())?; - args.push(format!("--log-file={}", &xmrig_log_file.to_str().unwrap())); - args.push(format!("--http-port={}", self.http_api_port)); - args.push(format!("--http-access-token={}", self.http_api_token)); - args.push("--donate-level=1".to_string()); - args.push(format!("--user={}", self.monero_address)); - args.push(format!("--threads={}", cpu_max_percentage)); - - let client = XmrigHttpApiClient::new( - format!("http://127.0.0.1:{}", self.http_api_port), - self.http_api_token.clone(), - ); - - process_instance.handle = Some(tokio::spawn(async move { - // TODO: Ensure version string is not malicious - let version = - Self::ensure_latest(cache_dir.clone(), force_download, progress_tracker).await?; - let xmrig_dir = cache_dir - .join("xmrig") - .join(&version) - .join(format!("xmrig-{}", version)); - let xmrig_bin = xmrig_dir.join("xmrig"); - let mut xmrig = tokio::process::Command::new(xmrig_bin) - .args(args) - .kill_on_drop(true) - .spawn()?; - - if let Some(id) = xmrig.id() { - std::fs::write(data_dir.join("xmrig_pid"), id.to_string())?; - } - shutdown_signal.wait().await; - println!("Stopping xmrig"); - - xmrig.kill().await?; - - match std::fs::remove_file(data_dir.join("xmrig_pid")) { - Ok(_) => {} - Err(e) => { - warn!(target: LOG_TARGET, "Could not clear xmrig's pid file {:?}", e); - } - } - - Ok(()) - })); - - Ok((rx, process_instance, client)) - } pub async fn ensure_latest( cache_dir: PathBuf, @@ -171,15 +133,70 @@ impl ProcessAdapter for XmrigAdapter { fn spawn_inner( &self, - base_folder: PathBuf, + data_dir: PathBuf, ) -> Result<(ProcessInstance, Self::StatusMonitor), anyhow::Error> { - self.kill_previous_instances(base_folder.clone())?; - let instance = ProcessInstance { - shutdown: Shutdown::new(), - handle: None, - }; + self.kill_previous_instances(data_dir.clone())?; + + let cache_dir = self.cache_dir.clone(); + let progress_tracker = self.progress_tracker.clone(); + let force_download = self.force_download; + let xmrig_shutdown = Shutdown::new(); + let mut shutdown_signal = xmrig_shutdown.to_signal(); + let mut args = self.node_connection.generate_args(); + let xmrig_log_file = self.logs_dir.join("xmrig.log"); + std::fs::create_dir_all(xmrig_log_file.parent().unwrap())?; + args.push(format!("--log-file={}", &xmrig_log_file.to_str().unwrap())); + args.push(format!("--http-port={}", self.http_api_port)); + args.push(format!("--http-access-token={}", self.http_api_token)); + args.push(format!("--donate-level=1")); + args.push(format!("--user={}", self.monero_address)); + args.push(format!( + "--cpu-max-threads-hint={}", + self.cpu_max_percentage + )); + + Ok(( + ProcessInstance { + shutdown: xmrig_shutdown, + handle: Some(tokio::spawn(async move { + // TODO: Ensure version string is not malicious + let version = Self::ensure_latest( + cache_dir.clone(), + force_download, + progress_tracker.clone(), + ) + .await?; + let xmrig_dir = cache_dir + .clone() + .join("xmrig") + .join(&version) + .join(format!("xmrig-{}", version)); + let xmrig_bin = xmrig_dir.join("xmrig"); + let mut xmrig = tokio::process::Command::new(xmrig_bin) + .args(args) + .kill_on_drop(true) + .spawn()?; + + if let Some(id) = xmrig.id() { + std::fs::write(data_dir.join("xmrig_pid"), id.to_string())?; + } + shutdown_signal.wait().await; + println!("Stopping xmrig"); + + xmrig.kill().await?; + + match std::fs::remove_file(data_dir.join("xmrig_pid")) { + Ok(_) => {} + Err(e) => { + warn!(target: LOG_TARGET, "Could not clear xmrig's pid file - {e}"); + } + } - Ok((instance, XmrigStatusMonitor {})) + Ok(()) + })), + }, + XmrigStatusMonitor {}, + )) } fn name(&self) -> &str { From df2b33eaf3c2aa6fb644e55fa6dd6d7d32d110f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marcin=20Papie=C5=BC?= Date: Wed, 21 Aug 2024 11:41:26 +0200 Subject: [PATCH 8/8] Adjust to the new main --- src-tauri/src/cpu_miner.rs | 2 +- src-tauri/src/merge_mining_adapter.rs | 2 -- src-tauri/src/node_adapter.rs | 3 --- src-tauri/src/process_adapter.rs | 8 +++----- src-tauri/src/wallet_adapter.rs | 2 -- src-tauri/src/xmrig_adapter.rs | 10 +++------- 6 files changed, 7 insertions(+), 20 deletions(-) diff --git a/src-tauri/src/cpu_miner.rs b/src-tauri/src/cpu_miner.rs index b8dbfd801..50e1d67b7 100644 --- a/src-tauri/src/cpu_miner.rs +++ b/src-tauri/src/cpu_miner.rs @@ -101,7 +101,7 @@ impl CpuMiner { } else { println!("xmrig is not running"); match xmrig_child.stop().await { - Ok(()) => { + Ok(_) => { println!("xmrig exited successfully"); } Err(e) => { diff --git a/src-tauri/src/merge_mining_adapter.rs b/src-tauri/src/merge_mining_adapter.rs index d99b6bb7f..dfa4cc5d5 100644 --- a/src-tauri/src/merge_mining_adapter.rs +++ b/src-tauri/src/merge_mining_adapter.rs @@ -1,9 +1,7 @@ use crate::binary_resolver::{Binaries, BinaryResolver}; use crate::process_adapter::{ProcessAdapter, ProcessInstance, StatusMonitor}; use anyhow::Error; -use async_trait::async_trait; use log::{debug, warn}; -use log::warn; use std::fs; use std::path::PathBuf; use tari_common_types::tari_address::TariAddress; diff --git a/src-tauri/src/node_adapter.rs b/src-tauri/src/node_adapter.rs index 876bdd2ca..e0c569fbf 100644 --- a/src-tauri/src/node_adapter.rs +++ b/src-tauri/src/node_adapter.rs @@ -6,8 +6,6 @@ use anyhow::{anyhow, Error}; use humantime::format_duration; use log::{debug, info, warn}; use minotari_node_grpc_client::grpc::{Empty, HeightRequest, NewBlockTemplateRequest, PowAlgo}; -use log::{info, warn}; -use minotari_node_grpc_client::grpc::{Empty, HeightRequest, NewBlockTemplateRequest, PowAlgo}; use minotari_node_grpc_client::BaseNodeGrpcClient; use std::fs; use std::path::PathBuf; @@ -17,7 +15,6 @@ use tari_crypto::ristretto::RistrettoPublicKey; use tari_shutdown::Shutdown; use tari_utilities::ByteArray; use tokio::select; -use tokio::task::JoinHandle; const LOG_TARGET: &str = "tari::universe::minotari_node_adapter"; diff --git a/src-tauri/src/process_adapter.rs b/src-tauri/src/process_adapter.rs index c1a8a957c..faebbf33c 100644 --- a/src-tauri/src/process_adapter.rs +++ b/src-tauri/src/process_adapter.rs @@ -1,8 +1,6 @@ use crate::process_killer::kill_process; use anyhow::Error; -use async_trait::async_trait; use log::{info, warn}; -use log::warn; use std::fs; use std::path::PathBuf; use tari_shutdown::Shutdown; @@ -48,7 +46,7 @@ pub trait StatusMonitor {} pub struct ProcessInstance { pub shutdown: Shutdown, - pub handle: Option>>, + pub handle: Option>>, } impl ProcessInstance { @@ -59,7 +57,7 @@ impl ProcessInstance { .unwrap_or_else(|| false) } - pub async fn stop(&mut self) -> Result<(), anyhow::Error> { + pub async fn stop(&mut self) -> Result { self.shutdown.trigger(); let handle = self.handle.take(); handle.unwrap().await? @@ -73,7 +71,7 @@ impl Drop for ProcessInstance { if let Some(handle) = self.handle.take() { Handle::current().block_on(async move { let _ = handle.await.unwrap().map_err(|e| { - warn!(target: LOG_TARGET, "Error in {}: {}", self.name(), e); + warn!(target: LOG_TARGET, "Error in Process Adapter: {}", e); }); }); } diff --git a/src-tauri/src/wallet_adapter.rs b/src-tauri/src/wallet_adapter.rs index e8ae8449b..b878fa7cc 100644 --- a/src-tauri/src/wallet_adapter.rs +++ b/src-tauri/src/wallet_adapter.rs @@ -1,9 +1,7 @@ use crate::binary_resolver::{Binaries, BinaryResolver}; use crate::process_adapter::{ProcessAdapter, ProcessInstance, StatusMonitor}; use anyhow::Error; -use async_trait::async_trait; use log::{debug, info, warn}; -use log::{info, warn}; use minotari_node_grpc_client::grpc::wallet_client::WalletClient; use minotari_node_grpc_client::grpc::GetBalanceRequest; use serde::Serialize; diff --git a/src-tauri/src/xmrig_adapter.rs b/src-tauri/src/xmrig_adapter.rs index 5a12b8759..9b14d12b8 100644 --- a/src-tauri/src/xmrig_adapter.rs +++ b/src-tauri/src/xmrig_adapter.rs @@ -5,7 +5,7 @@ use crate::xmrig::http_api::XmrigHttpApiClient; use crate::xmrig::latest_release::fetch_latest_release; use crate::ProgressTracker; use anyhow::Error; -use log::{debug, info, warn}; +use log::{info, warn}; use std::path::PathBuf; use tari_shutdown::Shutdown; use tokio::fs; @@ -192,7 +192,7 @@ impl ProcessAdapter for XmrigAdapter { } } - Ok(()) + Ok(0) })), }, XmrigStatusMonitor {}, @@ -210,11 +210,7 @@ impl ProcessAdapter for XmrigAdapter { pub struct XmrigStatusMonitor {} -impl StatusMonitor for XmrigStatusMonitor { - fn status(&self) -> Result<(), Error> { - todo!() - } -} +impl StatusMonitor for XmrigStatusMonitor {} #[allow(unreachable_code)] fn get_os_string_id() -> String {