1use crate::{
2 error::Error,
3 run::{EventDetail, EventRecord},
4};
5use chrono::Local;
6use crossbeam::queue::{ArrayQueue, SegQueue};
7use csv::Writer;
8use serde::Serialize;
9use std::{
10 sync::Arc,
11 thread,
12 time::{Duration, Instant},
13};
14
15use mathru::statistics::distrib::{Continuous, Normal};
16
17#[derive(Debug)]
18pub enum TestPhase {
19 Start(Instant),
20 End(Instant),
21 StopNow,
22}
23
24pub trait DataCollector {
25 fn run(
26 &mut self,
27 stats_queue: Arc<SegQueue<EventRecord>>,
28 ctrl: Arc<ArrayQueue<TestPhase>>,
29 dump_raw_data: bool,
30 ) -> Result<(), Error>;
31}
32
33enum OpKind {
34 WriteOp,
35 ReadOp,
36 ReplicationDelay,
37 Auth, Error,
39}
40
41impl From<EventDetail> for OpKind {
42 fn from(value: EventDetail) -> Self {
43 match value {
44 EventDetail::PersonGetSelfMemberOf | EventDetail::PersonGetSelfAccount => {
45 OpKind::ReadOp
46 }
47 EventDetail::PersonSetSelfMail
48 | EventDetail::PersonSetSelfPassword
49 | EventDetail::PersonCreateGroup
50 | EventDetail::PersonAddGroupMembers => OpKind::WriteOp,
51 EventDetail::Login | EventDetail::Logout | EventDetail::PersonReauth => OpKind::Auth,
52 EventDetail::GroupReplicationDelay => OpKind::ReplicationDelay,
53 EventDetail::Error => OpKind::Error,
54 }
55 }
56}
57pub struct BasicStatistics {
58 person_count: usize,
59 group_count: usize,
60 node_count: usize,
61}
62
63impl BasicStatistics {
64 #[allow(clippy::new_ret_no_self)]
65 pub fn new(
66 person_count: usize,
67 group_count: usize,
68 node_count: usize,
69 ) -> Box<dyn DataCollector + Send> {
70 Box::new(BasicStatistics {
71 person_count,
72 group_count,
73 node_count,
74 })
75 }
76}
77
78impl DataCollector for BasicStatistics {
79 fn run(
80 &mut self,
81 stats_queue: Arc<SegQueue<EventRecord>>,
82 ctrl: Arc<ArrayQueue<TestPhase>>,
83 dump_raw_data: bool,
84 ) -> Result<(), Error> {
85 debug!("Started statistics collector");
86
87 let start = loop {
90 match ctrl.pop() {
91 Some(TestPhase::Start(start)) => {
92 break start;
93 }
94 Some(TestPhase::End(_)) => {
95 error!("invalid state");
96 return Err(Error::InvalidState);
98 }
99 Some(TestPhase::StopNow) => {
100 return Ok(());
102 }
103 None => {
104 #[allow(clippy::disallowed_methods)]
105 thread::sleep(Duration::from_millis(100))
107 }
108 }
109 };
110
111 let end = loop {
113 match ctrl.pop() {
114 Some(TestPhase::Start(_)) => {
115 return Err(Error::InvalidState);
117 }
118 Some(TestPhase::End(end)) => {
119 break end;
120 }
121 Some(TestPhase::StopNow) => {
122 warn!("requested to stop now!");
123 return Ok(());
125 }
126 None => {
127 #[allow(clippy::disallowed_methods)]
128 thread::sleep(Duration::from_millis(100))
130 }
131 }
132 };
133
134 info!("start statistics processing ...");
135
136 let mut readop_times = Vec::new();
137 let mut writeop_times = Vec::new();
138 let mut replication_delays = Vec::new();
139 let mut raw_stats = Vec::new();
140
141 while let Some(event_record) = stats_queue.pop() {
143 if event_record.start < start || event_record.start > end {
144 continue;
146 }
147
148 if dump_raw_data {
149 raw_stats.push(SerializableEventRecord::from_event_record(
150 &event_record,
151 start,
152 ));
153 }
154
155 match OpKind::from(event_record.details) {
156 OpKind::ReadOp => {
157 readop_times.push(event_record.duration.as_secs_f64());
158 }
159 OpKind::WriteOp => {
160 writeop_times.push(event_record.duration.as_secs_f64());
161 }
162 OpKind::ReplicationDelay => {
163 replication_delays.push(event_record.duration.as_secs_f64())
164 }
165 OpKind::Auth => {}
166 OpKind::Error => {}
167 }
168 }
169
170 if readop_times.is_empty() && writeop_times.is_empty() && replication_delays.is_empty() {
171 error!("For some weird reason no valid data was recorded in this benchmark, bailing out...");
172 return Err(Error::InvalidState);
173 }
174
175 let stats = StatsContainer::new(
176 &readop_times,
177 &writeop_times,
178 &replication_delays,
179 self.node_count,
180 self.person_count,
181 self.group_count,
182 );
183
184 info!(
185 "Server configuration was: {} nodes, {} users and {} groups",
186 self.node_count, self.person_count, self.group_count
187 );
188
189 info!("Received {} read events", stats.read_events);
190
191 info!("mean: {} seconds", stats.read_mean);
192 info!("variance: {} seconds", stats.read_variance);
193 info!("SD: {} seconds", stats.read_sd);
194 info!("95%: {}", stats.read_95);
195
196 info!("Received {} write events", stats.write_events);
197
198 info!("mean: {} seconds", stats.write_mean);
199 info!("variance: {} seconds", stats.write_variance);
200 info!("SD: {} seconds", stats.write_sd);
201 info!("95%: {}", stats.write_95);
202
203 info!(
204 "Received {} replication delays",
205 stats.replication_delay_events
206 );
207
208 info!("mean: {} seconds", stats.replication_delay_mean);
209 info!("variance: {} seconds", stats.replication_delay_variance);
210 info!("SD: {} seconds", stats.replication_delay_sd);
211 info!("95%: {}", stats.replication_delay_95);
212
213 let now = Local::now();
214 let filepath = format!("orca-run-{}.csv", now.to_rfc3339());
215
216 info!("Now saving stats as '{filepath}'");
217
218 let mut wrt = Writer::from_path(filepath).map_err(|_| Error::Io)?;
219 wrt.serialize(stats).map_err(|_| Error::Io)?;
220
221 if dump_raw_data {
222 let raw_data_filepath = format!("orca-run-{}-raw.csv", now.to_rfc3339());
223 info!("Now saving raw data as '{raw_data_filepath}'");
224
225 let mut wrt = Writer::from_path(raw_data_filepath).map_err(|_| Error::Io)?;
226
227 for record in raw_stats.iter() {
228 wrt.serialize(record).map_err(|_| Error::Io)?;
229 }
230 }
231
232 debug!("Ended statistics collector");
233
234 Ok(())
235 }
236}
237
238#[derive(Serialize)]
239struct SerializableEventRecord {
240 time_from_start_ms: u128,
241 duration_ms: u128,
242 details: EventDetail,
243}
244
245impl SerializableEventRecord {
246 fn from_event_record(event_record: &EventRecord, test_start: Instant) -> Self {
247 SerializableEventRecord {
248 time_from_start_ms: event_record.start.duration_since(test_start).as_millis(),
249 duration_ms: event_record.duration.as_millis(),
250 details: event_record.details.clone(),
251 }
252 }
253}
254
255#[derive(Serialize)]
256struct StatsContainer {
257 node_count: usize,
258 person_count: usize,
259 group_count: usize,
260 read_events: usize,
261 read_sd: f64,
262 read_mean: f64,
263 read_variance: f64,
264 read_95: f64,
265 write_events: usize,
266 write_sd: f64,
267 write_mean: f64,
268 write_variance: f64,
269 write_95: f64,
270 replication_delay_events: usize,
271 replication_delay_sd: f64,
272 replication_delay_mean: f64,
273 replication_delay_variance: f64,
274 replication_delay_95: f64,
275}
276
277type EventCount = usize;
279type Mean = f64;
280type Sd = f64;
281type Variance = f64;
282type Percentile95 = f64;
283
284impl StatsContainer {
285 fn new(
286 readop_times: &[f64],
287 writeop_times: &[f64],
288 replication_delays: &[f64],
289 node_count: usize,
290 person_count: usize,
291 group_count: usize,
292 ) -> Self {
293 let (read_events, read_mean, read_variance, read_sd, read_95) =
294 Self::compute_stats_from_timings_vec(readop_times);
295
296 let (write_events, write_mean, write_variance, write_sd, write_95) =
297 Self::compute_stats_from_timings_vec(writeop_times);
298
299 let (
300 replication_delay_events,
301 replication_delay_mean,
302 replication_delay_variance,
303 replication_delay_sd,
304 replication_delay_95,
305 ) = Self::compute_stats_from_timings_vec(replication_delays);
306
307 StatsContainer {
308 person_count,
309 group_count,
310 node_count,
311 read_events,
312 read_sd,
313 read_mean,
314 read_variance,
315 read_95,
316 write_events,
317 write_sd,
318 write_mean,
319 write_variance,
320 write_95,
321 replication_delay_events,
322 replication_delay_sd,
323 replication_delay_mean,
324 replication_delay_variance,
325 replication_delay_95,
326 }
327 }
328
329 fn compute_stats_from_timings_vec(
330 op_times: &[f64],
331 ) -> (EventCount, Mean, Variance, Sd, Percentile95) {
332 let op_times_len = op_times.len();
333 if op_times_len >= 2 {
334 let distr = Normal::from_data(op_times);
335 let mean = distr.mean();
336 let variance = distr.variance();
337 let sd = variance.sqrt();
338 let percentile_95 = mean + 2. * sd;
339 (op_times_len, mean, variance, sd, percentile_95)
340 } else {
341 (0, 0., 0., 0., 0.)
342 }
343 }
344}