Skip to main content

orca/
run.rs

1use crate::{
2    error::Error,
3    state::*,
4    stats::{BasicStatistics, TestPhase},
5};
6
7use std::sync::Arc;
8
9use rand::{RngExt, SeedableRng};
10use rand_chacha::ChaCha8Rng;
11
12use crossbeam::queue::{ArrayQueue, SegQueue};
13
14use kanidm_client::{KanidmClient, KanidmClientBuilder};
15
16use serde::Serialize;
17use tokio::sync::broadcast;
18
19use std::time::{Duration, Instant};
20
21async fn actor_person(
22    main_client: KanidmClient,
23    person: Person,
24    stats_queue: Arc<SegQueue<EventRecord>>,
25    mut actor_rx: broadcast::Receiver<Signal>,
26    rng_seed: u64,
27    additional_clients: Vec<KanidmClient>,
28    warmup_time: Duration,
29) -> Result<(), Error> {
30    let mut model =
31        person
32            .model
33            .as_dyn_object(rng_seed, additional_clients, &person.username, warmup_time)?;
34
35    while let Err(broadcast::error::TryRecvError::Empty) = actor_rx.try_recv() {
36        let events = model.transition(&main_client, &person).await?;
37        debug!("Pushed event to queue!");
38        for event in events.into_iter() {
39            stats_queue.push(event);
40        }
41    }
42
43    debug!("Stopped person {}", person.username);
44    Ok(())
45}
46
47#[derive(Debug)]
48pub struct EventRecord {
49    pub start: Instant,
50    pub duration: Duration,
51    pub details: EventDetail,
52}
53
54#[derive(Debug, Serialize, Clone)]
55pub enum EventDetail {
56    Login,
57    Logout,
58    PersonSetSelfMail,
59    PersonGetSelfAccount,
60    PersonGetSelfMemberOf,
61    PersonSetSelfPassword,
62    PersonReauth,
63    PersonCreateGroup,
64    PersonAddGroupMembers,
65    GroupReplicationDelay,
66    Error,
67}
68
69#[derive(Clone, Debug)]
70pub enum Signal {
71    Stop,
72}
73
74async fn execute_inner(
75    warmup: Duration,
76    test_time: Option<Duration>,
77    mut control_rx: broadcast::Receiver<Signal>,
78    stat_ctrl: Arc<ArrayQueue<TestPhase>>,
79) -> Result<(), Error> {
80    // Delay for warmup time.
81    tokio::select! {
82        _ = tokio::time::sleep(warmup) => {
83            // continue.
84        }
85        _ = control_rx.recv() => {
86            // Until we add other signal types, any event is
87            // either Ok(Signal::Stop) or Err(_), both of which indicate
88            // we need to stop immediately.
89            return Err(Error::Interrupt);
90        }
91    }
92    info!("warmup time passed, statistics will now be collected ...");
93
94    let start = Instant::now();
95    if let Err(crossbeam_err) = stat_ctrl.push(TestPhase::Start(start)) {
96        error!(
97            ?crossbeam_err,
98            "Unable to signal statistics collector to start"
99        );
100        return Err(Error::Crossbeam);
101    }
102
103    if let Some(test_time) = test_time {
104        let sleep = tokio::time::sleep(test_time);
105        tokio::pin!(sleep);
106        let recv = (control_rx).recv();
107        tokio::pin!(recv);
108
109        // Wait for some condition (signal, or time).
110        tokio::select! {
111            _ = sleep => {
112                // continue.
113            }
114            _ = recv => {
115                // Until we add other signal types, any event is
116                // either Ok(Signal::Stop) or Err(_), both of which indicate
117                // we need to stop immediately.
118                debug!("Interrupt");
119                return Err(Error::Interrupt);
120            }
121        }
122    } else {
123        let _ = control_rx.recv().await;
124    }
125
126    let end = Instant::now();
127    if let Err(crossbeam_err) = stat_ctrl.push(TestPhase::End(end)) {
128        error!(
129            ?crossbeam_err,
130            "Unable to signal statistics collector to end"
131        );
132        return Err(Error::Crossbeam);
133    }
134
135    Ok(())
136}
137
138pub async fn execute(state: State, control_rx: broadcast::Receiver<Signal>) -> Result<(), Error> {
139    // Create a statistics queue.
140    let stats_queue = Arc::new(SegQueue::new());
141    let stats_ctrl = Arc::new(ArrayQueue::new(4));
142
143    // Spawn the stats aggregator
144    let c_stats_queue = stats_queue.clone();
145    let c_stats_ctrl = stats_ctrl.clone();
146
147    let node_count = 1 + state.profile.extra_uris().len();
148    let mut dyn_data_collector =
149        BasicStatistics::new(state.persons.len(), state.groups.len(), node_count);
150
151    let dump_raw_data = state.profile.dump_raw_data();
152
153    let stats_task = tokio::task::spawn_blocking(move || {
154        dyn_data_collector.run(c_stats_queue, c_stats_ctrl, dump_raw_data)
155    });
156
157    // Create clients. Note, we actually seed these deterministically too, so that
158    // or persons are spread over the clients that exist, in a way that is also
159    // deterministic.
160    let mut seeded_rng = ChaCha8Rng::seed_from_u64(state.profile.seed());
161
162    let clients = std::iter::once(state.profile.control_uri().to_string())
163        .chain(state.profile.extra_uris().iter().cloned())
164        .map(|uri| {
165            KanidmClientBuilder::new()
166                .address(uri)
167                .danger_accept_invalid_hostnames(true)
168                .danger_accept_invalid_certs(true)
169                .build()
170                .map_err(|err| {
171                    error!(?err, "Unable to create kanidm client");
172                    Error::KanidmClient
173                })
174        })
175        .collect::<Result<Vec<_>, _>>()?;
176
177    let (actor_tx, _actor_rx) = broadcast::channel(1);
178
179    // Start the actors
180    let mut tasks = Vec::with_capacity(state.persons.len());
181    for person in state.persons.into_iter() {
182        // this is not super efficient but we don't really care as we are not even inside the warmup time window, so we're not in a hurry
183        let mut cloned_clients: Vec<KanidmClient> = clients
184            .iter()
185            .map(|client| {
186                client.new_session().map_err(|err| {
187                    error!(?err, "Unable to create a new kanidm client session");
188                    Error::KanidmClient
189                })
190            })
191            .collect::<Result<Vec<_>, _>>()?;
192        let main_client_index = seeded_rng.random_range(0..cloned_clients.len());
193        let main_client = cloned_clients.remove(main_client_index);
194        //note that cloned_clients now contains all other clients except the first one
195
196        let c_stats_queue = stats_queue.clone();
197
198        let c_actor_rx = actor_tx.subscribe();
199
200        tasks.push(tokio::spawn(actor_person(
201            main_client,
202            person,
203            c_stats_queue,
204            c_actor_rx,
205            state.profile.seed(),
206            cloned_clients,
207            state.profile.warmup_time(),
208        )))
209    }
210
211    let warmup = state.profile.warmup_time();
212    let test_time = state.profile.test_time();
213
214    // We run a separate test inner so we don't have to worry about
215    // task spawn/join within our logic.
216    let c_stats_ctrl = stats_ctrl.clone();
217    // Don't ? this, we want to stash the result so we cleanly stop all the workers
218    // before returning the inner test result.
219    let test_result = execute_inner(warmup, test_time, control_rx, c_stats_ctrl).await;
220
221    info!("stopping stats");
222
223    // The statistics collector has been working in the BG, and was likely told
224    // to end by now, but if not (due to an error) send a signal to stop immediately.
225    if let Err(crossbeam_err) = stats_ctrl.push(TestPhase::StopNow) {
226        error!(
227            ?crossbeam_err,
228            "Unable to signal statistics collector to stop"
229        );
230        return Err(Error::Crossbeam);
231    }
232
233    info!("stopping workers");
234
235    // Test workers to stop
236    actor_tx.send(Signal::Stop).map_err(|broadcast_err| {
237        error!(?broadcast_err, "Unable to signal workers to stop");
238        Error::Tokio
239    })?;
240
241    info!("joining workers");
242
243    // Join all the tasks.
244    for task in tasks {
245        task.await.map_err(|tokio_err| {
246            error!(?tokio_err, "Failed to join task");
247            Error::Tokio
248        })??;
249        // The double ? isn't a mistake, it's because this is Result<Result<T, E>, E>
250        // and flatten is nightly.
251    }
252
253    // By this point the stats task should have been told to halt and rejoin.
254    stats_task.await.map_err(|tokio_err| {
255        error!(?tokio_err, "Failed to join statistics task");
256        Error::Tokio
257    })??;
258    // Not an error, two ? to handle the inner data collector error.
259
260    // Complete!
261
262    test_result
263}