refactor(cli): Make some run params reusable (#13870)

* refactor: extract TelemetryParams and PrometheusParams

* improve run_cmd docs

* extract `RuntimeParams`

* use `normalize`

* keep params types same style

* improve `max_runtime_instances`

* fmt

* add license and improve code

* Update client/cli/src/params/runtime_params.rs

Co-authored-by: Bastian Köcher <git@kchr.de>

---------

Co-authored-by: Bastian Köcher <git@kchr.de>
This commit is contained in:
yjh
2023-04-25 16:18:35 +08:00
committed by GitHub
parent b46a512e1a
commit bcf7601169
9 changed files with 210 additions and 103 deletions
@@ -61,7 +61,7 @@ pub struct KeystoreParams {
pub password_filename: Option<PathBuf>,
}
/// Parse a sercret string, returning a displayable error.
/// Parse a secret string, returning a displayable error.
pub fn secret_string_from_str(s: &str) -> std::result::Result<SecretString, String> {
std::str::FromStr::from_str(s).map_err(|_| "Could not get SecretString".to_string())
}
@@ -20,14 +20,13 @@
use crate::error::Error;
use array_bytes::{hex2bytes, hex_bytes2hex_str};
use clap::Parser;
use clap::Args;
use std::io::BufRead;
/// Params to configure how a message should be passed into a command.
#[derive(Parser, Debug, Clone)]
#[derive(Debug, Clone, Args)]
pub struct MessageParams {
/// Message to process. Will be read from STDIN otherwise.
///
/// The message is assumed to be raw bytes per default. Use `--hex` for hex input. Can
/// optionally be prefixed with `0x` in the hex case.
#[arg(long)]
+5 -2
View File
@@ -22,8 +22,11 @@ mod message_params;
mod network_params;
mod node_key_params;
mod offchain_worker_params;
mod prometheus_params;
mod pruning_params;
mod runtime_params;
mod shared_params;
mod telemetry_params;
mod transaction_pool_params;
use crate::arg_enums::{CryptoScheme, OutputType};
@@ -37,8 +40,8 @@ use std::{fmt::Debug, str::FromStr};
pub use crate::params::{
database_params::*, import_params::*, keystore_params::*, message_params::*, network_params::*,
node_key_params::*, offchain_worker_params::*, pruning_params::*, shared_params::*,
transaction_pool_params::*,
node_key_params::*, offchain_worker_params::*, prometheus_params::*, pruning_params::*,
runtime_params::*, shared_params::*, telemetry_params::*, transaction_pool_params::*,
};
/// Parse Ss58AddressFormat
@@ -0,0 +1,63 @@
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use clap::Args;
use sc_service::config::PrometheusConfig;
use std::net::{Ipv4Addr, SocketAddr};
/// Parameters used to config prometheus.
#[derive(Debug, Clone, Args)]
pub struct PrometheusParams {
/// Specify Prometheus exporter TCP Port.
#[arg(long, value_name = "PORT")]
pub prometheus_port: Option<u16>,
/// Expose Prometheus exporter on all interfaces.
///
/// Default is local.
#[arg(long)]
pub prometheus_external: bool,
/// Do not expose a Prometheus exporter endpoint.
///
/// Prometheus metric endpoint is enabled by default.
#[arg(long)]
pub no_prometheus: bool,
}
impl PrometheusParams {
/// Creates [`PrometheusConfig`].
pub fn prometheus_config(
&self,
default_listen_port: u16,
chain_id: String,
) -> Option<PrometheusConfig> {
if self.no_prometheus {
None
} else {
let interface =
if self.prometheus_external { Ipv4Addr::UNSPECIFIED } else { Ipv4Addr::LOCALHOST };
Some(PrometheusConfig::new_with_default_registry(
SocketAddr::new(
interface.into(),
self.prometheus_port.unwrap_or(default_listen_port),
),
chain_id,
))
}
}
}
@@ -21,7 +21,7 @@ use clap::Args;
use sc_service::{BlocksPruning, PruningMode};
/// Parameters to define the pruning mode
#[derive(Debug, Clone, PartialEq, Args)]
#[derive(Debug, Clone, Args)]
pub struct PruningParams {
/// Specify the state pruning mode.
///
@@ -0,0 +1,43 @@
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use clap::Args;
use std::str::FromStr;
/// Parameters used to config runtime.
#[derive(Debug, Clone, Args)]
pub struct RuntimeParams {
/// The size of the instances cache for each runtime. The values higher than 256 are illegal.
#[arg(long, default_value_t = 8, value_parser = parse_max_runtime_instances)]
pub max_runtime_instances: usize,
/// Maximum number of different runtimes that can be cached.
#[arg(long, default_value_t = 2)]
pub runtime_cache_size: u8,
}
fn parse_max_runtime_instances(s: &str) -> Result<usize, String> {
let max_runtime_instances = usize::from_str(s)
.map_err(|_err| format!("Illegal `--max-runtime-instances` value: {s}"))?;
if max_runtime_instances > 256 {
Err(format!("Illegal `--max-runtime-instances` value: {max_runtime_instances} is more than the allowed maximum of `256` "))
} else {
Ok(max_runtime_instances)
}
}
@@ -22,7 +22,7 @@ use sc_service::config::BasePath;
use std::path::PathBuf;
/// Shared parameters used by all `CoreParams`.
#[derive(Debug, Clone, PartialEq, Args)]
#[derive(Debug, Clone, Args)]
pub struct SharedParams {
/// Specify the chain specification.
///
@@ -0,0 +1,68 @@
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
use clap::Args;
/// Parameters used to config telemetry.
#[derive(Debug, Clone, Args)]
pub struct TelemetryParams {
/// Disable connecting to the Substrate telemetry server.
///
/// Telemetry is on by default on global chains.
#[arg(long)]
pub no_telemetry: bool,
/// The URL of the telemetry server to connect to.
///
/// This flag can be passed multiple times as a means to specify multiple
/// telemetry endpoints. Verbosity levels range from 0-9, with 0 denoting
/// the least verbosity.
/// Expected format is 'URL VERBOSITY', e.g. `--telemetry-url 'wss://foo/bar 0'`.
#[arg(long = "telemetry-url", value_name = "URL VERBOSITY", value_parser = parse_telemetry_endpoints)]
pub telemetry_endpoints: Vec<(String, u8)>,
}
#[derive(Debug)]
enum TelemetryParsingError {
MissingVerbosity,
VerbosityParsingError(std::num::ParseIntError),
}
impl std::error::Error for TelemetryParsingError {}
impl std::fmt::Display for TelemetryParsingError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
TelemetryParsingError::MissingVerbosity => write!(f, "Verbosity level missing"),
TelemetryParsingError::VerbosityParsingError(e) => write!(f, "{}", e),
}
}
}
fn parse_telemetry_endpoints(s: &str) -> Result<(String, u8), TelemetryParsingError> {
let pos = s.find(' ');
match pos {
None => Err(TelemetryParsingError::MissingVerbosity),
Some(pos_) => {
let url = s[..pos_].to_string();
let verbosity =
s[pos_ + 1..].parse().map_err(TelemetryParsingError::VerbosityParsingError)?;
Ok((url, verbosity))
},
}
}