From 00c46c528ecdf48bdaec8488123e7b5186dfb806 Mon Sep 17 00:00:00 2001 From: Michael Vines Date: Tue, 15 Dec 2020 11:06:03 -0800 Subject: [PATCH] Add --reset flag to allow for easy ledger reset --- validator/src/bin/solana-test-validator.rs | 40 +++++++++++++++++++--- 1 file changed, 36 insertions(+), 4 deletions(-) diff --git a/validator/src/bin/solana-test-validator.rs b/validator/src/bin/solana-test-validator.rs index 43d1775a06..e0baaf215e 100644 --- a/validator/src/bin/solana-test-validator.rs +++ b/validator/src/bin/solana-test-validator.rs @@ -1,6 +1,7 @@ use { clap::{value_t_or_exit, App, Arg}, console::style, + fd_lock::FdLock, indicatif::{ProgressBar, ProgressDrawTarget, ProgressStyle}, solana_clap_utils::{input_parsers::pubkey_of, input_validators::is_pubkey}, solana_client::{client_error, rpc_client::RpcClient}, @@ -18,9 +19,9 @@ use { }, solana_validator::{start_logger, test_validator::*}, std::{ - fs, + fs, io, net::{IpAddr, Ipv4Addr, SocketAddr}, - path::PathBuf, + path::{Path, PathBuf}, process::exit, sync::mpsc::channel, thread, @@ -90,6 +91,16 @@ fn main() { .default_value("test-ledger") .help("Use DIR as ledger location"), ) + .arg( + Arg::with_name("reset") + .short("r") + .long("reset") + .takes_value(false) + .help( + "Reset the ledger to genesis if it exists. \ + By default the validator will resume an existing ledger (if present)", + ), + ) .arg( Arg::with_name("quiet") .short("q") @@ -144,6 +155,7 @@ fn main() { }); let ledger_path = value_t_or_exit!(matches, "ledger_path", PathBuf); + let reset_ledger = matches.is_present("reset"); let output = if matches.is_present("quiet") { Output::None } else if matches.is_present("log") { @@ -196,10 +208,10 @@ fn main() { err ); exit(1); - }) + }); } - let mut ledger_fd_lock = fd_lock::FdLock::new(std::fs::File::open(&ledger_path).unwrap()); + let mut ledger_fd_lock = FdLock::new(fs::File::open(&ledger_path).unwrap()); let _ledger_lock = ledger_fd_lock.try_lock().unwrap_or_else(|_| { eprintln!( "Error: Unable to lock {} directory. Check if another solana-test-validator is running", @@ -208,6 +220,13 @@ fn main() { exit(1); }); + if reset_ledger { + remove_directory_contents(&ledger_path).unwrap_or_else(|err| { + eprintln!("Error: Unable to remove {}: {}", ledger_path.display(), err); + exit(1); + }) + } + let validator_log_symlink = ledger_path.join("validator.log"); let logfile = if output != Output::Log { let validator_log_with_timestamp = format!( @@ -339,3 +358,16 @@ fn main() { std::thread::park(); } + +fn remove_directory_contents(ledger_path: &Path) -> Result<(), io::Error> { + for entry in fs::read_dir(&ledger_path)? { + let entry = entry?; + println!("emove {}:", entry.path().display()); + if entry.metadata()?.is_file() { + fs::remove_file(&entry.path())? + } else { + fs::remove_dir_all(&entry.path())? + } + } + Ok(()) +}