Skip to content

Commit

Permalink
feat: move events to process watcher (#1301)
Browse files Browse the repository at this point in the history
Co-authored-by: brianp <[email protected]>
  • Loading branch information
stringhandler and brianp authored Dec 20, 2024
1 parent 1c89064 commit b302808
Show file tree
Hide file tree
Showing 11 changed files with 232 additions and 262 deletions.
6 changes: 3 additions & 3 deletions src-tauri/src/binaries/binaries_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ use super::{
Binaries,
};

use log::{error, info, warn};
use log::{debug, error, info, warn};

pub const LOG_TARGET: &str = "tari::universe::binary_manager";

Expand Down Expand Up @@ -102,7 +102,7 @@ impl BinaryManager {
VersionReq::default()
});

info!(target: LOG_TARGET, "Version requirements for {:?}: {:?}", binary_name, version_requirement);
debug!(target: LOG_TARGET, "Version requirements for {:?}: {:?}", binary_name, version_requirement);

version_requirement
}
Expand Down Expand Up @@ -514,7 +514,7 @@ impl BinaryManager {
}

pub async fn read_local_versions(&mut self) {
info!(target: LOG_TARGET,"Reading local versions for binary: {:?}", self.binary_name);
debug!(target: LOG_TARGET,"Reading local versions for binary: {:?}", self.binary_name);

let binary_folder = match self.adapter.get_binary_folder() {
Ok(path) => path,
Expand Down
83 changes: 26 additions & 57 deletions src-tauri/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,13 @@ use crate::external_dependencies::{
use crate::gpu_miner_adapter::{GpuMinerStatus, GpuNodeSource};
use crate::hardware::hardware_status_monitor::{HardwareStatusMonitor, PublicDeviceProperties};
use crate::internal_wallet::{InternalWallet, PaperWalletConfig};
use crate::node_manager::NodeManagerError;
use crate::p2pool::models::{Connections, Stats};
use crate::progress_tracker::ProgressTracker;
use crate::tor_adapter::TorConfig;
use crate::utils::shutdown_utils::stop_all_processes;
use crate::wallet_adapter::{TransactionInfo, WalletBalance};
use crate::wallet_manager::WalletManagerError;
use crate::{setup_inner, UniverseAppState, APPLICATION_FOLDER_ID};
use crate::{node_adapter, setup_inner, UniverseAppState, APPLICATION_FOLDER_ID};

use base64::prelude::*;
use keyring::Entry;
Expand All @@ -54,7 +53,6 @@ use std::sync::atomic::Ordering;
use std::thread::{available_parallelism, sleep};
use std::time::{Duration, Instant, SystemTime};
use tari_common::configuration::Network;
use tari_core::transactions::tari_amount::MicroMinotari;
use tauri::{Manager, PhysicalPosition, PhysicalSize};
use tauri_plugin_sentry::sentry;
use tauri_plugin_sentry::sentry::protocol::Event;
Expand Down Expand Up @@ -398,18 +396,27 @@ pub async fn get_miner_metrics(
}
state.is_getting_miner_metrics.store(true, Ordering::SeqCst);

let (sha_hash_rate, randomx_hash_rate, block_reward, block_height, block_time, is_synced) = state.node_manager
.get_network_hash_rate_and_block_reward().await
.unwrap_or_else(|e| {
if !matches!(e, NodeManagerError::NodeNotStarted) {
warn!(target: LOG_TARGET, "Error getting network hash rate and block reward: {}", e);
}
(0, 0, MicroMinotari(0), 0, 0, false)
});
let node_status = state.base_node_latest_status.borrow().clone();
let node_adapter::BaseNodeStatus {
sha_network_hashrate,
randomx_network_hashrate,
block_height,
block_time,
is_synced,
block_reward,
} = node_status;
// let (sha_hash_rate, randomx_hash_rate, block_reward, block_height, block_time, is_synced) = state.node_manager
// .get_network_hash_rate_and_block_reward().await
// .unwrap_or_else(|e| {
// if !matches!(e, NodeManagerError::NodeNotStarted) {
// warn!(target: LOG_TARGET, "Error getting network hash rate and block reward: {}", e);
// }
// (0, 0, MicroMinotari(0), 0, 0, false)
// });

let cpu_miner = state.cpu_miner.read().await;
let cpu_mining_status = match cpu_miner
.status(randomx_hash_rate, block_reward)
.status(randomx_network_hashrate, block_reward)
.await
.map_err(|e| e.to_string())
{
Expand All @@ -424,18 +431,7 @@ pub async fn get_miner_metrics(
};
drop(cpu_miner);

let gpu_miner = state.gpu_miner.read().await;
let gpu_mining_status = match gpu_miner.status(sha_hash_rate, block_reward).await {
Ok(gpu) => gpu,
Err(e) => {
warn!(target: LOG_TARGET, "Error getting gpu miner status: {:?}", e);
state
.is_getting_miner_metrics
.store(false, Ordering::SeqCst);
return Err(e.to_string());
}
};
drop(gpu_miner);
let gpu_mining_status = state.gpu_latest_status.borrow().clone();

let gpu_public_parameters = HardwareStatusMonitor::current()
.get_gpu_devices_public_properties()
Expand All @@ -453,8 +449,8 @@ pub async fn get_miner_metrics(
}

let metrics_ret = MinerMetrics {
sha_network_hash_rate: sha_hash_rate,
randomx_network_hash_rate: randomx_hash_rate,
sha_network_hash_rate: sha_network_hashrate,
randomx_network_hash_rate: randomx_network_hashrate,
cpu: CpuMinerMetrics {
// hardware: cpu_public_parameters.clone(),
mining: cpu_mining_status,
Expand Down Expand Up @@ -670,43 +666,16 @@ pub async fn get_tari_wallet_details(
state: tauri::State<'_, UniverseAppState>,
) -> Result<TariWalletDetails, String> {
let timer = Instant::now();
if state.is_getting_wallet_balance.load(Ordering::SeqCst) {
let read = state.cached_wallet_details.read().await;
if let Some(details) = &*read {
warn!(target: LOG_TARGET, "Already getting wallet balance, returning cached value");
return Ok(details.clone());
}
warn!(target: LOG_TARGET, "Already getting wallet balance");
return Err("Already getting wallet balance".to_string());
}
state
.is_getting_wallet_balance
.store(true, Ordering::SeqCst);
let wallet_balance = match state.wallet_manager.get_balance().await {
Ok(w) => Some(w),
Err(e) => {
if !matches!(e, WalletManagerError::WalletNotStarted) {
warn!(target: LOG_TARGET, "Error getting wallet balance: {}", e);
}

None
}
};
let tari_address = state.tari_address.read().await;

if timer.elapsed() > MAX_ACCEPTABLE_COMMAND_TIME {
warn!(target: LOG_TARGET, "get_tari_wallet_details took too long: {:?}", timer.elapsed());
}
let wallet_balance = state.wallet_latest_balance.borrow().clone();
let result = TariWalletDetails {
wallet_balance,
tari_address_base58: tari_address.to_base58(),
tari_address_emoji: tari_address.to_emoji_string(),
};
let mut lock = state.cached_wallet_details.write().await;
*lock = Some(result.clone());
state
.is_getting_wallet_balance
.store(false, Ordering::SeqCst);
if timer.elapsed() > MAX_ACCEPTABLE_COMMAND_TIME {
warn!(target: LOG_TARGET, "get_tari_wallet_details took too long: {:?}", timer.elapsed());
}

Ok(result)
}
Expand Down
64 changes: 9 additions & 55 deletions src-tauri/src/gpu_miner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,13 @@
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

use std::{path::PathBuf, sync::Arc};

use log::info;
use serde::Deserialize;
use std::time::Duration;
use std::{path::PathBuf, sync::Arc};
use tari_common_types::tari_address::TariAddress;
use tari_core::transactions::tari_amount::MicroMinotari;
use tari_shutdown::ShutdownSignal;
use tokio::sync::RwLock;
use tokio::sync::{watch, RwLock};

use crate::app_config::GpuThreads;
use crate::binaries::{Binaries, BinaryResolver};
Expand All @@ -39,7 +38,6 @@ use crate::{
process_watcher::ProcessWatcher,
};

const SHA_BLOCKS_PER_DAY: u64 = 360;
const LOG_TARGET: &str = "tari::universe::gpu_miner";

#[derive(Debug, Deserialize)]
Expand All @@ -66,9 +64,12 @@ pub(crate) struct GpuMiner {
}

impl GpuMiner {
pub fn new() -> Self {
let adapter = GpuMinerAdapter::new(vec![]);
let process_watcher = ProcessWatcher::new(adapter);
pub fn new(status_broadcast: watch::Sender<GpuMinerStatus>) -> Self {
let adapter = GpuMinerAdapter::new(vec![], status_broadcast);
let mut process_watcher = ProcessWatcher::new(adapter);
process_watcher.health_timeout = Duration::from_secs(9);
process_watcher.poll_time = Duration::from_secs(10);

Self {
watcher: Arc::new(RwLock::new(process_watcher)),
is_available: false,
Expand Down Expand Up @@ -135,53 +136,6 @@ impl GpuMiner {
lock.is_pid_file_exists(base_path)
}

pub async fn status(
&self,
network_hash_rate: u64,
block_reward: MicroMinotari,
) -> Result<GpuMinerStatus, anyhow::Error> {
let process_watcher = self.watcher.read().await;
if !process_watcher.is_running() {
return Ok(GpuMinerStatus {
hash_rate: 0,
estimated_earnings: 0,
is_mining: false,
is_available: self.is_available,
});
}
match &process_watcher.status_monitor {
Some(status_monitor) => {
let mut status = status_monitor.status().await?;
let hash_rate = status.hash_rate;
let estimated_earnings = if network_hash_rate == 0 {
0
} else {
#[allow(clippy::cast_possible_truncation)]
{
((block_reward.as_u64() as f64)
* (hash_rate as f64 / network_hash_rate as f64)
* (SHA_BLOCKS_PER_DAY as f64))
.floor() as u64
}
};
// Can't be more than the max reward for a day
let estimated_earnings = std::cmp::min(
estimated_earnings,
block_reward.as_u64() * SHA_BLOCKS_PER_DAY,
);
status.estimated_earnings = estimated_earnings;
status.is_available = self.is_available;
Ok(status)
}
None => Ok(GpuMinerStatus {
hash_rate: 0,
estimated_earnings: 0,
is_mining: false,
is_available: self.is_available,
}),
}
}

pub async fn detect(&mut self, config_dir: PathBuf) -> Result<(), anyhow::Error> {
info!(target: LOG_TARGET, "Verify if gpu miner can work on the system");

Expand Down
18 changes: 11 additions & 7 deletions src-tauri/src/gpu_miner_adapter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ use std::time::Instant;
use tari_common::configuration::Network;
use tari_common_types::tari_address::TariAddress;
use tari_shutdown::Shutdown;
use tokio::sync::watch;

#[cfg(target_os = "windows")]
use crate::utils::setup_utils::setup_utils::add_firewall_rule;
Expand All @@ -60,10 +61,14 @@ pub(crate) struct GpuMinerAdapter {
pub(crate) coinbase_extra: String,
pub(crate) excluded_gpu_devices: Vec<u8>,
pub(crate) gpu_devices: Vec<GpuConfig>,
latest_status_broadcast: watch::Sender<GpuMinerStatus>,
}

impl GpuMinerAdapter {
pub fn new(gpu_devices: Vec<GpuConfig>) -> Self {
pub fn new(
gpu_devices: Vec<GpuConfig>,
latest_status_broadcast: watch::Sender<GpuMinerStatus>,
) -> Self {
Self {
tari_address: TariAddress::default(),
gpu_grid_size: gpu_devices
Expand All @@ -77,6 +82,7 @@ impl GpuMinerAdapter {
coinbase_extra: "tari-universe".to_string(),
excluded_gpu_devices: vec![],
gpu_devices,
latest_status_broadcast,
}
}

Expand Down Expand Up @@ -233,6 +239,7 @@ impl ProcessAdapter for GpuMinerAdapter {
GpuMinerStatusMonitor {
http_api_port,
start_time: Instant::now(),
latest_status_broadcast: self.latest_status_broadcast.clone(),
},
))
}
Expand All @@ -250,12 +257,14 @@ impl ProcessAdapter for GpuMinerAdapter {
pub struct GpuMinerStatusMonitor {
http_api_port: u16,
start_time: Instant,
latest_status_broadcast: watch::Sender<GpuMinerStatus>,
}

#[async_trait]
impl StatusMonitor for GpuMinerStatusMonitor {
async fn check_health(&self) -> HealthStatus {
if let Ok(status) = self.status().await {
let _result = self.latest_status_broadcast.send(status.clone());
// GPU returns 0 for first 10 seconds until it has an average
if status.hash_rate > 0 || self.start_time.elapsed().as_secs() < 11 {
HealthStatus::Healthy
Expand Down Expand Up @@ -285,14 +294,12 @@ impl GpuMinerStatusMonitor {
is_mining: false,
hash_rate: 0,
estimated_earnings: 0,
is_available: false,
});
}
return Ok(GpuMinerStatus {
is_mining: false,
hash_rate: 0,
estimated_earnings: 0,
is_available: false,
});
}
};
Expand All @@ -305,7 +312,6 @@ impl GpuMinerStatusMonitor {
is_mining: false,
hash_rate: 0,
estimated_earnings: 0,
is_available: false,
});
}
};
Expand All @@ -314,7 +320,6 @@ impl GpuMinerStatusMonitor {
is_mining: true,
estimated_earnings: 0,
hash_rate: body.total_hashrate.ten_seconds.unwrap_or(0.0) as u64,
is_available: true,
})
}
}
Expand All @@ -334,10 +339,9 @@ pub(crate) struct AverageHashrate {
one_minute: Option<f64>,
}

#[derive(Debug, Serialize, Clone)]
#[derive(Debug, Serialize, Clone, Default)]
pub(crate) struct GpuMinerStatus {
pub is_mining: bool,
pub hash_rate: u64,
pub estimated_earnings: u64,
pub is_available: bool,
}
Loading

0 comments on commit b302808

Please sign in to comment.