File size: 9,435 Bytes
d5bfab8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
use super::{MetricEvent, MetricsPrometheus, MovingAverage, Recorder, CoordinatorWorkerMessage};
use std::time::{Duration, Instant};
use prometheus_client::encoding::text::encode;
use prometheus_client::registry::Registry;
use std::sync::{Arc, Mutex};
use bastion::prelude::*;

pub struct MetricsWorker;

impl MetricsWorker {
    /// Print metrics every second to commandline.
    pub fn start_without_server() -> anyhow::Result<()> {
        Bastion::supervisor(|supervisor| {
            supervisor.children(|children| {
                children
                    .with_redundancy(1)
                    .with_distributor(Distributor::named("metrics_worker"))
                    .with_exec(metrics_worker_print)
            })
        }).expect("Unable to create metrics_worker_print");
        Ok(())
    }

    /// Runs a webserver with realtime metrics, so bottlenecks can be identified.
    pub fn start_with_server(listen_on_port: u16, number_of_workers: u64) -> anyhow::Result<()> {
        println!("miner metrics can be downloaded here: http://localhost:{}/metrics", listen_on_port);
    
        let mut registry = <Registry>::default();
        let metrics = MetricsPrometheus::new(&mut registry);
        metrics.number_of_workers.set(number_of_workers);
    
        let registry2: MyRegistry = Arc::new(Mutex::new(registry));
    
        let _ = tokio::spawn(async move {
            let result = webserver_with_metrics(registry2, listen_on_port).await;
            if let Err(error) = result {
                error!("webserver thread failed with error: {:?}", error);
            }
        });

        Bastion::supervisor(|supervisor| {
            supervisor.children(|children| {
                children
                    .with_redundancy(1)
                    .with_distributor(Distributor::named("metrics_worker"))
                    .with_exec(move |ctx: BastionContext| {
                        let metrics_clone = metrics.clone();
                        async move {
                            metrics_worker_server(
                                ctx,
                                metrics_clone,
                            ).await
                        }
                    })
            })
        }).expect("Unable to create metrics_worker_webserver");
        Ok(())
    }
}

#[derive(Clone)]
struct State {
    registry: MyRegistry,
}

type MyRegistryInner = prometheus_client::registry::Registry<std::boxed::Box<dyn prometheus_client::encoding::text::SendSyncEncodeMetric>>;
type MyRegistry = std::sync::Arc<std::sync::Mutex<MyRegistryInner>>;

async fn webserver_with_metrics(registry: MyRegistry, listen_port: u16) -> std::result::Result<(), Box<dyn std::error::Error>> {
    let mut app = tide::with_state(State {
        registry: registry,
    });
    app.at("/").get(|_| async { Ok("Hello, world!") });
    app.at("/sync").get(|_| async {
        let distributor = Distributor::named("coordinator_worker");
        let tell_result = distributor.tell_everyone(CoordinatorWorkerMessage::TriggerSync);
        if let Err(error) = tell_result {
            let response = tide::Response::builder(500)
                .body(format!("webserver_with_metrics: /sync - Unable to send TriggerSync to coordinator_worker_distributor. {:?}", error))
                .content_type("text/plain; charset=utf-8")
                .build();
            return Ok(response);
        }
        let response = tide::Response::builder(200)
            .body("did send TriggerSync")
            .content_type("text/plain; charset=utf-8")
            .build();
        Ok(response)
    });
    app.at("/metrics")
        .get(|req: tide::Request<State>| async move {
            let mut encoded = Vec::new();
            {
                let registry = match req.state().registry.lock() {
                    Ok(value) => value,
                    Err(error) => {
                        error!("webserver_with_metrics: /metrics - Unable to lock registry. {:?}", error);
                        let response = tide::Response::builder(500)
                            .body(format!("webserver_with_metrics: /metrics - Unable to lock registry. {:?}", error))
                            .content_type("text/plain; charset=utf-8")
                            .build();
                        return Ok(response);
                    }
                };
                match encode(&mut encoded, &registry) {
                    Ok(()) => {},
                    Err(error) => {
                        error!("webserver_with_metrics: /metrics - Unable to encode registry. {:?}", error);
                        let response = tide::Response::builder(500)
                            .body(format!("webserver_with_metrics: /metrics - Unable to encode registry. {:?}", error))
                            .content_type("text/plain; charset=utf-8")
                            .build();
                        return Ok(response);
                    }
                }
            }
            let response = tide::Response::builder(200)
                .body(encoded)
                .content_type("application/openmetrics-text; version=1.0.0; charset=utf-8")
                .build();
            Ok(response)
        });
    let server_address = format!("localhost:{}", listen_port);
    app.listen(server_address).await?;
    Ok(())
}

/// Inspect metrics via the Graphana dashboard.
/// 
/// Underneeth Graphana accesses the data via Prometheus.
/// 
/// This function forwards metrics events to Prometheus.
async fn metrics_worker_server(ctx: BastionContext, metrics: MetricsPrometheus) -> Result<(), ()> {
    debug!("metrics_worker_server is ready");
    let mut progress_time = Instant::now();
    let mut miner_iteration_count: u64 = 0;
    let mut moving_average = MovingAverage::new();
    loop {
        let elapsed: u128 = progress_time.elapsed().as_millis();
        if elapsed >= 1000 {
            // Compute average number of iterations over the last second.
            moving_average.insert(miner_iteration_count);
            let weighted_average: u64 = moving_average.average();
            moving_average.rotate();
            metrics.number_of_iteration_now.set(weighted_average);

            progress_time = Instant::now();
            miner_iteration_count = 0;
        }

        let timeout = Duration::from_millis(1000);
        let message: SignedMessage = match ctx.try_recv_timeout(timeout).await {
            Ok(message) => message,
            Err(error) => {
                if let ReceiveError::Timeout(_duration) = error {
                    debug!("metrics_worker_server: timeout happened");
                    continue;
                }
                error!("metrics_worker_server: Unknown error happened. error: {:?}", error);
                continue;
            }
        };
        MessageHandler::new(message)
            .on_tell(|metric_event: MetricEvent, _| {
                if let MetricEvent::General { number_of_iterations, .. } = metric_event {
                    miner_iteration_count += number_of_iterations;
                }
                metrics.record(&metric_event);
            })
            .on_fallback(|unknown, _sender_addr| {
                error!(
                    "metrics_worker_server {}, received an unknown message!:\n{:?}",
                    ctx.current().id(),
                    unknown
                );
            });
    }
}

/// Inspect metrics from commandline.
/// 
/// Prints stats with 1 second interval.
async fn metrics_worker_print(ctx: BastionContext) -> Result<(), ()> {
    debug!("metrics_worker_print is ready");
    let mut progress_time = Instant::now();
    let mut miner_iteration_count: u64 = 0;
    let mut metric_event_count: u64 = 0;
    loop {
        let elapsed: u128 = progress_time.elapsed().as_millis();
        if elapsed >= 1000 {
            if miner_iteration_count > 0 {
                println!("miner_iterations: {}", miner_iteration_count);
            } else {
                debug!("metrics_worker_print: metric_events: {} miner_iterations: {} - no activity", metric_event_count, miner_iteration_count);
            }
            progress_time = Instant::now();
            miner_iteration_count = 0;
            metric_event_count = 0;
        }

        let timeout = Duration::from_millis(1000);
        let message: SignedMessage = match ctx.try_recv_timeout(timeout).await {
            Ok(message) => message,
            Err(error) => {
                if let ReceiveError::Timeout(_duration) = error {
                    debug!("metrics_worker_print: timeout happened");
                    continue;
                }
                error!("metrics_worker_print: Unknown error happened. error: {:?}", error);
                continue;
            }
        };
        MessageHandler::new(message)
            .on_tell(|metric_event: MetricEvent, _| {
                metric_event_count += 1;
                if let MetricEvent::General { number_of_iterations, .. } = metric_event {
                    miner_iteration_count += number_of_iterations;
                }
            })
            .on_fallback(|unknown, _sender_addr| {
                error!(
                    "metrics_worker_print {}, received an unknown message!:\n{:?}",
                    ctx.current().id(),
                    unknown
                );
            });
    }
}