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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
use backtrace::Backtrace;
use parking_lot::{Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard};
use snowflake::ProcessUniqueId;
use std::{
    collections::HashMap,
    ops::{Deref, DerefMut},
    thread,
    time::{Duration, Instant},
};

// if a lock guard lives this long, it is assumed it will never die
const IMMORTAL_TIMEOUT_SECS: u64 = 60;

// this should be at least twice the IMMORTAL_TIMEOUT, so that locks don't timeout
// before all long-running guards are detected, in the case of a deadlock
const LOCK_TIMEOUT_SECS: u64 = 150;

// This is how often we check the elapsed time of guards
const GUARD_WATCHER_POLL_INTERVAL_MS: u64 = 1000;

// We filter out any guards alive less than this long
const ACTIVE_GUARD_MIN_ELAPSED_MS: i64 = 500;

// How often to retry getting a lock after receiving a WouldBlock error
// during try_lock
const LOCK_POLL_INTERVAL_MS: u64 = 10;

#[derive(Debug)]
pub enum HcLockErrorKind {
    HcLockTimeout,
    HcLockPoisonError,
    HcLockWouldBlock,
}

#[derive(Debug)]
pub enum LockType {
    Lock,
    Read,
    Write,
}

#[derive(Debug)]
pub struct HcLockError {
    lock_type: LockType,
    backtraces: Option<Vec<Backtrace>>,
    kind: HcLockErrorKind,
}

impl HcLockError {
    pub fn new(lock_type: LockType, kind: HcLockErrorKind) -> Self {
        Self {
            lock_type,
            backtraces: None,
            kind,
        }
    }
}

pub type HcLockResult<T> = Result<T, HcLockError>;

struct GuardTracker {
    puid: ProcessUniqueId,
    created: Instant,
    backtrace: Backtrace,
    lock_type: LockType,
    immortal: bool,
}

impl GuardTracker {
    pub fn new(puid: ProcessUniqueId, lock_type: LockType) -> Self {
        Self {
            puid,
            lock_type,
            created: Instant::now(),
            backtrace: Backtrace::new_unresolved(),
            immortal: false,
        }
    }

    pub fn report_and_update(&mut self) -> Option<(i64, String)> {
        let elapsed = Instant::now().duration_since(self.created);
        let elapsed_ms = elapsed.as_millis() as i64;
        if elapsed_ms > ACTIVE_GUARD_MIN_ELAPSED_MS {
            if !self.immortal && elapsed.as_secs() > IMMORTAL_TIMEOUT_SECS {
                self.immortalize();
            }
            let lock_type_str = format!("{:?}", self.lock_type);
            let report = if self.immortal {
                format!(
                    "{:<6} {:<13} {:>12} [!!!]",
                    lock_type_str, self.puid, elapsed_ms
                )
            } else {
                format!("{:<6} {:<13} {:>12}", lock_type_str, self.puid, elapsed_ms)
            };
            Some((elapsed_ms, report))
        } else {
            None
        }
    }

    pub fn report_header() -> String {
        format!("{:6} {:^13} {:>12}", "KIND", "PUID", "ELAPSED (ms)")
    }

    fn immortalize(&mut self) {
        if self.immortal {
            return;
        }
        self.immortal = true;
        self.backtrace.resolve();
        error!(
            r"

        !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        !!! IMMORTAL LOCK GUARD FOUND !!!
        !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

{:?} guard {} lived for > {} seconds. Backtrace at the moment of guard creation follows:

{:?}",
            self.lock_type, self.puid, IMMORTAL_TIMEOUT_SECS, self.backtrace
        );
    }
}

lazy_static! {
    static ref GUARDS: Mutex<HashMap<ProcessUniqueId, GuardTracker>> = Mutex::new(HashMap::new());
    static ref PENDING_LOCKS: Mutex<HashMap<ProcessUniqueId, (LockType, Instant, Backtrace)>> =
        Mutex::new(HashMap::new());
}

pub fn spawn_hc_guard_watcher() {
    let _ = thread::Builder::new()
        .name(format!(
            "hc_guard_watcher/{}",
            ProcessUniqueId::new().to_string()
        ))
        .spawn(move || loop {
            let mut reports: Vec<(i64, String)> = {
                GUARDS
                    .lock()
                    .values_mut()
                    .filter_map(|gt| gt.report_and_update())
                    .collect()
            };
            if reports.len() > 0 {
                reports.sort_unstable_by_key(|(elapsed, _)| -*elapsed);
                let num_active = reports.len();
                let lines: Vec<String> = reports.into_iter().map(|(_, report)| report).collect();
                let output = lines.join("\n");
                debug!(
                    "tracking {} active guard(s) alive for > {}ms:\n{}\n{}",
                    num_active,
                    ACTIVE_GUARD_MIN_ELAPSED_MS,
                    GuardTracker::report_header(),
                    output
                );
            } else {
                debug!(
                    "no active guards alive for > {}ms",
                    ACTIVE_GUARD_MIN_ELAPSED_MS
                );
            }

            thread::sleep(Duration::from_millis(GUARD_WATCHER_POLL_INTERVAL_MS));
        });
    debug!("spawn_hc_guard_watcher: SPAWNED");
}

fn _print_pending_locks() {
    for (puid, (lock_type, instant, backtrace)) in PENDING_LOCKS.lock().iter() {
        debug!(
            "PENDING LOCK {:?} locktype={:?}, pending for {:?}, backtrace:\n{:?}",
            puid,
            lock_type,
            Instant::now().duration_since(*instant),
            backtrace
        );
    }
}

// /////////////////////////////////////////////////////////////
// GUARDS

macro_rules! guard_struct {
    ($HcGuard:ident, $Guard:ident, $lock_type:ident) => {
        pub struct $HcGuard<'a, T: ?Sized> {
            puid: ProcessUniqueId,
            inner: $Guard<'a, T>,
        }

        impl<'a, T: ?Sized> $HcGuard<'a, T> {
            pub fn new(inner: $Guard<'a, T>) -> Self {
                let puid = ProcessUniqueId::new();
                GUARDS
                    .lock()
                    .insert(puid, GuardTracker::new(puid, LockType::$lock_type));
                Self { puid, inner }
            }
        }

        impl<'a, T: ?Sized> Drop for $HcGuard<'a, T> {
            fn drop(&mut self) {
                GUARDS.lock().remove(&self.puid);
            }
        }
    };
}

guard_struct!(HcMutexGuard, MutexGuard, Lock);
guard_struct!(HcRwLockReadGuard, RwLockReadGuard, Read);
guard_struct!(HcRwLockWriteGuard, RwLockWriteGuard, Write);

// TODO: impl as appropriate
// AsRef<InnerType>
// Borrow<InnerType>
// Deref<Target=InnerType>
// AsMut<InnerType>
// BorrowMut<InnerType>
// DerefMut<Target=InnerType>

impl<'a, T: ?Sized> Deref for HcMutexGuard<'a, T> {
    type Target = T;
    fn deref(&self) -> &T {
        self.inner.deref()
    }
}

impl<'a, T: ?Sized> DerefMut for HcMutexGuard<'a, T> {
    fn deref_mut(&mut self) -> &mut T {
        self.inner.deref_mut()
    }
}

impl<'a, T: ?Sized> Deref for HcRwLockReadGuard<'a, T> {
    type Target = T;
    fn deref(&self) -> &T {
        self.inner.deref()
    }
}

impl<'a, T: ?Sized> Deref for HcRwLockWriteGuard<'a, T> {
    type Target = T;
    fn deref(&self) -> &T {
        self.inner.deref()
    }
}

impl<'a, T: ?Sized> DerefMut for HcRwLockWriteGuard<'a, T> {
    fn deref_mut(&mut self) -> &mut T {
        self.inner.deref_mut()
    }
}

// /////////////////////////////////////////////////////////////
// MUTEXES

#[derive(Debug)]
pub struct HcMutex<T: ?Sized> {
    inner: Mutex<T>,
}

impl<T> HcMutex<T> {
    pub fn new(v: T) -> Self {
        Self {
            inner: Mutex::new(v),
        }
    }
}

#[derive(Debug)]
pub struct HcRwLock<T: ?Sized> {
    inner: RwLock<T>,
}

impl<T> HcRwLock<T> {
    pub fn new(v: T) -> Self {
        Self {
            inner: RwLock::new(v),
        }
    }
}

macro_rules! mutex_impl {
    ($HcMutex: ident, $Mutex: ident, $Guard:ident, $lock_type:ident, $lock_fn:ident, $try_lock_fn:ident, $try_lock_until_fn:ident, $try_lock_until_inner_fn:ident ) => {
        impl<T: ?Sized> $HcMutex<T> {
            pub fn $lock_fn(&self) -> HcLockResult<$Guard<T>> {
                let deadline = Instant::now() + Duration::from_secs(LOCK_TIMEOUT_SECS);
                self.$try_lock_until_fn(deadline)
            }

            fn $try_lock_until_fn(&self, deadline: Instant) -> HcLockResult<$Guard<T>> {
                // Set a number twice the expected number of iterations, just to prevent an infinite loop
                let max_iters = 2 * LOCK_TIMEOUT_SECS * 1000 / LOCK_POLL_INTERVAL_MS;
                let mut pending_puid = None;
                for _i in 0..max_iters {
                    match self.$try_lock_fn() {
                        Some(v) => {
                            if let Some(puid) = pending_puid {
                                PENDING_LOCKS.lock().remove(&puid);
                            }
                            return Ok(v);
                        }
                        None => {
                            pending_puid.get_or_insert_with(|| {
                                let p = ProcessUniqueId::new();
                                PENDING_LOCKS.lock().insert(
                                    p,
                                    (
                                        LockType::$lock_type,
                                        Instant::now(),
                                        Backtrace::new_unresolved(),
                                    ),
                                );
                                p
                            });

                            // TIMEOUT
                            if let None = deadline.checked_duration_since(Instant::now()) {
                                // PENDING_LOCKS.lock().remove(&puid);
                                return Err(HcLockError::new(
                                    LockType::$lock_type,
                                    HcLockErrorKind::HcLockTimeout,
                                ));
                            }
                        }
                    }
                    std::thread::sleep(Duration::from_millis(LOCK_POLL_INTERVAL_MS));
                }
                error!(
                    "$try_lock_until_inner_fn exceeded max_iters, this should not have happened!"
                );
                return Err(HcLockError::new(
                    LockType::$lock_type,
                    HcLockErrorKind::HcLockTimeout,
                ));
            }

            pub fn $try_lock_fn(&self) -> Option<$Guard<T>> {
                (*self).inner.$try_lock_fn().map(|g| $Guard::new(g))
            }
        }
    };
}

mutex_impl!(
    HcMutex,
    Mutex,
    HcMutexGuard,
    Lock,
    lock,
    try_lock,
    try_lock_until,
    try_lock_until_inner
);
mutex_impl!(
    HcRwLock,
    RwLock,
    HcRwLockReadGuard,
    Read,
    read,
    try_read,
    try_read_until,
    try_read_until_inner
);
mutex_impl!(
    HcRwLock,
    RwLock,
    HcRwLockWriteGuard,
    Write,
    write,
    try_write,
    try_write_until,
    try_write_until_inner
);