sc_informant/
display.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
5
6// This program is free software: you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10
11// This program is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// You should have received a copy of the GNU General Public License
17// along with this program. If not, see <https://www.gnu.org/licenses/>.
18
19use console::style;
20use log::info;
21use sc_client_api::ClientInfo;
22use sc_network::NetworkStatus;
23use sc_network_sync::{SyncState, SyncStatus, WarpSyncPhase, WarpSyncProgress};
24use sp_runtime::traits::{Block as BlockT, CheckedDiv, NumberFor, Saturating, Zero};
25use std::{fmt, time::Instant};
26
27/// State of the informant display system.
28///
29/// This is the system that handles the line that gets regularly printed and that looks something
30/// like:
31///
32/// > Syncing  5.4 bps, target=#531028 (4 peers), best: #90683 (0x4ca8…51b8),
33/// > finalized #360 (0x6f24…a38b), ⬇ 5.5kiB/s ⬆ 0.9kiB/s
34///
35/// # Usage
36///
37/// Call `InformantDisplay::new` to initialize the state, then regularly call `display` with the
38/// information to display.
39pub struct InformantDisplay<B: BlockT> {
40	/// Head of chain block number from the last time `display` has been called.
41	/// `None` if `display` has never been called.
42	last_number: Option<NumberFor<B>>,
43	/// The last time `display` or `new` has been called.
44	last_update: Instant,
45	/// The last seen total of bytes received.
46	last_total_bytes_inbound: u64,
47	/// The last seen total of bytes sent.
48	last_total_bytes_outbound: u64,
49}
50
51impl<B: BlockT> InformantDisplay<B> {
52	/// Builds a new informant display system.
53	pub fn new() -> InformantDisplay<B> {
54		InformantDisplay {
55			last_number: None,
56			last_update: Instant::now(),
57			last_total_bytes_inbound: 0,
58			last_total_bytes_outbound: 0,
59		}
60	}
61
62	/// Displays the informant by calling `info!`.
63	pub fn display(
64		&mut self,
65		info: &ClientInfo<B>,
66		net_status: NetworkStatus,
67		sync_status: SyncStatus<B>,
68		num_connected_peers: usize,
69	) {
70		let best_number = info.chain.best_number;
71		let best_hash = info.chain.best_hash;
72		let finalized_number = info.chain.finalized_number;
73		let speed = speed::<B>(best_number, self.last_number, self.last_update);
74		let total_bytes_inbound = net_status.total_bytes_inbound;
75		let total_bytes_outbound = net_status.total_bytes_outbound;
76
77		let now = Instant::now();
78		let elapsed = (now - self.last_update).as_secs();
79		self.last_update = now;
80		self.last_number = Some(best_number);
81
82		let diff_bytes_inbound = total_bytes_inbound - self.last_total_bytes_inbound;
83		let diff_bytes_outbound = total_bytes_outbound - self.last_total_bytes_outbound;
84		let (avg_bytes_per_sec_inbound, avg_bytes_per_sec_outbound) = if elapsed > 0 {
85			self.last_total_bytes_inbound = total_bytes_inbound;
86			self.last_total_bytes_outbound = total_bytes_outbound;
87			(diff_bytes_inbound / elapsed, diff_bytes_outbound / elapsed)
88		} else {
89			(diff_bytes_inbound, diff_bytes_outbound)
90		};
91
92		let (level, status, target) =
93			match (sync_status.state, sync_status.state_sync, sync_status.warp_sync) {
94				// Do not set status to "Block history" when we are doing a major sync.
95				//
96				// A node could for example have been warp synced to the tip of the chain and
97				// shutdown. At the next start we still need to download the block history, but
98				// first will sync to the tip of the chain.
99				(
100					sync_status,
101					_,
102					Some(WarpSyncProgress { phase: WarpSyncPhase::DownloadingBlocks(n), .. }),
103				) if !sync_status.is_major_syncing() => ("⏩", "Block history".into(), format!(", #{}", n)),
104				// Handle all phases besides the two phases we already handle above.
105				(_, _, Some(warp))
106					if !matches!(warp.phase, WarpSyncPhase::DownloadingBlocks(_)) =>
107					(
108						"⏩",
109						"Warping".into(),
110						format!(
111							", {}, {:.2} Mib",
112							warp.phase,
113							(warp.total_bytes as f32) / (1024f32 * 1024f32)
114						),
115					),
116				(_, Some(state), _) => (
117					"⚙️ ",
118					"State sync".into(),
119					format!(
120						", {}, {}%, {:.2} Mib",
121						state.phase,
122						state.percentage,
123						(state.size as f32) / (1024f32 * 1024f32)
124					),
125				),
126				(SyncState::Idle, _, _) => ("💤", "Idle".into(), "".into()),
127				(SyncState::Downloading { target }, _, _) =>
128					("⚙️ ", format!("Syncing{}", speed), format!(", target=#{target}")),
129				(SyncState::Importing { target }, _, _) =>
130					("⚙️ ", format!("Preparing{}", speed), format!(", target=#{target}")),
131			};
132
133		info!(
134			target: "substrate",
135			"{} {}{} ({} peers), best: #{} ({}), finalized #{} ({}), ⬇ {} ⬆ {}",
136			level,
137			style(&status).white().bold(),
138			target,
139			style(num_connected_peers).white().bold(),
140			style(best_number).white().bold(),
141			best_hash,
142			style(finalized_number).white().bold(),
143			info.chain.finalized_hash,
144			style(TransferRateFormat(avg_bytes_per_sec_inbound)).green(),
145			style(TransferRateFormat(avg_bytes_per_sec_outbound)).red(),
146		)
147	}
148}
149
150/// Calculates `(best_number - last_number) / (now - last_update)` and returns a `String`
151/// representing the speed of import.
152fn speed<B: BlockT>(
153	best_number: NumberFor<B>,
154	last_number: Option<NumberFor<B>>,
155	last_update: Instant,
156) -> String {
157	// Number of milliseconds elapsed since last time.
158	let elapsed_ms = {
159		let elapsed = last_update.elapsed();
160		let since_last_millis = elapsed.as_secs() * 1000;
161		let since_last_subsec_millis = elapsed.subsec_millis() as u64;
162		since_last_millis + since_last_subsec_millis
163	};
164
165	// Number of blocks that have been imported since last time.
166	let diff = match last_number {
167		None => return String::new(),
168		Some(n) => best_number.saturating_sub(n),
169	};
170
171	if let Ok(diff) = TryInto::<u128>::try_into(diff) {
172		// If the number of blocks can be converted to a regular integer, then it's easy: just
173		// do the math and turn it into a `f64`.
174		let speed = diff
175			.saturating_mul(10_000)
176			.checked_div(u128::from(elapsed_ms))
177			.map_or(0.0, |s| s as f64) /
178			10.0;
179		format!(" {:4.1} bps", speed)
180	} else {
181		// If the number of blocks can't be converted to a regular integer, then we need a more
182		// algebraic approach and we stay within the realm of integers.
183		let one_thousand = NumberFor::<B>::from(1_000u32);
184		let elapsed =
185			NumberFor::<B>::from(<u32 as TryFrom<_>>::try_from(elapsed_ms).unwrap_or(u32::MAX));
186
187		let speed = diff
188			.saturating_mul(one_thousand)
189			.checked_div(&elapsed)
190			.unwrap_or_else(Zero::zero);
191		format!(" {} bps", speed)
192	}
193}
194
195/// Contains a number of bytes per second. Implements `fmt::Display` and shows this number of bytes
196/// per second in a nice way.
197struct TransferRateFormat(u64);
198impl fmt::Display for TransferRateFormat {
199	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
200		// Special case 0.
201		if self.0 == 0 {
202			return write!(f, "0")
203		}
204
205		// Under 0.1 kiB, display plain bytes.
206		if self.0 < 100 {
207			return write!(f, "{} B/s", self.0)
208		}
209
210		// Under 1.0 MiB/sec, display the value in kiB/sec.
211		if self.0 < 1024 * 1024 {
212			return write!(f, "{:.1}kiB/s", self.0 as f64 / 1024.0)
213		}
214
215		write!(f, "{:.1}MiB/s", self.0 as f64 / (1024.0 * 1024.0))
216	}
217}