Make cli subcommands accept --dev, --chain and --base_path (#1214)

This restores an old behavior with more checks to inform the user
about misuse.
Only the `build-spec` parameter is not accepting these flags and options.
This subcommand only works with the options specified on the main command,
this is a restriction of the current cli parse/execute design.
This commit is contained in:
Bastian Köcher
2018-12-10 08:45:22 +01:00
committed by Gav Wood
parent 00410e636f
commit a4a67ccbe7
2 changed files with 266 additions and 169 deletions
+97 -24
View File
@@ -113,13 +113,17 @@ pub trait IntoExit {
fn into_exit(self) -> Self::Exit; fn into_exit(self) -> Self::Exit;
} }
fn get_chain_key(matches: &clap::ArgMatches) -> String {
matches.value_of("chain").unwrap_or_else(
|| if matches.is_present("dev") { "dev" } else { "" }
).into()
}
fn load_spec<F, G>(matches: &clap::ArgMatches, factory: F) -> Result<ChainSpec<G>, String> fn load_spec<F, G>(matches: &clap::ArgMatches, factory: F) -> Result<ChainSpec<G>, String>
where G: RuntimeGenesis, F: FnOnce(&str) -> Result<Option<ChainSpec<G>>, String>, where G: RuntimeGenesis, F: FnOnce(&str) -> Result<Option<ChainSpec<G>>, String>,
{ {
let chain_key = matches.value_of("chain").unwrap_or_else( let chain_key = get_chain_key(matches);
|| if matches.is_present("dev") { "dev" } else { "" } let spec = match factory(&chain_key)? {
);
let spec = match factory(chain_key)? {
Some(spec) => spec, Some(spec) => spec,
None => ChainSpec::from_json_file(PathBuf::from(chain_key))? None => ChainSpec::from_json_file(PathBuf::from(chain_key))?
}; };
@@ -132,6 +136,10 @@ fn base_path(matches: &clap::ArgMatches) -> PathBuf {
.unwrap_or_else(default_base_path) .unwrap_or_else(default_base_path)
} }
fn create_input_err<T: Into<String>>(msg: T) -> error::Error {
error::ErrorKind::Input(msg.into()).into()
}
/// Check whether a node name is considered as valid /// Check whether a node name is considered as valid
fn is_node_name_valid(_name: &str) -> Result<(), &str> { fn is_node_name_valid(_name: &str) -> Result<(), &str> {
const MAX_NODE_NAME_LENGTH: usize = 32; const MAX_NODE_NAME_LENGTH: usize = 32;
@@ -202,8 +210,14 @@ where
}; };
match is_node_name_valid(&config.name) { match is_node_name_valid(&config.name) {
Ok(_) => (), Ok(_) => (),
Err(msg) => return Err(error::ErrorKind::Input( Err(msg) => bail!(
format!("Invalid node name '{}'. Reason: {}. If unsure, use none.", config.name, msg)).into()) create_input_err(
format!("Invalid node name '{}'. Reason: {}. If unsure, use none.",
config.name,
msg
)
)
)
} }
let base_path = base_path(&matches); let base_path = base_path(&matches);
@@ -220,7 +234,7 @@ where
Some("archive") => PruningMode::ArchiveAll, Some("archive") => PruningMode::ArchiveAll,
None => PruningMode::default(), None => PruningMode::default(),
Some(s) => PruningMode::keep_blocks(s.parse() Some(s) => PruningMode::keep_blocks(s.parse()
.map_err(|_| error::ErrorKind::Input("Invalid pruning mode specified".to_owned()))?), .map_err(|_| create_input_err("Invalid pruning mode specified"))?),
}; };
let role = let role =
@@ -240,7 +254,7 @@ where
"both" => service::ExecutionStrategy::Both, "both" => service::ExecutionStrategy::Both,
"native" => service::ExecutionStrategy::NativeWhenPossible, "native" => service::ExecutionStrategy::NativeWhenPossible,
"wasm" => service::ExecutionStrategy::AlwaysWasm, "wasm" => service::ExecutionStrategy::AlwaysWasm,
_ => return Err(error::ErrorKind::Input("Invalid execution mode specified".to_owned()).into()), _ => bail!(create_input_err("Invalid execution mode specified")),
}; };
} }
@@ -280,7 +294,7 @@ where
config.network.client_version = config.client_id(); config.network.client_version = config.client_id();
config.network.use_secret = match matches.value_of("node_key").map(H256::from_str) { config.network.use_secret = match matches.value_of("node_key").map(H256::from_str) {
Some(Ok(secret)) => Some(secret.into()), Some(Ok(secret)) => Some(secret.into()),
Some(Err(err)) => return Err(format!("Error parsing node key: {}", err).into()), Some(Err(err)) => bail!(create_input_err(format!("Error parsing node key: {}", err))),
None => None, None => None,
}; };
@@ -318,6 +332,47 @@ where
Ok((spec, config)) Ok((spec, config))
} }
fn get_db_path_for_subcommand(
main_cmd: &clap::ArgMatches,
sub_cmd: &clap::ArgMatches
) -> error::Result<PathBuf> {
if main_cmd.is_present("chain") && sub_cmd.is_present("chain") {
bail!(create_input_err("`--chain` option is present two times"));
}
fn check_contradicting_chain_dev_flags(
m0: &clap::ArgMatches,
m1: &clap::ArgMatches
) -> error::Result<()> {
if m0.is_present("dev") && m1.is_present("chain") {
bail!(create_input_err("`--dev` and `--chain` given on different levels"));
}
Ok(())
}
check_contradicting_chain_dev_flags(main_cmd, sub_cmd)?;
check_contradicting_chain_dev_flags(sub_cmd, main_cmd)?;
let spec_id = if sub_cmd.is_present("chain") || sub_cmd.is_present("dev") {
get_chain_key(sub_cmd)
} else {
get_chain_key(main_cmd)
};
if main_cmd.is_present("base_path") && sub_cmd.is_present("base_path") {
bail!(create_input_err("`--base_path` option is present two times"));
}
let base_path = if sub_cmd.is_present("base_path") {
base_path(sub_cmd)
} else {
base_path(main_cmd)
};
Ok(db_path(&base_path, &spec_id))
}
// //
// IANA unassigned port ranges that we could use: // IANA unassigned port ranges that we could use:
// 6717-6766 Unassigned // 6717-6766 Unassigned
@@ -337,30 +392,40 @@ where
E: IntoExit, E: IntoExit,
F: ServiceFactory, F: ServiceFactory,
{ {
panic_hook::set(); panic_hook::set();
let log_pattern = matches.value_of("log").unwrap_or(""); let log_pattern = matches.value_of("log").unwrap_or("");
init_logger(log_pattern); init_logger(log_pattern);
fdlimit::raise_fd_limit(); fdlimit::raise_fd_limit();
let base_path = base_path(matches);
let db_path = db_path(&base_path, spec.id());
if let Some(matches) = matches.subcommand_matches("build-spec") { if let Some(matches) = matches.subcommand_matches("build-spec") {
build_spec::<F>(matches, spec, config)?; build_spec::<F>(matches, spec, config)?;
return Ok(Action::ExecutedInternally); return Ok(Action::ExecutedInternally);
} else if let Some(matches) = matches.subcommand_matches("export-blocks") { } else if let Some(sub_matches) = matches.subcommand_matches("export-blocks") {
export_blocks::<F, _>(db_path, matches, spec, exit.into_exit())?; export_blocks::<F, _>(
get_db_path_for_subcommand(matches, sub_matches)?,
matches,
spec,
exit.into_exit()
)?;
return Ok(Action::ExecutedInternally); return Ok(Action::ExecutedInternally);
} else if let Some(matches) = matches.subcommand_matches("import-blocks") { } else if let Some(sub_matches) = matches.subcommand_matches("import-blocks") {
import_blocks::<F, _>(db_path, matches, spec, exit.into_exit())?; import_blocks::<F, _>(
get_db_path_for_subcommand(matches, sub_matches)?,
matches,
spec,
exit.into_exit()
)?;
return Ok(Action::ExecutedInternally); return Ok(Action::ExecutedInternally);
} else if let Some(matches) = matches.subcommand_matches("revert") { } else if let Some(sub_matches) = matches.subcommand_matches("revert") {
revert_chain::<F>(db_path, matches, spec)?; revert_chain::<F>(
get_db_path_for_subcommand(matches, sub_matches)?,
matches,
spec
)?;
return Ok(Action::ExecutedInternally); return Ok(Action::ExecutedInternally);
} else if let Some(matches) = matches.subcommand_matches("purge-chain") { } else if let Some(sub_matches) = matches.subcommand_matches("purge-chain") {
purge_chain::<F>(db_path)?; purge_chain::<F>(get_db_path_for_subcommand(matches, sub_matches)?)?;
return Ok(Action::ExecutedInternally); return Ok(Action::ExecutedInternally);
} }
@@ -514,10 +579,18 @@ fn purge_chain<F>(
Ok(()) Ok(())
} }
fn parse_address(default: &str, port_param: &str, matches: &clap::ArgMatches) -> Result<SocketAddr, String> { fn parse_address(
let mut address: SocketAddr = default.parse().ok().ok_or_else(|| format!("Invalid address specified for --{}.", port_param))?; default: &str,
port_param: &str,
matches: &clap::ArgMatches
) -> Result<SocketAddr, String> {
let mut address: SocketAddr = default.parse().ok().ok_or_else(
|| format!("Invalid address specified for --{}.", port_param)
)?;
if let Some(port) = matches.value_of(port_param) { if let Some(port) = matches.value_of(port_param) {
let port: u16 = port.parse().ok().ok_or_else(|| format!("Invalid port for --{} specified.", port_param))?; let port: u16 = port.parse().ok().ok_or_else(
|| format!("Invalid port for --{} specified.", port_param)
)?;
address.set_port(port); address.set_port(port);
} }
+169 -145
View File
@@ -21,199 +21,223 @@ use structopt::StructOpt;
#[derive(Debug, StructOpt)] #[derive(Debug, StructOpt)]
#[structopt(name = "Substrate")] #[structopt(name = "Substrate")]
pub struct CoreParams { pub struct CoreParams {
///Sets a custom logging filter ///Sets a custom logging filter
#[structopt(short = "l", long = "log", value_name = "LOG_PATTERN")] #[structopt(short = "l", long = "log", value_name = "LOG_PATTERN")]
log: Option<String>, log: Option<String>,
/// Specify custom base path /// Specify custom keystore path
#[structopt(long = "base-path", short = "d", value_name = "PATH", parse(from_os_str))] #[structopt(long = "keystore-path", value_name = "PATH", parse(from_os_str))]
base_path: Option<PathBuf>, keystore_path: Option<PathBuf>,
/// Specify custom keystore path /// Specify additional key seed
#[structopt(long = "keystore-path", value_name = "PATH", parse(from_os_str))] #[structopt(long = "key", value_name = "STRING")]
keystore_path: Option<PathBuf>, key: Option<String>,
/// Specify additional key seed /// Specify node secret key (64-character hex string)
#[structopt(long = "key", value_name = "STRING")] #[structopt(long = "node-key", value_name = "KEY")]
key: Option<String>, node_key: Option<String>,
/// Specify node secret key (64-character hex string) /// Enable validator mode
#[structopt(long = "node-key", value_name = "KEY")] #[structopt(long = "validator")]
node_key: Option<String>, validator: bool,
/// Enable validator mode /// Run in light client mode
#[structopt(long = "validator")] #[structopt(long = "light")]
validator: bool, light: bool,
/// Run in light client mode /// Listen on this multiaddress
#[structopt(long = "light")] #[structopt(long = "listen-addr", value_name = "LISTEN_ADDR")]
light: bool, listen_addr: Vec<String>,
/// Run in development mode; implies --chain=dev --validator --key Alice /// Specify p2p protocol TCP port. Only used if --listen-addr is not specified.
#[structopt(long = "dev")] #[structopt(long = "port", value_name = "PORT")]
dev: bool, port: Option<u32>,
/// Listen on this multiaddress /// Listen to all RPC interfaces (default is local)
#[structopt(long = "listen-addr", value_name = "LISTEN_ADDR")] #[structopt(long = "rpc-external")]
listen_addr: Vec<String>, rpc_external: bool,
/// Specify p2p protocol TCP port. Only used if --listen-addr is not specified. /// Listen to all Websocket interfaces (default is local)
#[structopt(long = "port", value_name = "PORT")] #[structopt(long = "ws-external")]
port: Option<u32>, ws_external: bool,
/// Listen to all RPC interfaces (default is local) /// Specify HTTP RPC server TCP port
#[structopt(long = "rpc-external")] #[structopt(long = "rpc-port", value_name = "PORT")]
rpc_external: bool, rpc_port: Option<u32>,
/// Listen to all Websocket interfaces (default is local) /// Specify WebSockets RPC server TCP port
#[structopt(long = "ws-external")] #[structopt(long = "ws-port", value_name = "PORT")]
ws_external: bool, ws_port: Option<u32>,
/// Specify HTTP RPC server TCP port /// Specify a list of bootnodes
#[structopt(long = "rpc-port", value_name = "PORT")] #[structopt(long = "bootnodes", value_name = "URL")]
rpc_port: Option<u32>, bootnodes: Vec<String>,
/// Specify WebSockets RPC server TCP port /// Specify a list of reserved node addresses
#[structopt(long = "ws-port", value_name = "PORT")] #[structopt(long = "reserved-nodes", value_name = "URL")]
ws_port: Option<u32>, reserved_nodes: Vec<String>,
/// Specify a list of bootnodes /// Specify the number of outgoing connections we're trying to maintain
#[structopt(long = "bootnodes", value_name = "URL")] #[structopt(long = "out-peers", value_name = "OUT_PEERS")]
bootnodes: Vec<String>, out_peers: Option<u8>,
/// Specify a list of reserved node addresses /// Specify the maximum number of incoming connections we're accepting
#[structopt(long = "reserved-nodes", value_name = "URL")] #[structopt(long = "in-peers", value_name = "IN_PEERS")]
reserved_nodes: Vec<String>, in_peers: Option<u8>,
/// Specify the number of outgoing connections we're trying to maintain /// Specify the pruning mode, a number of blocks to keep or 'archive'. Default is 256.
#[structopt(long = "out-peers", value_name = "OUT_PEERS")] #[structopt(long = "pruning", value_name = "PRUNING_MODE")]
out_peers: Option<u8>, pruning: Option<u32>,
/// Specify the maximum number of incoming connections we're accepting /// The human-readable name for this node, as reported to the telemetry server, if enabled
#[structopt(long = "in-peers", value_name = "IN_PEERS")] #[structopt(long = "name", value_name = "NAME")]
in_peers: Option<u8>, name: Option<String>,
/// Specify the chain specification (one of dev, local or staging) /// Should connect to the Substrate telemetry server (telemetry is off by default on local chains)
#[structopt(long = "chain", value_name = "CHAIN_SPEC")] #[structopt(short = "t", long = "telemetry")]
chain: Option<String>, telemetry: bool,
/// Specify the pruning mode, a number of blocks to keep or 'archive'. Default is 256. /// Should not connect to the Substrate telemetry server (telemetry is on by default on global chains)
#[structopt(long = "pruning", value_name = "PRUNING_MODE")] #[structopt(long = "no-telemetry")]
pruning: Option<u32>, no_telemetry: bool,
/// The human-readable name for this node, as reported to the telemetry server, if enabled /// The URL of the telemetry server. Implies --telemetry
#[structopt(long = "name", value_name = "NAME")] #[structopt(long = "telemetry-url", value_name = "TELEMETRY_URL")]
name: Option<String>, telemetry_url: Option<String>,
/// Should connect to the Substrate telemetry server (telemetry is off by default on local chains) /// The means of execution used when calling into the runtime. Can be either wasm, native or both.
#[structopt(short = "t", long = "telemetry")] #[structopt(long = "execution", value_name = "STRATEGY")]
telemetry: bool, execution: Option<ExecutionStrategy>,
/// Should not connect to the Substrate telemetry server (telemetry is on by default on global chains) #[allow(missing_docs)]
#[structopt(long = "no-telemetry")] #[structopt(flatten)]
no_telemetry: bool, shared_flags: SharedFlags,
/// The URL of the telemetry server. Implies --telemetry #[structopt(subcommand)]
#[structopt(long = "telemetry-url", value_name = "TELEMETRY_URL")] cmds: Option<CoreCommands>,
telemetry_url: Option<String>,
/// The means of execution used when calling into the runtime. Can be either wasm, native or both.
#[structopt(long = "execution", value_name = "STRATEGY")]
execution: Option<ExecutionStrategy>,
#[structopt(subcommand)]
cmds: Option<CoreCommands>,
} }
/// How to execute blocks /// How to execute blocks
#[derive(Debug, StructOpt)] #[derive(Debug, StructOpt)]
pub enum ExecutionStrategy { pub enum ExecutionStrategy {
/// Execute native only /// Execute native only
Native, Native,
/// Execute wasm only /// Execute wasm only
Wasm, Wasm,
/// Execute natively when possible, wasm otherwise /// Execute natively when possible, wasm otherwise
Both, Both,
} }
impl Default for ExecutionStrategy { impl Default for ExecutionStrategy {
fn default() -> Self { fn default() -> Self {
ExecutionStrategy::Both ExecutionStrategy::Both
} }
} }
impl std::str::FromStr for ExecutionStrategy { impl std::str::FromStr for ExecutionStrategy {
type Err = String; type Err = String;
fn from_str(input: &str) -> Result<Self, Self::Err> { fn from_str(input: &str) -> Result<Self, Self::Err> {
match input { match input {
"native" => Ok(ExecutionStrategy::Native), "native" => Ok(ExecutionStrategy::Native),
"wasm" | "webassembly" => Ok(ExecutionStrategy::Wasm), "wasm" | "webassembly" => Ok(ExecutionStrategy::Wasm),
"both" => Ok(ExecutionStrategy::Both), "both" => Ok(ExecutionStrategy::Both),
_ => Err("Please specify either 'native', 'wasm' or 'both".to_owned()) _ => Err("Please specify either 'native', 'wasm' or 'both".to_owned())
} }
} }
}
/// Flags used by `CoreParams` and almost all `CoreCommands`.
#[derive(Debug, StructOpt)]
pub struct SharedFlags {
/// Specify the chain specification (one of dev, local or staging)
#[structopt(long = "chain", value_name = "CHAIN_SPEC")]
chain: Option<String>,
/// Specify the development chain
#[structopt(long = "dev")]
dev: bool,
/// Specify custom base path.
#[structopt(long = "base-path", short = "d", value_name = "PATH")]
base_path: Option<String>,
} }
/// Subcommands provided by Default /// Subcommands provided by Default
#[derive(Debug, StructOpt)] #[derive(Debug, StructOpt)]
pub enum CoreCommands { pub enum CoreCommands {
/// Build a spec.json file, outputing to stdout /// Build a spec.json file, outputing to stdout
#[structopt(name = "build-spec")] #[structopt(name = "build-spec")]
BuildSpec { BuildSpec {
/// Force raw genesis storage output. /// Force raw genesis storage output.
#[structopt(long = "raw")] #[structopt(long = "raw")]
raw: bool, raw: bool,
}, },
/// Export blocks to a file /// Export blocks to a file
#[structopt(name = "export-blocks")] #[structopt(name = "export-blocks")]
ExportBlocks { ExportBlocks {
/// Output file name or stdout if unspecified. /// Output file name or stdout if unspecified.
#[structopt(parse(from_os_str))] #[structopt(parse(from_os_str))]
output: Option<PathBuf>, output: Option<PathBuf>,
/// Specify starting block number. 1 by default. /// Specify starting block number. 1 by default.
#[structopt(long = "from", value_name = "BLOCK")] #[structopt(long = "from", value_name = "BLOCK")]
from: Option<u128>, from: Option<u128>,
/// Specify last block number. Best block by default. /// Specify last block number. Best block by default.
#[structopt(long = "to", value_name = "BLOCK")] #[structopt(long = "to", value_name = "BLOCK")]
to: Option<u128>, to: Option<u128>,
/// Use JSON output rather than binary. /// Use JSON output rather than binary.
#[structopt(long = "json")] #[structopt(long = "json")]
json: bool, json: bool,
},
/// Import blocks from file. #[allow(missing_docs)]
#[structopt(name = "import-blocks")] #[structopt(flatten)]
ImportBlocks { shared_flags: SharedFlags,
/// Input file or stdin if unspecified. },
#[structopt(parse(from_os_str))]
input: Option<PathBuf>,
/// The means of execution used when executing blocks. Can be either wasm, native or both. /// Import blocks from file.
#[structopt(long = "execution", value_name = "STRATEGY")] #[structopt(name = "import-blocks")]
execution: ExecutionStrategy, ImportBlocks {
/// Input file or stdin if unspecified.
#[structopt(parse(from_os_str))]
input: Option<PathBuf>,
/// The means of execution used when calling into the runtime. Can be either wasm, native or both. /// The means of execution used when executing blocks. Can be either wasm, native or both.
#[structopt(long = "api-execution", value_name = "STRATEGY")] #[structopt(long = "execution", value_name = "STRATEGY")]
api_execution: ExecutionStrategy, execution: ExecutionStrategy,
/// The maximum number of 64KB pages to ever allocate for Wasm execution. Don't alter this unless you know what you're doing. /// The means of execution used when calling into the runtime. Can be either wasm, native or both.
#[structopt(long = "max-heap-pages", value_name = "COUNT")] #[structopt(long = "api-execution", value_name = "STRATEGY")]
max_heap_pages: Option<u32>, api_execution: ExecutionStrategy,
},
///Revert chain to the previous state /// The maximum number of 64KB pages to ever allocate for Wasm execution. Don't alter this unless you know what you're doing.
#[structopt(name = "revert")] #[structopt(long = "max-heap-pages", value_name = "COUNT")]
Revert { max_heap_pages: Option<u32>,
/// Number of blocks to revert. Default is 256.
num: Option<u32>,
},
/// Remove the whole chain data. #[allow(missing_docs)]
#[structopt(name = "purge-chain")] #[structopt(flatten)]
PurgeChain {}, shared_flags: SharedFlags,
},
///Revert chain to the previous state
#[structopt(name = "revert")]
Revert {
/// Number of blocks to revert. Default is 256.
num: Option<u32>,
#[allow(missing_docs)]
#[structopt(flatten)]
shared_flags: SharedFlags,
},
/// Remove the whole chain data.
#[structopt(name = "purge-chain")]
PurgeChain {
#[allow(missing_docs)]
#[structopt(flatten)]
shared_flags: SharedFlags,
},
} }