Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

implementation of chain simulator features for sc-meta #1848

Merged
merged 5 commits into from
Nov 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions framework/meta/src/cli/cli_args_standalone.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,32 @@ pub enum StandaloneCliAction {
about = "Generates a new wallet or performs actions on an existing wallet."
)]
Wallet(WalletArgs),

#[command(
name = "cs",
about = "Can install, start and stop a chain simulator configuration."
)]
ChainSimulator(ChainSimulatorArgs),
}

#[derive(Clone, PartialEq, Eq, Debug, Args)]
pub struct ChainSimulatorArgs {
#[command(subcommand)]
pub command: ChainSimulatorCommand,
}

#[derive(Clone, PartialEq, Eq, Debug, Subcommand)]
pub enum ChainSimulatorCommand {
#[command(
about = "Pulls the latest chain simulator docker image available. Needs Docker installed."
)]
Install,

#[command(about = "Starts the chain simulator.")]
Start,

#[command(about = "Stops the chain simulator.")]
Stop,
}

#[derive(Default, Clone, PartialEq, Eq, Debug, Args)]
Expand Down
4 changes: 4 additions & 0 deletions framework/meta/src/cli/cli_standalone_main.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::cli::{StandaloneCliAction, StandaloneCliArgs};
use crate::cmd::chain_simulator::chain_simulator;
use crate::cmd::retrieve_address::retrieve_address;
use crate::cmd::wallet::wallet;
use clap::Parser;
Expand Down Expand Up @@ -50,6 +51,9 @@ pub async fn cli_main_standalone() {
Some(StandaloneCliAction::Wallet(args)) => {
wallet(args);
},
Some(StandaloneCliAction::ChainSimulator(args)) => {
chain_simulator(args);
},
None => {},
}
}
1 change: 1 addition & 0 deletions framework/meta/src/cmd.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
pub mod all;
pub mod chain_simulator;
pub mod code_report;
pub mod info;
pub mod install;
Expand Down
40 changes: 40 additions & 0 deletions framework/meta/src/cmd/chain_simulator.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
mod error;
mod install;
mod start;
mod stop;

use crate::cli::{ChainSimulatorArgs, ChainSimulatorCommand};
use std::process;

use install::install_and_check;
use start::start_and_check;
use stop::stop_and_check;

pub fn chain_simulator(args: &ChainSimulatorArgs) {
match args.command {
ChainSimulatorCommand::Install => cs_install(),
ChainSimulatorCommand::Start => cs_start(),
ChainSimulatorCommand::Stop => cs_stop(),
}
}

pub fn cs_install() {
if let Err(err) = install_and_check() {
eprintln!("{err}");
process::exit(1);
}
}

pub fn cs_start() {
if let Err(err) = start_and_check() {
eprintln!("{err}");
process::exit(1);
}
}

pub fn cs_stop() {
if let Err(err) = stop_and_check() {
eprintln!("{err}");
process::exit(1);
}
}
43 changes: 43 additions & 0 deletions framework/meta/src/cmd/chain_simulator/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
use colored::*;
use std::fmt;

pub const DOCKER_CMD: &str = "docker";
pub const SIMULATOR_IMAGE: &str = "multiversx/chainsimulator:latest";
pub const DEFAULT_PORT: &str = "8085:8085";

#[derive(Debug)]
pub enum ChainSimulatorError {
DockerNotInstalled,
CommandFailed(String),
OperationFailed(String),
ContainerNotRunning,
}

impl fmt::Display for ChainSimulatorError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ChainSimulatorError::DockerNotInstalled => {
write!(
f,
"{}",
"Error: Docker is not installed. Please install Docker to continue.".red()
)
},
ChainSimulatorError::CommandFailed(cmd) => {
write!(f, "{} {}", "Error: Failed to execute command:".red(), cmd)
},
ChainSimulatorError::OperationFailed(op) => {
write!(f, "{} {}", "Error: Operation failed:".red(), op)
},
ChainSimulatorError::ContainerNotRunning => {
write!(
f,
"{}",
"Warning: No running Chain Simulator container found.".yellow()
)
},
}
}
}

impl std::error::Error for ChainSimulatorError {}
34 changes: 34 additions & 0 deletions framework/meta/src/cmd/chain_simulator/install.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
use crate::cmd::chain_simulator::error::{ChainSimulatorError, DOCKER_CMD, SIMULATOR_IMAGE};
use colored::Colorize;
use std::process::Command;

pub fn install_and_check() -> Result<(), ChainSimulatorError> {
println!(
"{}",
"Attempting to install prerequisites for the Chain Simulator...".yellow()
);

if Command::new(DOCKER_CMD).arg("--version").output().is_err() {
return Err(ChainSimulatorError::DockerNotInstalled);
}

let output = Command::new(DOCKER_CMD)
.args(["image", "pull", SIMULATOR_IMAGE])
.output()
.map_err(|e| {
ChainSimulatorError::CommandFailed(format!(
"Failed to execute `{DOCKER_CMD} image pull {SIMULATOR_IMAGE}`. Cause: {e:#?}"
))
})?;

if output.status.success() {
println!(
"{}",
"Successfully pulled the latest Chain Simulator image.".green()
);
Ok(())
} else {
let stderr = String::from_utf8_lossy(&output.stderr);
Err(ChainSimulatorError::CommandFailed(stderr.to_string()))
}
}
57 changes: 57 additions & 0 deletions framework/meta/src/cmd/chain_simulator/start.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
use crate::cmd::chain_simulator::error::{
ChainSimulatorError, DEFAULT_PORT, DOCKER_CMD, SIMULATOR_IMAGE,
};
use colored::Colorize;
use std::io::{self, BufRead};
use std::process::{Command, Stdio};

pub fn start_and_check() -> Result<(), ChainSimulatorError> {
println!("{}", "Attempting to start the Chain Simulator...".yellow());

let mut child = Command::new(DOCKER_CMD)
.args(["run", "-p", DEFAULT_PORT, SIMULATOR_IMAGE])
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.map_err(|e| ChainSimulatorError::CommandFailed(format!(
"Failed to execute `{DOCKER_CMD} run -p {DEFAULT_PORT} {SIMULATOR_IMAGE}`. Cause: {e:#?}"
)))?;

println!("{}", "Successfully started the Chain Simulator.".green());

let stdout = child.stdout.take().ok_or_else(|| {
ChainSimulatorError::OperationFailed("Failed to capture stdout.".to_string())
})?;
let stderr = child.stderr.take().ok_or_else(|| {
ChainSimulatorError::OperationFailed("Failed to capture stderr.".to_string())
})?;

let stdout_reader = io::BufReader::new(stdout);
let stderr_reader = io::BufReader::new(stderr);

for line in stdout_reader.lines().map_while(Result::ok) {
println!("{line}");
}

let mut stderr_lines = Vec::new();
for line in stderr_reader.lines().map_while(Result::ok) {
eprintln!("{line}");
stderr_lines.push(line);
}

let status = child.wait().map_err(|e| {
ChainSimulatorError::OperationFailed(format!(
"Waiting for the container process to finish failed. Cause: {e:#?}"
))
})?;

if status.success() {
Ok(())
} else {
let stderr_msg = stderr_lines.join("\n");

Err(ChainSimulatorError::OperationFailed(format!(
"Chain Simulator execution failed. Exit status: {status}. Error stack trace: {stderr_msg}",
)))
}
}
44 changes: 44 additions & 0 deletions framework/meta/src/cmd/chain_simulator/stop.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
use crate::cmd::chain_simulator::error::{ChainSimulatorError, DOCKER_CMD, SIMULATOR_IMAGE};
use colored::Colorize;
use std::process::Command;

pub fn stop_and_check() -> Result<(), ChainSimulatorError> {
println!("{}", "Attempting to close the Chain Simulator...".yellow());

let output = Command::new(DOCKER_CMD)
.args(["ps", "-q", "--filter", format!("ancestor={SIMULATOR_IMAGE}").as_str()])
.output()
.map_err(|e| {
ChainSimulatorError::CommandFailed(format!(
"Failed to execute `{DOCKER_CMD} ps` to find a running Chain Simulator container. Cause: {e:#?}"
))
})?;

if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(ChainSimulatorError::CommandFailed(stderr.to_string()));
}

let container_id = String::from_utf8_lossy(&output.stdout).trim().to_string();

if container_id.is_empty() {
return Err(ChainSimulatorError::ContainerNotRunning);
}

let stop_output = Command::new(DOCKER_CMD)
.args(["stop", &container_id])
.output()
.map_err(|e| {
ChainSimulatorError::CommandFailed(format!(
"Failed to execute `{DOCKER_CMD} stop {container_id}`. Cause: {e:#?}"
))
})?;

if stop_output.status.success() {
println!("{}", "Successfully stopped the Chain Simulator.".green());
Ok(())
} else {
let stderr = String::from_utf8_lossy(&stop_output.stderr);
Err(ChainSimulatorError::CommandFailed(stderr.to_string()))
}
}
Loading