Skip to main content

orca/
main.rs

1#![deny(warnings)]
2#![warn(unused_extern_crates)]
3#![allow(clippy::panic)]
4#![deny(clippy::unreachable)]
5#![deny(clippy::await_holding_lock)]
6#![deny(clippy::needless_pass_by_value)]
7#![deny(clippy::trivially_copy_pass_by_ref)]
8
9#[macro_use]
10extern crate tracing;
11
12use std::process::ExitCode;
13
14use clap::Parser;
15use opt::OrcaOpt;
16
17use crate::profile::{Profile, ProfileBuilder};
18
19use tokio::{runtime::Runtime, sync::broadcast};
20
21mod error;
22mod generate;
23mod kani;
24mod model;
25mod models;
26mod opt;
27mod populate;
28mod profile;
29mod run;
30mod state;
31mod stats;
32
33impl OrcaOpt {
34    fn debug(&self) -> bool {
35        match self {
36            OrcaOpt::Version { common }
37            | OrcaOpt::SetupWizard { common, .. }
38            | OrcaOpt::TestConnection { common, .. }
39            | OrcaOpt::GenerateData { common, .. }
40            | OrcaOpt::PopulateData { common, .. }
41            | OrcaOpt::Run { common, .. } => common.debug,
42        }
43    }
44}
45
46fn main() -> ExitCode {
47    let opt = OrcaOpt::parse();
48
49    if opt.debug() {
50        ::std::env::set_var(
51            "RUST_LOG",
52            "orca=debug,kanidm=debug,kanidm_client=debug,webauthn=debug",
53        );
54    }
55
56    tracing_subscriber::fmt::init();
57
58    info!("Orca - the Kanidm Load Testing Utility.");
59    debug!("cli -> {:?}", opt);
60    match opt {
61        OrcaOpt::Version { .. } => {
62            println!("orca {}", env!("KANIDM_PKG_VERSION"));
63            ExitCode::SUCCESS
64        }
65
66        // Build the profile and the test dimensions.
67        OrcaOpt::SetupWizard {
68            common: _,
69            admin_password,
70            idm_admin_password,
71            control_uri,
72            seed,
73            profile_path,
74            threads,
75            model,
76            dump_raw_data,
77        } => {
78            // For now I hardcoded some dimensions, but we should prompt
79            // the user for these later.
80
81            let seed = seed.map(|seed| {
82                if seed < 0 {
83                    seed.wrapping_mul(-1) as u64
84                } else {
85                    seed as u64
86                }
87            });
88
89            let extra_uris = Vec::with_capacity(0);
90
91            let builder = ProfileBuilder::new(
92                control_uri,
93                extra_uris,
94                admin_password,
95                idm_admin_password,
96                model,
97                threads,
98                dump_raw_data,
99            )
100            .seed(seed);
101
102            let profile = match builder.build() {
103                Ok(p) => p,
104                Err(_err) => {
105                    return ExitCode::FAILURE;
106                }
107            };
108
109            match profile.write_to_path(&profile_path) {
110                Ok(_) => ExitCode::SUCCESS,
111                Err(_err) => ExitCode::FAILURE,
112            }
113        }
114
115        // Test the connection
116        OrcaOpt::TestConnection {
117            common: _,
118            profile_path,
119        } => {
120            let profile = match Profile::try_from(profile_path.as_path()) {
121                Ok(p) => p,
122                Err(_err) => {
123                    return ExitCode::FAILURE;
124                }
125            };
126
127            info!("Performing conntest of {}", profile.control_uri());
128
129            // we're okay with just one thread here
130            let runtime = build_tokio_runtime(Some(1));
131            runtime.block_on(async {
132                match kani::KanidmOrcaClient::new(&profile).await {
133                    Ok(_) => {
134                        info!("success");
135                        ExitCode::SUCCESS
136                    }
137                    Err(_err) => ExitCode::FAILURE,
138                }
139            })
140        }
141
142        // From the profile and test dimensions, generate the data into a state file.
143        OrcaOpt::GenerateData {
144            common: _,
145            profile_path,
146            state_path,
147        } => {
148            let profile = match Profile::try_from(profile_path.as_path()) {
149                Ok(p) => p,
150                Err(_err) => {
151                    return ExitCode::FAILURE;
152                }
153            };
154
155            // This is single threaded.
156            let runtime = build_tokio_runtime(Some(1));
157
158            runtime.block_on(async {
159                let client = match kani::KanidmOrcaClient::new(&profile).await {
160                    Ok(client) => client,
161                    Err(_err) => {
162                        return ExitCode::FAILURE;
163                    }
164                };
165
166                // do-it.
167                let state = match generate::populate(&client, profile).await {
168                    Ok(s) => s,
169                    Err(_err) => {
170                        return ExitCode::FAILURE;
171                    }
172                };
173
174                match state.write_to_path(&state_path) {
175                    Ok(_) => ExitCode::SUCCESS,
176                    Err(_err) => ExitCode::FAILURE,
177                }
178            })
179        }
180
181        //
182        OrcaOpt::PopulateData {
183            common: _,
184            state_path,
185        } => {
186            let state = match state::State::try_from(state_path.as_path()) {
187                Ok(p) => p,
188                Err(_err) => {
189                    return ExitCode::FAILURE;
190                }
191            };
192
193            // here we want all threads available to speed up the process.
194            let runtime = build_tokio_runtime(state.thread_count);
195
196            runtime.block_on(async {
197                match populate::preflight(state).await {
198                    Ok(_) => ExitCode::SUCCESS,
199                    Err(_err) => ExitCode::FAILURE,
200                }
201            })
202        }
203
204        // Run the test based on the state file.
205        OrcaOpt::Run {
206            common: _,
207            state_path,
208        } => {
209            let state = match state::State::try_from(state_path.as_path()) {
210                Ok(p) => p,
211                Err(_err) => {
212                    return ExitCode::FAILURE;
213                }
214            };
215            // here we need to create one less worker compared to the desired amount since we later call `spawn_blocking`, which consumes
216            // an extra thread all on its own
217            let runtime = build_tokio_runtime(state.thread_count);
218            // We have a broadcast channel setup for controlling the state of
219            // various actors and parts.
220            //
221            // We want a small amount of backlog because there are a few possible
222            // commands that could be sent.
223            runtime.block_on(async {
224                let (control_tx, control_rx) = broadcast::channel(8);
225
226                let mut run_execute = tokio::task::spawn(run::execute(state, control_rx));
227
228                loop {
229                    tokio::select! {
230                        // Note that we pass a &mut handle here because we want the future to join
231                        // but not be consumed each loop iteration.
232                        result = &mut run_execute => {
233                            match result {
234                                Ok(_) => {
235                                    return ExitCode::SUCCESS;
236                                }
237                                Err(_err) => {
238                                    return ExitCode::FAILURE;
239                                }
240                            };
241                        }
242                        // Signal handling.
243                        Ok(()) = tokio::signal::ctrl_c() => {
244                            info!("Stopping Task ...");
245                            let _ = control_tx.send(run::Signal::Stop);
246                        }
247                        Some(()) = async move {
248                            let sigterm = tokio::signal::unix::SignalKind::terminate();
249                            #[allow(clippy::unwrap_used)]
250                            tokio::signal::unix::signal(sigterm).unwrap().recv().await
251                        } => {
252                            // Kill it with fire I guess.
253                            return ExitCode::FAILURE;
254                        }
255                        Some(()) = async move {
256                            let sigterm = tokio::signal::unix::SignalKind::alarm();
257                            #[allow(clippy::unwrap_used)]
258                            tokio::signal::unix::signal(sigterm).unwrap().recv().await
259                        } => {
260                            // Ignore
261                        }
262                        Some(()) = async move {
263                            let sigterm = tokio::signal::unix::SignalKind::hangup();
264                            #[allow(clippy::unwrap_used)]
265                            tokio::signal::unix::signal(sigterm).unwrap().recv().await
266                        } => {
267                            // Ignore
268                        }
269                        Some(()) = async move {
270                            let sigterm = tokio::signal::unix::SignalKind::user_defined1();
271                            #[allow(clippy::unwrap_used)]
272                            tokio::signal::unix::signal(sigterm).unwrap().recv().await
273                        } => {
274                            // Ignore
275                        }
276                        Some(()) = async move {
277                            let sigterm = tokio::signal::unix::SignalKind::user_defined2();
278                            #[allow(clippy::unwrap_used)]
279                            tokio::signal::unix::signal(sigterm).unwrap().recv().await
280                        } => {
281                            // Ignore
282                        }
283                    }
284                }
285            })
286        }
287    }
288}
289
290/// Build the tokio runtime with the configured number of threads. If set to None, then the maximum
291/// of the system is used.
292fn build_tokio_runtime(threads: Option<usize>) -> Runtime {
293    let mut builder = tokio::runtime::Builder::new_multi_thread();
294    match threads {
295        Some(threads) => builder.worker_threads(threads),
296        None => &mut builder,
297    }
298    .enable_all()
299    .build()
300    .expect("Failed to build tokio runtime")
301}