random_crash/
lib.rs

1// Copyright 2020 Conflux Foundation. All rights reserved.
2// Conflux is free software and distributed under GNU General Public License.
3// See http://www.gnu.org/licenses/
4
5use lazy_static::lazy_static;
6/// This module can trigger random process crashes during testing.
7/// This is only used to insert crashes before db modifications.
8use log::info;
9
10use parking_lot::Mutex;
11use rand::{rng, Rng};
12lazy_static! {
13    /// The process exit code set for random crash.
14    pub static ref CRASH_EXIT_CODE: Mutex<i32> = Mutex::new(100);
15    /// The probability to trigger a random crash.
16    /// Set to `None` to disable random crash.
17    pub static ref CRASH_EXIT_PROBABILITY: Mutex<Option<f64>> =
18        Mutex::new(None);
19}
20
21/// Randomly crash with the probability and exit code already set.
22pub fn random_crash_if_enabled(exit_str: &str) {
23    if let Some(p) = *CRASH_EXIT_PROBABILITY.lock() {
24        if rng().random_bool(p) {
25            info!("exit before {}", exit_str);
26            std::process::exit(*CRASH_EXIT_CODE.lock());
27        }
28    }
29}