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
use super::ScenarioProgressBar;
use crate::mjolnir_lib::{bootstrap::ClientLoadConfig, MjolnirError};
use assert_fs::TempDir;
use indicatif::{MultiProgress, ProgressBar};
use jormungandr_automation::{
    jormungandr::{JormungandrProcess, LogLevel},
    testing::{benchmark_speed, SpeedBenchmarkFinish, SpeedBenchmarkRun},
};
use jormungandr_lib::interfaces::NodeState;
use std::{
    thread,
    time::{Duration, Instant},
};

pub struct DurationBasedClientLoad {
    config: ClientLoadConfig,
    duration: u64,
}

impl DurationBasedClientLoad {
    pub fn new(config: ClientLoadConfig, duration: u64) -> Self {
        Self { config, duration }
    }

    pub fn run(&self) -> Result<(), MjolnirError> {
        let m = MultiProgress::new();
        let mut results = vec![];
        let mut handles = vec![];

        for client_id in 1..=self.config.count() {
            handles.push(self.run_single(client_id, self.duration, &m)?);
        }
        m.join_and_clear().unwrap();

        for handle in handles {
            results.push(
                handle
                    .join()
                    .map_err(|_| MjolnirError::InternalClientError)?,
            );
        }

        if self.config.measure() {
            for overall_result in results {
                if let Ok(measurements) = &overall_result {
                    for measurement in measurements {
                        println!("{}", measurement);
                    }
                }
            }
        }
        Ok(())
    }

    fn wait_for_bootstrap_phase_completed(
        node: &JormungandrProcess,
        instant: &Instant,
        target: u64,
        benchmark: SpeedBenchmarkRun,
        progress_bar: &ScenarioProgressBar,
    ) -> Result<Option<SpeedBenchmarkFinish>, MjolnirError> {
        loop {
            thread::sleep(Duration::from_secs(2));
            progress_bar.set_progress(&format!(
                "progress: {}/{}",
                instant.elapsed().as_secs(),
                target
            ));

            node.check_no_errors_in_log()?;

            progress_bar.set_error_lines(
                node.logger
                    .get_log_lines_with_level(LogLevel::ERROR)
                    .map(|x| x.to_string())
                    .collect(),
            );

            if instant.elapsed().as_secs() > target {
                return Ok(None);
            }

            let stats = node.rest().stats()?;

            if stats.state == NodeState::Running {
                progress_bar.set_finished();
                return Ok(Some(benchmark.stop()));
            }
        }
    }

    fn run_single(
        &self,
        id: u32,
        duration: u64,
        multi_progress: &MultiProgress,
    ) -> Result<thread::JoinHandle<Result<Vec<SpeedBenchmarkFinish>, MjolnirError>>, MjolnirError>
    {
        let temp_dir = TempDir::new().unwrap().into_persistent();
        let storage_folder_name = format!("client_{}", id);

        let progress_bar = ScenarioProgressBar::new(
            multi_progress.add(ProgressBar::new(1)),
            &format!("[Node: {}]", id),
        );
        let mut benchmarks = vec![];
        let timer = Instant::now();

        let config = self.config.clone();
        let mut node = super::start_node(&config, &storage_folder_name, &temp_dir)?;

        Ok(thread::spawn(move || {
            loop {
                let benchmark = benchmark_speed(storage_folder_name.clone())
                    .no_target()
                    .start();
                let benchmark_result = Self::wait_for_bootstrap_phase_completed(
                    &node,
                    &timer,
                    duration,
                    benchmark,
                    &progress_bar,
                )?;

                match benchmark_result {
                    Some(benchmark) => benchmarks.push(benchmark),
                    // if there are no new benchmarks it means that test finished
                    None => return Ok(benchmarks),
                };

                node.shutdown();
                thread::sleep(Duration::from_secs(config.pace()));
                node = super::start_node(&config, &storage_folder_name, &temp_dir)?;
            }
        }))
    }
}