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
23
mod chain_spec;

Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
24
use chain_spec::ChainSpec;
25
use futures::{Future, FutureExt, TryFutureExt, future::select, channel::oneshot, compat::Future01CompatExt};
26
use tokio::runtime::Runtime;
Gavin Wood's avatar
Gavin Wood committed
27
use std::sync::Arc;
28
use log::{info, error};
29
use structopt::StructOpt;
30
31

pub use service::{
32
	AbstractService, CustomConfiguration,
33
34
35
	ProvideRuntimeApi, CoreApi, ParachainHost,
};

36
pub use cli::{VersionInfo, IntoExit, NoCustom};
Gavin Wood's avatar
Gavin Wood committed
37
pub use cli::{display_role, error};
Gavin Wood's avatar
Gavin Wood committed
38

39
type BoxedFuture = Box<dyn futures01::Future<Item = (), Error = ()> + Send>;
Gavin Wood's avatar
Gavin Wood committed
40
/// Abstraction over an executor that lets you spawn tasks in the background.
41
pub type TaskExecutor = Arc<dyn futures01::future::Executor<BoxedFuture> + Send + Sync>;
Gav Wood's avatar
Gav Wood committed
42

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

50
51
52
53
/// 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.
54
pub trait Worker: IntoExit {
55
56
	/// A future that resolves when the work is done or the node should exit.
	/// This will be run on a tokio runtime.
57
	type Work: Future<Output=()> + Unpin + Send + 'static;
58

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

64
	/// Do work and schedule exit.
65
66
67
68
69
70
71
	fn work<S, SC, B, CE>(self, service: &S, executor: TaskExecutor) -> Self::Work
	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,
		CE: service::CallExecutor<service::Block, service::Blake2Hasher> + Clone + Send + Sync + 'static;
72
73
}

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

impl cli::GetLogFilter for PolkadotSubCommands {
	fn get_log_filter(&self) -> Option<String> { None }
}

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

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

cli::impl_augment_clap!(PolkadotSubParams);

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
150
151
		cli::ParseAndPrepare::CustomCommand(PolkadotSubCommands::ValidationWorker(args)) => {
			service::run_validation_worker(&args.mem_id)?;
			Ok(())
152
		}
153
	}
154
}
155

156
fn run_until_exit<T, SC, B, CE, W>(
André Silva's avatar
André Silva committed
157
	mut runtime: Runtime,
158
	service: T,
159
160
	worker: W,
) -> error::Result<()>
161
	where
162
163
164
165
166
		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,
167
		W: Worker,
168
{
169
	let (exit_send, exit) = oneshot::channel();
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
170

171
	let executor = runtime.executor();
172
	let informant = cli::informant::build(&service);
173
174
175
176
177
	let future = select(exit, informant)
		.map(|_| Ok(()))
		.compat();

	executor.spawn(future);
178

André Silva's avatar
André Silva committed
179
180
181
182
	// 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();

183
	let work = worker.work(&service, Arc::new(executor));
184
185
186
187
188
189
190
191
192
193
	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
194

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

Gav's avatar
Gav committed
198
199
	Ok(())
}