lib.rs 7.09 KB
Newer Older
Gav's avatar
Gav committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Copyright 2017 Parity Technologies (UK) Ltd.
// This file is part of Polkadot.

// Polkadot 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.

// Polkadot 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 Polkadot.  If not, see <http://www.gnu.org/licenses/>.

//! Polkadot CLI library.

#![warn(missing_docs)]
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
20
#![warn(unused_extern_crates)]
Gav's avatar
Gav committed
21

Gav Wood's avatar
Gav Wood committed
22
mod chain_spec;
23
24
#[cfg(feature = "browser")]
mod browser;
Gav Wood's avatar
Gav Wood committed
25

Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
26
use chain_spec::ChainSpec;
27
28
29
30
use futures::{
	Future, FutureExt, TryFutureExt, future::select, channel::oneshot, compat::Future01CompatExt,
	task::Spawn
};
31
use tokio::runtime::Runtime;
32
use log::{info, error};
33
use structopt::StructOpt;
34
35

pub use service::{
36
	AbstractService, CustomConfiguration,
37
	ProvideRuntimeApi, CoreApi, ParachainHost,
38
	WrappedExecutor
39
40
};

41
pub use cli::{VersionInfo, IntoExit, NoCustom};
Gavin Wood's avatar
Gavin Wood committed
42
pub use cli::{display_role, error};
Gavin Wood's avatar
Gavin Wood committed
43

Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
44
45
46
47
48
fn load_spec(id: &str) -> Result<Option<service::ChainSpec>, String> {
	Ok(match ChainSpec::from(id) {
		Some(spec) => Some(spec.load()?),
		None => None,
	})
49
50
}

51
52
53
54
/// Additional worker making use of the node, to run asynchronously before shutdown.
///
/// This will be invoked with the service and spawn a future that resolves
/// when complete.
55
pub trait Worker: IntoExit {
56
57
	/// A future that resolves when the work is done or the node should exit.
	/// This will be run on a tokio runtime.
58
	type Work: Future<Output=()> + Unpin + Send + 'static;
59

60
61
	/// Return configuration for the polkadot node.
	// TODO: make this the full configuration, so embedded nodes don't need
62
	// string CLI args (https://github.com/paritytech/polkadot/issues/111)
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
63
	fn configuration(&self) -> service::CustomConfiguration { Default::default() }
64

65
	/// Do work and schedule exit.
66
	fn work<S, SC, B, CE, SP>(self, service: &S, spawner: SP) -> Self::Work
67
68
69
70
71
	where S: AbstractService<Block = service::Block, RuntimeApi = service::RuntimeApi,
		Backend = B, SelectChain = SC,
		NetworkSpecialization = service::PolkadotProtocol, CallExecutor = CE>,
		SC: service::SelectChain<service::Block> + 'static,
		B: service::Backend<service::Block, service::Blake2Hasher> + 'static,
72
73
		CE: service::CallExecutor<service::Block, service::Blake2Hasher> + Clone + Send + Sync + 'static,
		SP: Spawn + Clone + Send + Sync + 'static;
74
75
}

76
77
#[derive(Debug, StructOpt, Clone)]
enum PolkadotSubCommands {
78
	#[structopt(name = "validation-worker", setting = structopt::clap::AppSettings::Hidden)]
Gavin Wood's avatar
Gavin Wood committed
79
	ValidationWorker(ValidationWorkerCommand),
80
81
}

Gavin Wood's avatar
Gavin Wood committed
82
83
impl cli::GetSharedParams for PolkadotSubCommands {
	fn shared_params(&self) -> Option<&cli::SharedParams> { None }
84
85
86
}

#[derive(Debug, StructOpt, Clone)]
Gavin Wood's avatar
Gavin Wood committed
87
struct ValidationWorkerCommand {
88
89
90
91
	#[structopt()]
	pub mem_id: String,
}

Gavin Wood's avatar
Gavin Wood committed
92
93
94
95
96
97
#[derive(Debug, StructOpt, Clone)]
struct PolkadotSubParams {
	#[structopt(long = "enable-authority-discovery")]
	pub authority_discovery_enabled: bool,
}

98
99
/// Parses polkadot specific CLI arguments and run the service.
pub fn run<W>(worker: W, version: cli::VersionInfo) -> error::Result<()> where
100
	W: Worker,
Gav's avatar
Gav committed
101
{
Gavin Wood's avatar
Gavin Wood committed
102
103
104
105
106
	match cli::parse_and_prepare::<PolkadotSubCommands, PolkadotSubParams, _>(
		&version,
		"parity-polkadot",
		std::env::args(),
	) {
107
		cli::ParseAndPrepare::Run(cmd) => cmd.run(load_spec, worker,
Gavin Wood's avatar
Gavin Wood committed
108
		|worker, _cli_args, custom_args, mut config| {
109
			info!("{}", version.name);
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
110
			info!("  version {}", config.full_version());
111
			info!("  by {}, 2017-2019", version.author);
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
112
			info!("Chain specification: {}", config.chain_spec.name());
Gavin Wood's avatar
Gavin Wood committed
113
114
115
116
117
118
119
			if config.chain_spec.name().starts_with("Kusama") {
				info!("----------------------------");
				info!("This chain is not in any way");
				info!("      endorsed by the       ");
				info!("     KUSAMA FOUNDATION      ");
				info!("----------------------------");
			}
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
120
			info!("Node name: {}", config.name);
Gavin Wood's avatar
Gavin Wood committed
121
			info!("Roles: {}", display_role(&config));
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
122
			config.custom = worker.configuration();
Gavin Wood's avatar
Gavin Wood committed
123
			config.custom.authority_discovery_enabled = custom_args.authority_discovery_enabled;
124
125
126
127
128
			let runtime = Runtime::new().map_err(|e| format!("{:?}", e))?;
			match config.roles {
				service::Roles::LIGHT =>
					run_until_exit(
						runtime,
129
						service::new_light(config).map_err(|e| format!("{:?}", e))?,
130
131
132
133
						worker
					),
				_ => run_until_exit(
						runtime,
134
						service::new_full(config).map_err(|e| format!("{:?}", e))?,
135
136
137
						worker
					),
			}.map_err(|e| format!("{:?}", e))
138
		}),
Kian Paimani's avatar
Kian Paimani committed
139
		cli::ParseAndPrepare::BuildSpec(cmd) => cmd.run::<NoCustom, _, _, _>(load_spec),
thiolliere's avatar
thiolliere committed
140
		cli::ParseAndPrepare::ExportBlocks(cmd) => cmd.run_with_builder::<(), _, _, _, _, _, _>(|config|
141
			Ok(service::new_chain_ops(config)?), load_spec, worker),
thiolliere's avatar
thiolliere committed
142
		cli::ParseAndPrepare::ImportBlocks(cmd) => cmd.run_with_builder::<(), _, _, _, _, _, _>(|config|
143
			Ok(service::new_chain_ops(config)?), load_spec, worker),
144
145
		cli::ParseAndPrepare::CheckBlock(cmd) => cmd.run_with_builder::<(), _, _, _, _, _, _>(|config|
			Ok(service::new_chain_ops(config)?), load_spec, worker),
146
		cli::ParseAndPrepare::PurgeChain(cmd) => cmd.run(load_spec),
thiolliere's avatar
thiolliere committed
147
		cli::ParseAndPrepare::RevertChain(cmd) => cmd.run_with_builder::<(), _, _, _, _, _>(|config|
148
			Ok(service::new_chain_ops(config)?), load_spec),
149
		cli::ParseAndPrepare::CustomCommand(PolkadotSubCommands::ValidationWorker(args)) => {
150
151
152
153
154
155
156
			if cfg!(feature = "browser") {
				Err(error::Error::Input("Cannot run validation worker in browser".into()))
			} else {
				#[cfg(not(feature = "browser"))]
				service::run_validation_worker(&args.mem_id)?;
				Ok(())
			}
157
		}
158
	}
159
}
160

161
fn run_until_exit<T, SC, B, CE, W>(
André Silva's avatar
André Silva committed
162
	mut runtime: Runtime,
163
	service: T,
164
165
	worker: W,
) -> error::Result<()>
166
	where
167
168
169
170
171
		T: AbstractService<Block = service::Block, RuntimeApi = service::RuntimeApi,
			SelectChain = SC, Backend = B, NetworkSpecialization = service::PolkadotProtocol, CallExecutor = CE>,
		SC: service::SelectChain<service::Block> + 'static,
		B: service::Backend<service::Block, service::Blake2Hasher> + 'static,
		CE: service::CallExecutor<service::Block, service::Blake2Hasher> + Clone + Send + Sync + 'static,
172
		W: Worker,
173
{
174
	let (exit_send, exit) = oneshot::channel();
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
175

176
	let executor = runtime.executor();
177
	let informant = cli::informant::build(&service);
178
179
180
181
182
	let future = select(exit, informant)
		.map(|_| Ok(()))
		.compat();

	executor.spawn(future);
183

André Silva's avatar
André Silva committed
184
185
186
187
	// we eagerly drop the service so that the internal exit future is fired,
	// but we need to keep holding a reference to the global telemetry guard
	let _telemetry = service.telemetry();

188
	let work = worker.work(&service, WrappedExecutor(executor));
189
190
191
192
193
194
195
196
197
198
	let service = service
		.map_err(|err| error!("Error while running Service: {}", err))
		.compat();
	let future = select(service, work)
		.map(|_| Ok::<_, ()>(()))
		.compat();
	let _ = runtime.block_on(future);
	let _ = exit_send.send(());

	use futures01::Future;
André Silva's avatar
André Silva committed
199

André Silva's avatar
André Silva committed
200
201
202
	// TODO [andre]: timeout this future substrate/#1318
	let _ = runtime.shutdown_on_idle().wait();

Gav's avatar
Gav committed
203
204
	Ok(())
}