pub mod db;
pub mod backtrace;
use std::cell::RefCell;
use std::fs::File;
use std::str::FromStr;
use std::thread;
use std::time::SystemTime;
use serde::{Deserialize, Serialize};
pub use db::{Db, DBReader};
pub use backtrace::{Backtrace, Frame};
const WRITE_THRESHOLD: usize = 16;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Mode {
Lock,
TryLock,
Park,
}
impl FromStr for Mode {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"lock" => Ok(Mode::Lock),
"trylock" => Ok(Mode::TryLock),
"park" => Ok(Mode::Park),
_ => Err("Invalid mode".to_string()),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Contention {
pub time: SystemTime,
pub mode: Mode,
pub backtrace: Backtrace
}
thread_local! {
static CONTENTIONS: RefCell<Vec<Contention>> = RefCell::new(Vec::new());
static DB: RefCell<Option<Db<File, Contention>>> = RefCell::new(None);
}
pub fn contended(mode: Mode) {
let backtrace = Backtrace::capture();
let time: SystemTime = SystemTime::now();
let contention = Contention { time, mode, backtrace };
CONTENTIONS.with(|contentions| {
let mut contentions = contentions.borrow_mut();
contentions.push(contention);
if contentions.len() >= WRITE_THRESHOLD {
DB.with(|db_cell| {
let mut db_opt = db_cell.borrow_mut();
if db_opt.is_none() {
let current_thread = thread::current();
let thread_id = current_thread.id();
let filename = format!("contention-{:?}.db", thread_id);
*db_opt = Some(Db::open(&filename).expect("Failed to open contention DB"));
}
if let Some(db) = db_opt.as_mut() {
db.store(&contentions).expect("Failed to write contentions to DB");
}
});
contentions.clear();
}
});
}