lib.rs 4.35 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;

24
use std::ops::Deref;
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
25
use chain_spec::ChainSpec;
26
27
use futures::Future;
use tokio::runtime::Runtime;
28
use service::Service as BareService;
29
use log::info;
30
31
32
33
34
35

pub use service::{
	Components as ServiceComponents, PolkadotService, CustomConfiguration, ServiceFactory, Factory,
	ProvideRuntimeApi, CoreApi, ParachainHost,
};

36
pub use cli::{VersionInfo, IntoExit, NoCustom};
37
pub use cli::error;
38
pub use tokio::runtime::TaskExecutor;
Gav Wood's avatar
Gav Wood committed
39

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

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

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

61
	/// Do work and schedule exit.
62
	fn work<S: PolkadotService>(self, service: &S, executor: TaskExecutor) -> Self::Work;
63
64
}

Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
65
/// Parse command line arguments into service configuration.
Gav's avatar
Gav committed
66
67
68
69
70
71
72
///
/// IANA unassigned port ranges that we could use:
/// 6717-6766		Unassigned
/// 8504-8553		Unassigned
/// 9556-9591		Unassigned
/// 9803-9874		Unassigned
/// 9926-9949		Unassigned
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
73
pub fn run<I, T, W>(args: I, worker: W, version: cli::VersionInfo) -> error::Result<()> where
Gav's avatar
Gav committed
74
75
	I: IntoIterator<Item = T>,
	T: Into<std::ffi::OsString> + Clone,
76
	W: Worker,
Gav's avatar
Gav committed
77
{
78
79
	cli::parse_and_execute::<service::Factory, NoCustom, NoCustom, _, _, _, _, _>(
		load_spec, &version, "parity-polkadot", args, worker,
80
		|worker, _cli_args, _custom_args, mut config| {
81
			info!("{}", version.name);
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
82
			info!("  version {}", config.full_version());
83
			info!("  by {}, 2017-2019", version.author);
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
84
85
86
87
			info!("Chain specification: {}", config.chain_spec.name());
			info!("Node name: {}", config.name);
			info!("Roles: {:?}", config.roles);
			config.custom = worker.configuration();
88
			let runtime = Runtime::new().map_err(|e| format!("{:?}", e))?;
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
89
			let executor = runtime.executor();
90
91
92
93
94
95
96
97
98
99
100
101
102
			match config.roles {
				service::Roles::LIGHT =>
					run_until_exit(
						runtime,
						Factory::new_light(config, executor).map_err(|e| format!("{:?}", e))?,
						worker
					),
				_ => run_until_exit(
						runtime,
						Factory::new_full(config, executor).map_err(|e| format!("{:?}", e))?,
						worker
					),
			}.map_err(|e| format!("{:?}", e))
103
		}
104
	).map_err(Into::into).map(|_| ())
105
}
106
107

fn run_until_exit<T, C, W>(
André Silva's avatar
André Silva committed
108
	mut runtime: Runtime,
109
	service: T,
110
111
	worker: W,
) -> error::Result<()>
112
	where
113
	    T: Deref<Target=BareService<C>>,
114
		C: service::Components,
115
		BareService<C>: PolkadotService,
116
		W: Worker,
117
{
118
	let (exit_send, exit) = exit_future::signal();
Arkadiy Paronyan's avatar
Arkadiy Paronyan committed
119

120
	let executor = runtime.executor();
121
122
	let informant = cli::informant::build(&service);
	executor.spawn(exit.until(informant).map(|_| ()));
123

124
	let _ = runtime.block_on(worker.work(&*service, executor.clone()));
125
	exit_send.fire();
André Silva's avatar
André Silva committed
126
127
128
129
130
131
132
133
134

	// 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();
	drop(service);

	// TODO [andre]: timeout this future (https://github.com/paritytech/substrate/issues/1318)
	let _ = runtime.shutdown_on_idle().wait();

Gav's avatar
Gav committed
135
136
	Ok(())
}