proc-tree 0.2.0

Linux process tree: snapshot, incremental maintenance via fork/exec events, ancestry chain queries, PID reuse detection
Documentation
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
//! Default storage implementation using standard library types.
//!
//! [`DefaultStore`] is a `HashMap<Mutex>` store with optional TTL-based eviction.
//!
//! # Example
//!
//! ```rust
//! use proc_tree::{DefaultStore, snapshot};
//!
//! let store = DefaultStore::new(600);
//! snapshot(&store);
//! ```

use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use crate::traits::ProcessStore;
use crate::types::ProcessInfo;

// ---- Internal entry with optional TTL ----

struct Entry {
    value: ProcessInfo,
    inserted_at: Instant,
}

impl Clone for Entry {
    fn clone(&self) -> Self {
        Self {
            value: self.value.clone(),
            inserted_at: self.inserted_at,
        }
    }
}

// ---- Shared inner ----

type Inner = Arc<Mutex<HashMap<u32, Entry>>>;

fn get_inner(
    inner: &Inner,
    pid: u32,
    ttl: Duration,
    children_index: &Arc<Mutex<HashMap<u32, Vec<u32>>>>,
) -> Option<ProcessInfo> {
    let mut map = inner.lock().unwrap();
    let entry = map.get(&pid)?;
    if !ttl.is_zero() && entry.inserted_at.elapsed() >= ttl {
        let info = map.remove(&pid).unwrap().value;
        // Update children index
        let mut index = children_index.lock().unwrap();
        if let Some(children) = index.get_mut(&info.ppid) {
            children.retain(|&c| c != pid);
        }
        // Clean up this process's own children index entry
        index.remove(&pid);
        return None;
    }
    Some(entry.value.clone())
}

fn insert_inner(inner: &Inner, pid: u32, value: ProcessInfo) {
    let mut map = inner.lock().unwrap();
    map.insert(
        pid,
        Entry {
            value,
            inserted_at: Instant::now(),
        },
    );
}

// ---- DefaultStore ----

/// Process tree store backed by `HashMap<Mutex>` with optional TTL eviction.
///
/// Thread-safe via `Arc<Mutex<...>>`. Cloning shares the same data.
pub struct DefaultStore {
    inner: Inner,
    children_index: Arc<Mutex<HashMap<u32, Vec<u32>>>>,
    ttl: Duration,
}

impl DefaultStore {
    /// Create a new store with the given TTL in seconds.
    /// `ttl_secs = 0` means no expiration.
    pub fn new(ttl_secs: u64) -> Self {
        Self {
            inner: Arc::new(Mutex::new(HashMap::new())),
            children_index: Arc::new(Mutex::new(HashMap::new())),
            ttl: Duration::from_secs(ttl_secs),
        }
    }

    /// Number of entries (including possibly-expired ones not yet evicted).
    pub fn len(&self) -> usize {
        self.inner.lock().unwrap().len()
    }

    /// Returns `true` if the store contains no entries.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Check if a PID exists in the store.
    ///
    /// Does not trigger TTL eviction — use [`get_process`](ProcessStore::get_process)
    /// to check existence with TTL enforcement.
    pub fn contains_key(&self, pid: u32) -> bool {
        self.inner.lock().unwrap().contains_key(&pid)
    }
}

impl Clone for DefaultStore {
    fn clone(&self) -> Self {
        Self {
            inner: Arc::clone(&self.inner),
            children_index: Arc::clone(&self.children_index),
            ttl: self.ttl,
        }
    }
}

impl Default for DefaultStore {
    /// Creates a store with no TTL.
    fn default() -> Self {
        Self::new(0)
    }
}

impl ProcessStore for DefaultStore {
    fn get_process(&self, pid: u32) -> Option<ProcessInfo> {
        get_inner(&self.inner, pid, self.ttl, &self.children_index)
    }

    fn insert_process(&self, pid: u32, info: ProcessInfo) {
        let new_ppid = info.ppid;

        // Check if process already exists with different ppid
        let old_ppid = {
            let map = self.inner.lock().unwrap();
            map.get(&pid).map(|e| e.value.ppid)
        };

        // Insert the process
        insert_inner(&self.inner, pid, info);

        // Update children index
        let mut index = self.children_index.lock().unwrap();

        // Remove from old parent's index if ppid changed
        if let Some(old_ppid) = old_ppid
            && old_ppid != new_ppid
            && let Some(children) = index.get_mut(&old_ppid)
        {
            children.retain(|&c| c != pid);
        }

        // Add to new parent's index (avoid duplicates)
        let children = index.entry(new_ppid).or_default();
        if !children.contains(&pid) {
            children.push(pid);
        }
    }

    fn remove_process(&self, pid: u32) -> Option<ProcessInfo> {
        // Remove from inner
        let info = {
            let mut map = self.inner.lock().unwrap();
            map.remove(&pid).map(|e| e.value)
        };

        // Remove from children index
        if let Some(ref p) = info {
            let mut index = self.children_index.lock().unwrap();
            // Remove from parent's index
            if let Some(children) = index.get_mut(&p.ppid) {
                children.retain(|&c| c != pid);
            }
            // Clean up this process's own children index entry
            index.remove(&pid);
        }

        info
    }

    fn all_pids(&self) -> Vec<u32> {
        self.inner.lock().unwrap().keys().copied().collect()
    }

    fn children_of(&self, pid: u32) -> Vec<u32> {
        // O(1) lookup from index
        self.children_index
            .lock()
            .unwrap()
            .get(&pid)
            .cloned()
            .unwrap_or_default()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn default_store_insert_get() {
        let store = DefaultStore::new(0);
        store.insert_process(
            1,
            ProcessInfo {
                ppid: 0,
                cmd: "init".into(),
                user: "root".into(),
                tgid: 1,
                start_time_ns: 0,
            },
        );
        let info = store.get_process(1).unwrap();
        assert_eq!(info.ppid, 0);
        assert_eq!(info.cmd, "init");
    }

    #[test]
    fn default_store_ttl_expired() {
        let store = DefaultStore::new(0); // ttl=0 means no expiry
        store.insert_process(
            1,
            ProcessInfo {
                ppid: 0,
                cmd: "init".into(),
                user: "root".into(),
                tgid: 1,
                start_time_ns: 0,
            },
        );
        assert!(store.get_process(1).is_some());

        // With ttl=1, entry expires after 1 second
        let store = DefaultStore::new(1);
        store.insert_process(
            1,
            ProcessInfo {
                ppid: 0,
                cmd: "init".into(),
                user: "root".into(),
                tgid: 1,
                start_time_ns: 0,
            },
        );
        assert!(store.get_process(1).is_some());
        std::thread::sleep(Duration::from_millis(1100));
        assert!(store.get_process(1).is_none());
    }

    #[test]
    fn clone_shares_data() {
        let store = DefaultStore::new(0);
        store.insert_process(
            1,
            ProcessInfo {
                ppid: 0,
                cmd: "init".into(),
                user: "root".into(),
                tgid: 1,
                start_time_ns: 0,
            },
        );
        let store2 = store.clone();
        assert!(store2.get_process(1).is_some());
        store2.insert_process(
            2,
            ProcessInfo {
                ppid: 1,
                cmd: "bash".into(),
                user: "root".into(),
                tgid: 2,
                start_time_ns: 0,
            },
        );
        assert!(store.get_process(2).is_some());
    }

    #[test]
    fn len_and_contains() {
        let store = DefaultStore::new(0);
        assert_eq!(store.len(), 0);
        store.insert_process(
            1,
            ProcessInfo {
                ppid: 0,
                cmd: "a".into(),
                user: "u".into(),
                tgid: 1,
                start_time_ns: 0,
            },
        );
        assert_eq!(store.len(), 1);
        assert!(store.contains_key(1));
        assert!(!store.contains_key(999));
    }

    #[test]
    fn is_empty_default() {
        let store = DefaultStore::new(0);
        assert!(store.is_empty());
        store.insert_process(
            1,
            ProcessInfo {
                ppid: 0,
                cmd: "a".into(),
                user: "u".into(),
                tgid: 1,
                start_time_ns: 0,
            },
        );
        assert!(!store.is_empty());
    }

    #[test]
    fn all_pids_returns_keys() {
        let store = DefaultStore::new(0);
        store.insert_process(
            1,
            ProcessInfo {
                ppid: 0,
                cmd: "a".into(),
                user: "u".into(),
                tgid: 1,
                start_time_ns: 0,
            },
        );
        store.insert_process(
            2,
            ProcessInfo {
                ppid: 1,
                cmd: "b".into(),
                user: "u".into(),
                tgid: 2,
                start_time_ns: 0,
            },
        );
        store.insert_process(
            3,
            ProcessInfo {
                ppid: 1,
                cmd: "c".into(),
                user: "u".into(),
                tgid: 3,
                start_time_ns: 0,
            },
        );
        let mut pids = store.all_pids();
        pids.sort();
        assert_eq!(pids, vec![1, 2, 3]);
    }

    #[test]
    fn ttl_contains_key_does_not_expire() {
        let store = DefaultStore::new(1);
        store.insert_process(
            1,
            ProcessInfo {
                ppid: 0,
                cmd: "a".into(),
                user: "u".into(),
                tgid: 1,
                start_time_ns: 0,
            },
        );
        assert!(store.contains_key(1));
        std::thread::sleep(Duration::from_millis(1100));
        // contains_key does not trigger TTL eviction
        assert!(store.contains_key(1));
        // but get_process does
        assert!(store.get_process(1).is_none());
    }

    #[test]
    fn remove_process() {
        let store = DefaultStore::new(0);
        store.insert_process(
            1,
            ProcessInfo {
                ppid: 0,
                cmd: "init".into(),
                user: "root".into(),
                tgid: 1,
                start_time_ns: 0,
            },
        );
        store.insert_process(
            2,
            ProcessInfo {
                ppid: 1,
                cmd: "bash".into(),
                user: "root".into(),
                tgid: 2,
                start_time_ns: 0,
            },
        );

        assert_eq!(store.len(), 2);
        assert!(store.contains_key(2));

        let removed = store.remove_process(2);
        assert!(removed.is_some());
        assert_eq!(store.len(), 1);
        assert!(!store.contains_key(2));
    }

    #[test]
    fn children_of() {
        let store = DefaultStore::new(0);
        store.insert_process(
            1,
            ProcessInfo {
                ppid: 0,
                cmd: "init".into(),
                user: "root".into(),
                tgid: 1,
                start_time_ns: 0,
            },
        );
        store.insert_process(
            100,
            ProcessInfo {
                ppid: 1,
                cmd: "a".into(),
                user: "root".into(),
                tgid: 100,
                start_time_ns: 0,
            },
        );
        store.insert_process(
            200,
            ProcessInfo {
                ppid: 1,
                cmd: "b".into(),
                user: "root".into(),
                tgid: 200,
                start_time_ns: 0,
            },
        );
        store.insert_process(
            300,
            ProcessInfo {
                ppid: 100,
                cmd: "c".into(),
                user: "root".into(),
                tgid: 300,
                start_time_ns: 0,
            },
        );

        let mut kids = store.children_of(1);
        kids.sort();
        assert_eq!(kids, vec![100, 200]);

        let kids_100 = store.children_of(100);
        assert_eq!(kids_100, vec![300]);

        assert!(store.children_of(999).is_empty());
    }

    #[test]
    fn insert_ppid_change_removes_from_old_parent() {
        let store = DefaultStore::new(0);
        store.insert_process(
            1,
            ProcessInfo {
                ppid: 0,
                cmd: "init".into(),
                user: "root".into(),
                tgid: 1,
                start_time_ns: 0,
            },
        );
        store.insert_process(
            100,
            ProcessInfo {
                ppid: 0,
                cmd: "other".into(),
                user: "root".into(),
                tgid: 100,
                start_time_ns: 0,
            },
        );
        store.insert_process(
            200,
            ProcessInfo {
                ppid: 100,
                cmd: "child".into(),
                user: "root".into(),
                tgid: 200,
                start_time_ns: 0,
            },
        );

        // child 200 is under parent 100
        assert_eq!(store.children_of(100), vec![200]);
        assert!(store.children_of(1).is_empty());

        // Re-parent 200 from 100 to 1
        store.insert_process(
            200,
            ProcessInfo {
                ppid: 1,
                cmd: "child".into(),
                user: "root".into(),
                tgid: 200,
                start_time_ns: 0,
            },
        );

        // 200 should be removed from old parent's index
        assert!(
            store.children_of(100).is_empty(),
            "old parent should have no children"
        );
        // 200 should be in new parent's index
        assert_eq!(store.children_of(1), vec![200]);
    }

    #[test]
    fn insert_same_ppid_no_duplicate() {
        let store = DefaultStore::new(0);
        store.insert_process(
            1,
            ProcessInfo {
                ppid: 0,
                cmd: "init".into(),
                user: "root".into(),
                tgid: 1,
                start_time_ns: 0,
            },
        );
        store.insert_process(
            100,
            ProcessInfo {
                ppid: 1,
                cmd: "a".into(),
                user: "root".into(),
                tgid: 100,
                start_time_ns: 0,
            },
        );
        // Insert same pid with same ppid again
        store.insert_process(
            100,
            ProcessInfo {
                ppid: 1,
                cmd: "a".into(),
                user: "root".into(),
                tgid: 100,
                start_time_ns: 0,
            },
        );
        // Should not duplicate
        assert_eq!(store.children_of(1), vec![100]);
    }

    #[test]
    fn remove_process_cleans_own_children_index() {
        let store = DefaultStore::new(0);
        store.insert_process(
            1,
            ProcessInfo {
                ppid: 0,
                cmd: "init".into(),
                user: "root".into(),
                tgid: 1,
                start_time_ns: 0,
            },
        );
        store.insert_process(
            100,
            ProcessInfo {
                ppid: 1,
                cmd: "parent".into(),
                user: "root".into(),
                tgid: 100,
                start_time_ns: 0,
            },
        );
        store.insert_process(
            200,
            ProcessInfo {
                ppid: 100,
                cmd: "child".into(),
                user: "root".into(),
                tgid: 200,
                start_time_ns: 0,
            },
        );

        assert_eq!(store.children_of(100), vec![200]);

        // Remove parent 100
        store.remove_process(100);

        // children_of(100) should return empty, not stale [200]
        assert!(
            store.children_of(100).is_empty(),
            "removed process should have no children index"
        );
        // Child 200 still exists in store but parent is gone
        assert!(store.get_process(200).is_some());
    }

    #[test]
    fn ttl_expiration_cleans_own_children_index() {
        let store = DefaultStore::new(1); // 1 second TTL
        store.insert_process(
            1,
            ProcessInfo {
                ppid: 0,
                cmd: "init".into(),
                user: "root".into(),
                tgid: 1,
                start_time_ns: 0,
            },
        );
        store.insert_process(
            100,
            ProcessInfo {
                ppid: 1,
                cmd: "parent".into(),
                user: "root".into(),
                tgid: 100,
                start_time_ns: 0,
            },
        );
        store.insert_process(
            200,
            ProcessInfo {
                ppid: 100,
                cmd: "child".into(),
                user: "root".into(),
                tgid: 200,
                start_time_ns: 0,
            },
        );

        assert_eq!(store.children_of(100), vec![200]);

        // Wait for parent to expire
        std::thread::sleep(Duration::from_millis(1100));

        // Accessing expired parent triggers eviction
        assert!(store.get_process(100).is_none());

        // children_of(100) should return empty, not stale [200]
        assert!(
            store.children_of(100).is_empty(),
            "expired process should have no children index"
        );
    }
}