Skip to content
This repository has been archived by the owner on Jan 25, 2024. It is now read-only.

Commit

Permalink
feat: provide --peer argument
Browse files Browse the repository at this point in the history
The `add` command is extended to provide a `--peer` argument. It uses the `sn_peers_acquisition`
crate and thus parses them in the exact same way as `safenode`.
  • Loading branch information
jacderida committed Dec 5, 2023
1 parent 3a333ed commit 8464869
Show file tree
Hide file tree
Showing 6 changed files with 66 additions and 25 deletions.
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,13 @@ clap = { version = "4.4.6", features = ["derive", "env"]}
colored = "2.0.4"
color-eyre = "~0.6"
indicatif = { version = "0.17.5", features = ["tokio"] }
libp2p = { version="0.53" , features = [] }
libp2p-identity = { version="0.2.7", features = ["rand"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
service-manager = "0.5.1"
sn_node_rpc_client = "0.1.43"
sn_peers_acquisition = "0.1.10"
sn-releases = "0.1.1"
sysinfo = "0.29.10"
tokio = { version = "1.26", features = ["full"] }
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ As with other Safe-related components, Safenode Manager will shortly be availabl
- `--count`: Number of service instances to add. Optional. Default: 1.
- `--data-dir-path`: Path for the data directory. Optional, with platform-specific defaults.
- `--log-dir-path`: Path for the log directory. Optional, with platform-specific defaults.
- `--peer`: Provide the peer(s) for the node to connect to. Optional.
- `--user`: User account under which the service should run. Optional. Default: `safe`.
- `--version`: Version of `safenode` to add. Optional. Default: the latest version.
- Usage: `safenode-manager install [OPTIONS]`
Expand Down
25 changes: 20 additions & 5 deletions src/add_service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,18 @@ use crate::service::{ServiceConfig, ServiceControl};
use color_eyre::Result;
use colored::Colorize;
use indicatif::{ProgressBar, ProgressStyle};
use libp2p::Multiaddr;
use sn_releases::{get_running_platform, ArchiveType, ReleaseType, SafeReleaseRepositoryInterface};
use std::path::PathBuf;
use std::sync::Arc;

pub struct AddServiceOptions {
pub count: Option<u16>,
pub safenode_dir_path: PathBuf,
pub service_data_dir_path: PathBuf,
pub service_log_dir_path: PathBuf,
pub peers: Vec<Multiaddr>,
pub user: String,
pub count: Option<u16>,
pub version: Option<String>,
}

Expand Down Expand Up @@ -98,6 +100,7 @@ pub async fn add(
service_user: install_options.user.clone(),
log_dir_path: service_log_dir_path.clone(),
data_dir_path: service_data_dir_path.clone(),
peers: install_options.peers.clone(),
})?;

added_service_data.push((
Expand Down Expand Up @@ -249,6 +252,7 @@ mod tests {
.returning(|| Ok(8081))
.in_sequence(&mut seq);

// let peers: Vec<Multiaddr> = vec![];
mock_service_control
.expect_install()
.times(1)
Expand All @@ -260,17 +264,20 @@ mod tests {
service_user: "safe".to_string(),
log_dir_path: node_logs_dir.to_path_buf().join("safenode1"),
data_dir_path: node_data_dir.to_path_buf().join("safenode1"),
peers: vec![],
}))
.returning(|_| Ok(()))
.in_sequence(&mut seq);

println!("about to call add...");
add(
AddServiceOptions {
count: None,
safenode_dir_path: temp_dir.to_path_buf(),
service_data_dir_path: node_data_dir.to_path_buf(),
service_log_dir_path: node_logs_dir.to_path_buf(),
peers: vec![],
user: "safe".to_string(),
count: None,
version: None,
},
&mut node_registry,
Expand Down Expand Up @@ -378,6 +385,7 @@ mod tests {
service_user: "safe".to_string(),
log_dir_path: node_logs_dir.to_path_buf().join("safenode1"),
data_dir_path: node_data_dir.to_path_buf().join("safenode1"),
peers: vec![],
}))
.returning(|_| Ok(()))
.in_sequence(&mut seq);
Expand Down Expand Up @@ -405,6 +413,7 @@ mod tests {
service_user: "safe".to_string(),
log_dir_path: node_logs_dir.to_path_buf().join("safenode2"),
data_dir_path: node_data_dir.to_path_buf().join("safenode2"),
peers: vec![],
}))
.returning(|_| Ok(()))
.in_sequence(&mut seq);
Expand Down Expand Up @@ -432,17 +441,19 @@ mod tests {
service_user: "safe".to_string(),
log_dir_path: node_logs_dir.to_path_buf().join("safenode3"),
data_dir_path: node_data_dir.to_path_buf().join("safenode3"),
peers: vec![],
}))
.returning(|_| Ok(()))
.in_sequence(&mut seq);

add(
AddServiceOptions {
count: Some(3),
peers: vec![],
safenode_dir_path: temp_dir.to_path_buf(),
service_data_dir_path: node_data_dir.to_path_buf(),
service_log_dir_path: node_logs_dir.to_path_buf(),
user: "safe".to_string(),
count: Some(3),
version: None,
},
&mut node_registry,
Expand Down Expand Up @@ -573,17 +584,19 @@ mod tests {
service_user: "safe".to_string(),
log_dir_path: node_logs_dir.to_path_buf().join("safenode1"),
data_dir_path: node_data_dir.to_path_buf().join("safenode1"),
peers: vec![],
}))
.returning(|_| Ok(()))
.in_sequence(&mut seq);

add(
AddServiceOptions {
count: None,
peers: vec![],
safenode_dir_path: temp_dir.to_path_buf(),
service_data_dir_path: node_data_dir.to_path_buf(),
service_log_dir_path: node_logs_dir.to_path_buf(),
user: "safe".to_string(),
count: None,
version: Some(specific_version.to_string()),
},
&mut node_registry,
Expand Down Expand Up @@ -703,17 +716,19 @@ mod tests {
service_user: "safe".to_string(),
log_dir_path: node_logs_dir.to_path_buf().join("safenode2"),
data_dir_path: node_data_dir.to_path_buf().join("safenode2"),
peers: vec![],
}))
.returning(|_| Ok(()))
.in_sequence(&mut seq);

add(
AddServiceOptions {
count: None,
peers: vec![],
safenode_dir_path: temp_dir.to_path_buf(),
service_data_dir_path: node_data_dir.to_path_buf(),
service_log_dir_path: node_logs_dir.to_path_buf(),
user: "safe".to_string(),
count: None,
version: None,
},
&mut node_registry,
Expand Down
9 changes: 7 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ use clap::{Parser, Subcommand};
use color_eyre::{eyre::eyre, Help, Result};
use libp2p_identity::PeerId;
use sn_node_rpc_client::RpcClient;
use sn_peers_acquisition::{parse_peers_args, PeersArgs};
use sn_releases::SafeReleaseRepositoryInterface;
use std::path::PathBuf;
use std::str::FromStr;
Expand Down Expand Up @@ -63,6 +64,8 @@ pub enum SubCmd {
/// - Windows: C:\ProgramData\safenode\logs
#[clap(long, verbatim_doc_comment)]
log_dir_path: Option<PathBuf>,
#[command(flatten)]
peers: PeersArgs,
/// The user the service should run as.
///
/// If the account does not exist, it will be created.
Expand Down Expand Up @@ -118,8 +121,9 @@ async fn main() -> Result<()> {
match args.cmd {
SubCmd::Add {
count,
log_dir_path,
data_dir_path,
log_dir_path,
peers,
user,
version,
} => {
Expand All @@ -144,11 +148,12 @@ async fn main() -> Result<()> {

add(
AddServiceOptions {
count,
peers: parse_peers_args(peers).await?,
safenode_dir_path: get_safenode_install_path()?,
service_data_dir_path,
service_log_dir_path,
user: service_user,
count,
version,
},
&mut node_registry,
Expand Down
36 changes: 26 additions & 10 deletions src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

use crate::config::create_owned_dir;
use color_eyre::Result;
use libp2p::Multiaddr;
#[cfg(test)]
use mockall::automock;
use service_manager::{
Expand All @@ -27,6 +28,7 @@ pub struct ServiceConfig {
pub service_user: String,
pub log_dir_path: PathBuf,
pub data_dir_path: PathBuf,
pub peers: Vec<Multiaddr>,
}

/// A thin wrapper around the `service_manager::ServiceManager`, which makes our own testing
Expand Down Expand Up @@ -156,24 +158,38 @@ impl ServiceControl for NodeServiceManager {

let label: ServiceLabel = config.name.parse()?;
let manager = <dyn ServiceManager>::native()?;
let mut args = vec![
OsString::from("--port"),
OsString::from(config.node_port.to_string()),
OsString::from("--rpc"),
OsString::from(format!("127.0.0.1:{}", config.rpc_port)),
OsString::from("--root-dir"),
OsString::from(config.data_dir_path.to_string_lossy().to_string()),
OsString::from("--log-output-dest"),
OsString::from(config.log_dir_path.to_string_lossy().to_string()),
];

if !config.peers.is_empty() {
let peers_str = config
.peers
.iter()
.map(|peer| peer.to_string())
.collect::<Vec<_>>()
.join(",");
args.push(OsString::from("--peer"));
args.push(OsString::from(peers_str));
}

manager.install(ServiceInstallCtx {
label: label.clone(),
program: config.safenode_path.to_path_buf(),
args: vec![
OsString::from("--port"),
OsString::from(config.node_port.to_string()),
OsString::from("--rpc"),
OsString::from(format!("127.0.0.1:{}", config.rpc_port)),
OsString::from("--root-dir"),
OsString::from(config.data_dir_path.to_string_lossy().to_string()),
OsString::from("--log-output-dest"),
OsString::from(config.log_dir_path.to_string_lossy().to_string()),
],
args,
contents: None,
username: Some(config.service_user.to_string()),
working_directory: None,
environment: None,
})?;

Ok(())
}

Expand Down
18 changes: 10 additions & 8 deletions tests/e2e.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,13 @@ fn cross_platform_service_install_and_control() {
// An explicit version of `safenode` will be used to avoid any rate limiting from Github when
// retrieving the latest version number.
let mut cmd = Command::cargo_bin("safenode-manager").unwrap();
cmd.arg("install")
cmd.arg("add")
.arg("--user")
.arg(CI_USER)
.arg("--count")
.arg("3")
.arg("--peer")
.arg("/ip4/127.0.0.1/tcp/46091/p2p/12D3KooWAWnbQLxqspWeB3M8HB3ab3CSj6FYzsJxEG9XdVnGNCod")
.arg("--version")
.arg("0.98.27")
.assert()
Expand All @@ -54,15 +56,15 @@ fn cross_platform_service_install_and_control() {

assert_eq!(service_status[0].name, "safenode1");
assert_eq!(service_status[0].peer_id, "-");
assert_eq!(service_status[0].status, "INSTALLED");
assert_eq!(service_status[0].status, "ADDED");
assert_eq!(service_status[1].name, "safenode2");
assert_eq!(service_status[1].peer_id, "-");
assert_eq!(service_status[1].status, "INSTALLED");
assert_eq!(service_status[1].status, "ADDED");
assert_eq!(service_status[2].name, "safenode3");
assert_eq!(service_status[2].peer_id, "-");
assert_eq!(service_status[2].status, "INSTALLED");
assert_eq!(service_status[2].status, "ADDED");

// Start each of the three installed services.
// Start each of the three services.
let mut cmd = Command::cargo_bin("safenode-manager").unwrap();
cmd.arg("start").assert().success();
let output = Command::cargo_bin("safenode-manager")
Expand All @@ -89,7 +91,7 @@ fn cross_platform_service_install_and_control() {
.map(|s| s.peer_id.clone())
.collect::<Vec<String>>();

// Stop each of the three installed services.
// Stop each of the three services.
let mut cmd = Command::cargo_bin("safenode-manager").unwrap();
cmd.arg("stop").assert().success();
let output = Command::cargo_bin("safenode-manager")
Expand All @@ -110,7 +112,7 @@ fn cross_platform_service_install_and_control() {
assert_eq!(stop_status[2].status, "STOPPED");
assert_eq!(stop_status[2].peer_id, peer_ids[2]);

// Start each of the three installed services again.
// Start each of the three services again.
let mut cmd = Command::cargo_bin("safenode-manager").unwrap();
cmd.arg("start").assert().success();
let output = Command::cargo_bin("safenode-manager")
Expand Down Expand Up @@ -181,7 +183,7 @@ fn cross_platform_service_install_and_control() {
assert_eq!(single_node_start_status[2].status, "RUNNING");
assert_eq!(single_node_start_status[2].peer_id, peer_ids[2]);

// Finally, stop each of the three installed services.
// Finally, stop each of the three services.
let mut cmd = Command::cargo_bin("safenode-manager").unwrap();
cmd.arg("stop").assert().success();
let output = Command::cargo_bin("safenode-manager")
Expand Down

0 comments on commit 8464869

Please sign in to comment.