referrerpolicy=no-referrer-when-downgrade
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
// 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/>.

//! BEEFY Prometheus metrics definition

use crate::LOG_TARGET;
use log::{debug, error};
use prometheus_endpoint::{register, Counter, Gauge, PrometheusError, Registry, U64};

/// Helper trait for registering BEEFY metrics to Prometheus registry.
pub(crate) trait PrometheusRegister<T: Sized = Self>: Sized {
	const DESCRIPTION: &'static str;
	fn register(registry: &Registry) -> Result<Self, PrometheusError>;
}

/// BEEFY voting-related metrics exposed through Prometheus
#[derive(Clone, Debug)]
pub struct VoterMetrics {
	/// Current active validator set id
	pub beefy_validator_set_id: Gauge<U64>,
	/// Total number of votes sent by this node
	pub beefy_votes_sent: Counter<U64>,
	/// Best block finalized by BEEFY
	pub beefy_best_block: Gauge<U64>,
	/// Best block BEEFY voted on
	pub beefy_best_voted: Gauge<U64>,
	/// Next block BEEFY should vote on
	pub beefy_should_vote_on: Gauge<U64>,
	/// Number of sessions with lagging signed commitment on mandatory block
	pub beefy_lagging_sessions: Counter<U64>,
	/// Number of times no Authority public key found in store
	pub beefy_no_authority_found_in_store: Counter<U64>,
	/// Number of good votes successfully handled
	pub beefy_good_votes_processed: Counter<U64>,
	/// Number of equivocation votes received
	pub beefy_equivocation_votes: Counter<U64>,
	/// Number of invalid votes received
	pub beefy_invalid_votes: Counter<U64>,
	/// Number of valid but stale votes received
	pub beefy_stale_votes: Counter<U64>,
	/// Number of currently buffered justifications
	pub beefy_buffered_justifications: Gauge<U64>,
	/// Number of valid but stale justifications received
	pub beefy_stale_justifications: Counter<U64>,
	/// Number of valid justifications successfully imported
	pub beefy_imported_justifications: Counter<U64>,
	/// Number of justifications dropped due to full buffers
	pub beefy_buffered_justifications_dropped: Counter<U64>,
}

impl PrometheusRegister for VoterMetrics {
	const DESCRIPTION: &'static str = "voter";
	fn register(registry: &Registry) -> Result<Self, PrometheusError> {
		Ok(Self {
			beefy_validator_set_id: register(
				Gauge::new(
					"substrate_beefy_validator_set_id",
					"Current BEEFY active validator set id.",
				)?,
				registry,
			)?,
			beefy_votes_sent: register(
				Counter::new("substrate_beefy_votes_sent", "Number of votes sent by this node")?,
				registry,
			)?,
			beefy_best_block: register(
				Gauge::new("substrate_beefy_best_block", "Best block finalized by BEEFY")?,
				registry,
			)?,
			beefy_best_voted: register(
				Gauge::new("substrate_beefy_best_voted", "Best block voted on by BEEFY")?,
				registry,
			)?,
			beefy_should_vote_on: register(
				Gauge::new("substrate_beefy_should_vote_on", "Next block, BEEFY should vote on")?,
				registry,
			)?,
			beefy_lagging_sessions: register(
				Counter::new(
					"substrate_beefy_lagging_sessions",
					"Number of sessions with lagging signed commitment on mandatory block",
				)?,
				registry,
			)?,
			beefy_no_authority_found_in_store: register(
				Counter::new(
					"substrate_beefy_no_authority_found_in_store",
					"Number of times no Authority public key found in store",
				)?,
				registry,
			)?,
			beefy_good_votes_processed: register(
				Counter::new(
					"substrate_beefy_successful_handled_votes",
					"Number of good votes successfully handled",
				)?,
				registry,
			)?,
			beefy_equivocation_votes: register(
				Counter::new(
					"substrate_beefy_equivocation_votes",
					"Number of equivocation votes received",
				)?,
				registry,
			)?,
			beefy_invalid_votes: register(
				Counter::new("substrate_beefy_invalid_votes", "Number of invalid votes received")?,
				registry,
			)?,
			beefy_stale_votes: register(
				Counter::new(
					"substrate_beefy_stale_votes",
					"Number of valid but stale votes received",
				)?,
				registry,
			)?,
			beefy_buffered_justifications: register(
				Gauge::new(
					"substrate_beefy_buffered_justifications",
					"Number of currently buffered justifications",
				)?,
				registry,
			)?,
			beefy_stale_justifications: register(
				Counter::new(
					"substrate_beefy_stale_justifications",
					"Number of valid but stale justifications received",
				)?,
				registry,
			)?,
			beefy_imported_justifications: register(
				Counter::new(
					"substrate_beefy_imported_justifications",
					"Number of valid justifications successfully imported",
				)?,
				registry,
			)?,
			beefy_buffered_justifications_dropped: register(
				Counter::new(
					"substrate_beefy_buffered_justifications_dropped",
					"Number of justifications dropped due to full buffers",
				)?,
				registry,
			)?,
		})
	}
}

/// BEEFY block-import-related metrics exposed through Prometheus
#[derive(Clone, Debug)]
pub struct BlockImportMetrics {
	/// Number of Good Justification imports
	pub beefy_good_justification_imports: Counter<U64>,
	/// Number of Bad Justification imports
	pub beefy_bad_justification_imports: Counter<U64>,
}

impl PrometheusRegister for BlockImportMetrics {
	const DESCRIPTION: &'static str = "block-import";
	fn register(registry: &Registry) -> Result<Self, PrometheusError> {
		Ok(Self {
			beefy_good_justification_imports: register(
				Counter::new(
					"substrate_beefy_good_justification_imports",
					"Number of good justifications on block-import",
				)?,
				registry,
			)?,
			beefy_bad_justification_imports: register(
				Counter::new(
					"substrate_beefy_bad_justification_imports",
					"Number of bad justifications on block-import",
				)?,
				registry,
			)?,
		})
	}
}

/// BEEFY on-demand-justifications-related metrics exposed through Prometheus
#[derive(Clone, Debug)]
pub struct OnDemandIncomingRequestsMetrics {
	/// Number of Successful Justification responses
	pub beefy_successful_justification_responses: Counter<U64>,
	/// Number of Failed Justification responses
	pub beefy_failed_justification_responses: Counter<U64>,
}

impl PrometheusRegister for OnDemandIncomingRequestsMetrics {
	const DESCRIPTION: &'static str = "on-demand incoming justification requests";
	fn register(registry: &Registry) -> Result<Self, PrometheusError> {
		Ok(Self {
			beefy_successful_justification_responses: register(
				Counter::new(
					"substrate_beefy_successful_justification_responses",
					"Number of Successful Justification responses",
				)?,
				registry,
			)?,
			beefy_failed_justification_responses: register(
				Counter::new(
					"substrate_beefy_failed_justification_responses",
					"Number of Failed Justification responses",
				)?,
				registry,
			)?,
		})
	}
}

/// BEEFY on-demand-justifications-related metrics exposed through Prometheus
#[derive(Clone, Debug)]
pub struct OnDemandOutgoingRequestsMetrics {
	/// Number of times there was no good peer to request justification from
	pub beefy_on_demand_justification_no_peer_to_request_from: Counter<U64>,
	/// Number of on-demand justification peer refused valid requests
	pub beefy_on_demand_justification_peer_refused: Counter<U64>,
	/// Number of on-demand justification peer error
	pub beefy_on_demand_justification_peer_error: Counter<U64>,
	/// Number of on-demand justification invalid proof
	pub beefy_on_demand_justification_invalid_proof: Counter<U64>,
	/// Number of on-demand justification good proof
	pub beefy_on_demand_justification_good_proof: Counter<U64>,
	/// Number of live beefy peers available for requests.
	pub beefy_on_demand_live_peers: Gauge<U64>,
}

impl PrometheusRegister for OnDemandOutgoingRequestsMetrics {
	const DESCRIPTION: &'static str = "on-demand outgoing justification requests";
	fn register(registry: &Registry) -> Result<Self, PrometheusError> {
		Ok(Self {
			beefy_on_demand_justification_no_peer_to_request_from: register(
				Counter::new(
					"substrate_beefy_on_demand_justification_no_peer_to_request_from",
					"Number of times there was no good peer to request justification from",
				)?,
				registry,
			)?,
			beefy_on_demand_justification_peer_refused: register(
				Counter::new(
					"beefy_on_demand_justification_peer_refused",
					"Number of on-demand justification peer refused valid requests",
				)?,
				registry,
			)?,
			beefy_on_demand_justification_peer_error: register(
				Counter::new(
					"substrate_beefy_on_demand_justification_peer_error",
					"Number of on-demand justification peer error",
				)?,
				registry,
			)?,
			beefy_on_demand_justification_invalid_proof: register(
				Counter::new(
					"substrate_beefy_on_demand_justification_invalid_proof",
					"Number of on-demand justification invalid proof",
				)?,
				registry,
			)?,
			beefy_on_demand_justification_good_proof: register(
				Counter::new(
					"substrate_beefy_on_demand_justification_good_proof",
					"Number of on-demand justification good proof",
				)?,
				registry,
			)?,
			beefy_on_demand_live_peers: register(
				Gauge::new(
					"substrate_beefy_on_demand_live_peers",
					"Number of live beefy peers available for requests.",
				)?,
				registry,
			)?,
		})
	}
}

pub(crate) fn register_metrics<T: PrometheusRegister>(
	prometheus_registry: Option<prometheus_endpoint::Registry>,
) -> Option<T> {
	prometheus_registry.as_ref().map(T::register).and_then(|result| match result {
		Ok(metrics) => {
			debug!(target: LOG_TARGET, "🥩 Registered {} metrics", T::DESCRIPTION);
			Some(metrics)
		},
		Err(err) => {
			error!(
				target: LOG_TARGET,
				"🥩 Failed to register {} metrics: {:?}",
				T::DESCRIPTION,
				err
			);
			None
		},
	})
}

// Note: we use the `format` macro to convert an expr into a `u64`. This will fail,
// if expr does not derive `Display`.
#[macro_export]
macro_rules! metric_set {
	($metrics:expr, $m:ident, $v:expr) => {{
		let val: u64 = format!("{}", $v).parse().unwrap();

		if let Some(metrics) = $metrics.as_ref() {
			metrics.$m.set(val);
		}
	}};
}

#[macro_export]
macro_rules! metric_inc {
	($metrics:expr, $m:ident) => {{
		if let Some(metrics) = $metrics.as_ref() {
			metrics.$m.inc();
		}
	}};
}

#[macro_export]
macro_rules! metric_get {
	($metrics:expr, $m:ident) => {{
		$metrics.as_ref().map(|metrics| metrics.$m.clone())
	}};
}

#[cfg(test)]
pub(crate) mod tests {
	use super::*;

	#[test]
	fn should_register_metrics() {
		let registry = Some(Registry::new());
		assert!(register_metrics::<VoterMetrics>(registry.clone()).is_some());
		assert!(register_metrics::<BlockImportMetrics>(registry.clone()).is_some());
		assert!(register_metrics::<OnDemandIncomingRequestsMetrics>(registry.clone()).is_some());
		assert!(register_metrics::<OnDemandOutgoingRequestsMetrics>(registry.clone()).is_some());
	}
}