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
use crate::{Result, Version};
use anyhow::anyhow;
use aptos_config::{config::NodeConfig, network_id::NetworkId};
use aptos_rest_client::Client as RestClient;
use aptos_sdk::types::PeerId;
use inspection_service::inspection_client::InspectionClient;
use std::{
collections::HashMap,
time::{Duration, Instant},
};
use url::Url;
#[derive(Debug)]
pub enum HealthCheckError {
NotRunning(String),
Failure(anyhow::Error),
Unknown(anyhow::Error),
}
impl std::fmt::Display for HealthCheckError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{:?}", self)
}
}
impl std::error::Error for HealthCheckError {}
#[async_trait::async_trait]
pub trait Node: Send + Sync {
fn peer_id(&self) -> PeerId;
fn name(&self) -> &str;
fn version(&self) -> Version;
fn rest_api_endpoint(&self) -> Url;
fn inspection_service_endpoint(&self) -> Url;
fn config(&self) -> &NodeConfig;
async fn start(&mut self) -> Result<()>;
fn stop(&mut self) -> Result<()>;
fn clear_storage(&mut self) -> Result<()>;
async fn health_check(&mut self) -> Result<(), HealthCheckError>;
fn counter(&self, counter: &str, port: u64) -> Result<f64>;
fn expose_metric(&self) -> Result<u64>;
}
#[async_trait::async_trait]
pub trait Validator: Node + Sync {
async fn check_connectivity(&self, expected_peers: usize) -> Result<bool> {
if expected_peers == 0 {
return Ok(true);
}
self.get_connected_peers(NetworkId::Validator, None)
.await
.map(|maybe_n| maybe_n.map(|n| n >= expected_peers as i64).unwrap_or(false))
}
async fn wait_for_connectivity(&self, expected_peers: usize, deadline: Instant) -> Result<()> {
while !self.check_connectivity(expected_peers).await? {
if Instant::now() > deadline {
return Err(anyhow!("waiting for connectivity timed out"));
}
tokio::time::sleep(Duration::from_millis(500)).await;
}
Ok(())
}
}
#[async_trait::async_trait]
pub trait FullNode: Node + Sync {
async fn check_connectivity(&self) -> Result<bool> {
const DIRECTION: Option<&str> = Some("outbound");
const EXPECTED_PEERS: usize = 1;
self.get_connected_peers(NetworkId::Public, DIRECTION)
.await
.map(|maybe_n| maybe_n.map(|n| n >= EXPECTED_PEERS as i64).unwrap_or(false))
}
async fn wait_for_connectivity(&self, deadline: Instant) -> Result<()> {
while !self.check_connectivity().await? {
if Instant::now() > deadline {
return Err(anyhow!("waiting for connectivity timed out"));
}
tokio::time::sleep(Duration::from_millis(500)).await;
}
Ok(())
}
}
impl<T: ?Sized> NodeExt for T where T: Node {}
#[async_trait::async_trait]
pub trait NodeExt: Node {
fn rest_client(&self) -> RestClient {
RestClient::new(self.rest_api_endpoint())
}
fn inspection_client(&self) -> InspectionClient {
InspectionClient::from_url(self.inspection_service_endpoint())
}
async fn restart(&mut self) -> Result<()> {
self.stop()?;
self.start().await
}
async fn get_metric(&self, metric_name: &str) -> Result<Option<i64>> {
self.inspection_client().get_node_metric(metric_name).await
}
async fn get_metric_with_fields(
&self,
metric_name: &str,
fields: HashMap<String, String>,
) -> Result<Option<i64>> {
let filtered: Vec<_> = self
.inspection_client()
.get_node_metric_with_name(metric_name)
.await?
.into_iter()
.flat_map(|map| map.into_iter())
.filter_map(|(metric, metric_value)| {
if fields
.iter()
.all(|(key, value)| metric.contains(&format!("{}={}", key, value)))
{
Some(metric_value)
} else {
None
}
})
.collect();
Ok(if filtered.is_empty() {
None
} else {
Some(filtered.iter().sum())
})
}
async fn get_connected_peers(
&self,
network_id: NetworkId,
direction: Option<&str>,
) -> Result<Option<i64>> {
let mut map = HashMap::new();
map.insert("network_id".to_string(), network_id.to_string());
if let Some(direction) = direction {
map.insert("direction".to_string(), direction.to_string());
}
self.get_metric_with_fields("aptos_connections", map).await
}
async fn liveness_check(&self, seconds: u64) -> Result<()> {
self.rest_client().health_check(seconds).await
}
async fn wait_until_healthy(&mut self, deadline: Instant) -> Result<()> {
while Instant::now() < deadline {
match self.health_check().await {
Ok(()) => return Ok(()),
Err(HealthCheckError::NotRunning(error)) => {
return Err(anyhow::anyhow!(
"Node {}:{} not running! Error: {:?}",
self.name(),
self.peer_id(),
error,
))
}
Err(_) => {}
}
tokio::time::sleep(Duration::from_millis(500)).await;
}
Err(anyhow::anyhow!(
"Timed out waiting for Node {}:{} to be healthy",
self.name(),
self.peer_id()
))
}
}