tycho-util 0.3.7

Shared utilities for node components.
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
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::Duration;

use tycho_util::metrics::spawn_metrics_loop;
use tycho_util::sync::CancellationFlag;
use walkdir::WalkDir;

const BYTES_METRIC: &str = "tycho_fs_used_bytes";
const FILES_METRIC: &str = "tycho_fs_used_files";
const BLOCKS_METRIC: &str = "tycho_fs_used_blocks";
const TOTAL_LABEL: &str = "__total__";

#[derive(Debug, Clone)]
pub struct Stats {
    pub entries: Vec<StatsEntry>,
}

#[derive(Debug, Clone)]
pub struct StatsEntry {
    pub path: PathBuf,
    pub usage: Usage,
}

#[derive(Debug, Clone, Copy, Default)]
pub struct Usage {
    pub bytes: u64,
    pub files: u64,
    pub blocks: u64,
}

impl Stats {
    pub fn total(&self) -> Usage {
        total_counts(&self.entries)
    }
}

pub struct FsUsageBuilder {
    paths: Vec<PathBuf>,
}

impl FsUsageBuilder {
    pub fn new() -> Self {
        Self { paths: Vec::new() }
    }

    pub fn add_path<P: Into<PathBuf>>(mut self, path: P) -> Self {
        self.paths.push(path.into());
        self
    }

    pub fn build(self) -> FsUsageMonitor {
        let entries = self.paths.into_iter().map(Entry::new).collect::<Vec<_>>();

        FsUsageMonitor {
            state: Arc::new(FsUsageState {
                entries: Mutex::new(entries),
            }),
            stop: CancellationFlag::new(),
            export_handle: None,
        }
    }
}

impl Default for FsUsageBuilder {
    fn default() -> Self {
        Self::new()
    }
}

pub struct FsUsageMonitor {
    state: Arc<FsUsageState>,
    stop: CancellationFlag,
    export_handle: Option<tokio::task::AbortHandle>,
}

impl FsUsageMonitor {
    pub fn add_path<P: Into<PathBuf>>(&self, path: P) -> bool {
        let path = path.into();
        let mut entries = self.state.entries.lock().unwrap();

        if entries.iter().any(|e| e.path == path) {
            return false;
        }

        entries.push(Entry::new(path));
        true
    }

    pub fn iter_sizes(&self) -> impl Iterator<Item = StatsEntry> {
        self.snapshot().entries.into_iter()
    }

    pub fn walk(&self) -> Stats {
        walk_state(self.state.as_ref(), &self.stop)
    }

    pub fn snapshot(&self) -> Stats {
        let entries = self.state.entries.lock().unwrap();
        Stats {
            entries: entries
                .iter()
                .map(|e| StatsEntry {
                    path: e.path.clone(),
                    usage: e.usage,
                })
                .collect(),
        }
    }

    /// Starts the metrics loop that periodically collects and exports filesystem usage metrics.
    /// Can only be called once; subsequent calls will return an error.
    pub fn spawn_metrics_loop(&mut self, interval: Duration) -> Result<(), MetricsLoopStartError> {
        if self.stop.check() {
            return Err(MetricsLoopStartError::ShuttingDown);
        }

        if self.export_handle.is_some() {
            return Err(MetricsLoopStartError::AlreadyRunning);
        }

        let stop = self.stop.clone();

        let handle = spawn_metrics_loop(&self.state, interval, move |state| {
            let stop = stop.clone();
            async move {
                let stats = tokio::task::spawn_blocking(move || walk_state(state.as_ref(), &stop))
                    .await
                    .expect("spawn blocking failed");

                export_metrics(&stats);
            }
        });

        self.export_handle = Some(handle);

        Ok(())
    }

    fn shutdown(&mut self) {
        self.stop.cancel();

        if let Some(handle) = self.export_handle.take() {
            handle.abort();
        }
    }
}

impl Drop for FsUsageMonitor {
    fn drop(&mut self) {
        self.shutdown();
    }
}

#[derive(Debug)]
struct FsUsageState {
    entries: Mutex<Vec<Entry>>,
}

#[derive(Debug, Clone)]
struct Entry {
    path: PathBuf,
    usage: Usage,
}

impl Entry {
    fn new(path: PathBuf) -> Self {
        Self {
            path,
            usage: Usage::default(),
        }
    }
}

fn walk_state(state: &FsUsageState, stop: &CancellationFlag) -> Stats {
    let paths: Vec<_> = state.entries.lock().unwrap().clone();

    if paths.is_empty() {
        return Stats { entries: vec![] };
    }

    let mut results = Vec::with_capacity(paths.len());
    for e in paths {
        if stop.check() {
            break;
        }

        let usage = collect_path_usage(&e.path, stop);
        results.push((e.path, usage));
    }

    let mut entries = state.entries.lock().unwrap();

    let stats_out = entries
        .iter_mut()
        .zip(results)
        .map(|(entry, (path, usage))| {
            entry.usage = usage;
            StatsEntry { path, usage }
        })
        .collect();

    Stats { entries: stats_out }
}

fn collect_path_usage(path: &Path, stop: &CancellationFlag) -> Usage {
    let mut usage = Usage::default();

    let walker = WalkDir::new(path)
        .follow_links(false)
        .follow_root_links(true);

    for item in walker {
        if stop.check() {
            break;
        }

        let entry = match item {
            Ok(e) => e,
            Err(e) => {
                tracing::warn!("fs usage: walk e: {e:?}");
                continue;
            }
        };

        if entry.file_type().is_symlink() {
            continue;
        }

        let metadata = match entry.metadata() {
            Ok(m) => m,
            Err(e) => {
                tracing::warn!(
                    path = %entry.path().display(),
                    "fs usage: failed to read metadata: {e:?}",
                );
                continue;
            }
        };

        if metadata.is_dir() {
            usage.files = usage.files.saturating_add(1);
            usage.blocks = usage.blocks.saturating_add(blocks_from_metadata(&metadata));
        } else if metadata.is_file() {
            usage.files = usage.files.saturating_add(1);
            usage.bytes = usage.bytes.saturating_add(metadata.len());
            usage.blocks = usage.blocks.saturating_add(blocks_from_metadata(&metadata));
        }
    }

    usage
}

fn total_counts(entries: &[StatsEntry]) -> Usage {
    let mut sorted = entries.iter().collect::<Vec<_>>();
    sorted.sort_by(|a, b| a.path.cmp(&b.path));

    let mut total_bytes: u64 = 0;
    let mut total_files: u64 = 0;
    let mut total_blocks: u64 = 0;

    let mut last_parent: Option<&Path> = None;

    for entry in sorted {
        if let Some(parent) = last_parent
            && entry.path.starts_with(parent)
        {
            continue;
        }

        total_bytes = total_bytes.saturating_add(entry.usage.bytes);
        total_files = total_files.saturating_add(entry.usage.files);
        total_blocks = total_blocks.saturating_add(entry.usage.blocks);

        last_parent = Some(entry.path.as_path());
    }

    Usage {
        bytes: total_bytes,
        files: total_files,
        blocks: total_blocks,
    }
}

fn export_metrics(stats: &Stats) {
    for entry in &stats.entries {
        let path = entry.path.to_string_lossy().into_owned();

        for (metric, value) in [
            (BYTES_METRIC, entry.usage.bytes),
            (FILES_METRIC, entry.usage.files),
            (BLOCKS_METRIC, entry.usage.blocks),
        ] {
            metrics::gauge!(metric, "path" => path.clone()).set(value as f64);
        }
    }

    let Usage {
        bytes,
        files,
        blocks,
    } = stats.total();
    for (metric, value) in [
        (BYTES_METRIC, bytes),
        (FILES_METRIC, files),
        (BLOCKS_METRIC, blocks),
    ] {
        metrics::gauge!(metric, "path" => TOTAL_LABEL).set(value as f64);
    }
}

fn blocks_from_metadata(metadata: &fs::Metadata) -> u64 {
    #[cfg(unix)]
    {
        use std::os::unix::fs::MetadataExt;
        metadata.blocks()
    }
    #[cfg(not(unix))]
    {
        let len = metadata.len();
        if len == 0 {
            0
        } else {
            len.saturating_add(511) / 512
        }
    }
}

#[derive(thiserror::Error, Debug)]
pub enum MetricsLoopStartError {
    #[error("metrics loop is already running")]
    AlreadyRunning,
    #[error("fs monitor is shutting down")]
    ShuttingDown,
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;

    use tempfile::TempDir;

    use super::*;

    #[tokio::test]
    async fn walk_counts_files_and_dirs() {
        let temp_dir = TempDir::new().unwrap();
        let root = temp_dir.path();

        let file_a = root.join("a.txt");
        fs::write(&file_a, b"abcd").unwrap();

        let nested_dir = root.join("nested");
        fs::create_dir(&nested_dir).unwrap();
        fs::write(nested_dir.join("b.bin"), b"123456").unwrap();

        let monitor = FsUsageBuilder::new().add_path(root).build();

        let stats = monitor.walk();
        let entry = stats.entries.first().unwrap();

        assert_eq!(entry.usage.bytes, 10);
        assert_eq!(entry.usage.files, 4);
        assert!(entry.usage.blocks.saturating_mul(512) >= entry.usage.bytes);
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn walk_skips_symlinks_and_missing_paths() {
        let temp_dir = TempDir::new().unwrap();
        let root = temp_dir.path();
        let file_a = root.join("a");
        fs::write(&file_a, b"1").unwrap();

        let link = root.join("link");
        std::os::unix::fs::symlink(&file_a, &link).unwrap();

        let missing = root.join("missing");

        let monitor = FsUsageBuilder::new()
            .add_path(&link)
            .add_path(&missing)
            .add_path(&file_a)
            .build();

        let stats = monitor.walk();
        let totals = stats
            .entries
            .iter()
            .map(|entry| {
                (
                    entry
                        .path
                        .file_name()
                        .unwrap()
                        .to_string_lossy()
                        .into_owned(),
                    (entry.usage.bytes, entry.usage.files, entry.usage.blocks),
                )
            })
            .collect::<HashMap<_, _>>();

        assert_eq!(totals.get("link"), Some(&(0, 0, 0)));
        assert_eq!(totals.get("missing"), Some(&(0, 0, 0)));
        let &(bytes, files, blocks) = totals.get("a").unwrap();
        assert_eq!(bytes, 1);
        assert_eq!(files, 1);
        assert!(blocks >= 1);
    }

    #[test]
    fn total_counts_skips_children() {
        let entries = vec![
            StatsEntry {
                path: PathBuf::from("/var/log"),
                usage: Usage {
                    bytes: 3,
                    files: 1,
                    blocks: 2,
                },
            },
            StatsEntry {
                path: PathBuf::from("/var"),
                usage: Usage {
                    bytes: 10,
                    files: 4,
                    blocks: 7,
                },
            },
            StatsEntry {
                path: PathBuf::from("/opt"),
                usage: Usage {
                    bytes: 5,
                    files: 2,
                    blocks: 3,
                },
            },
        ];

        let Usage {
            bytes,
            files,
            blocks,
        } = total_counts(&entries);

        assert_eq!(bytes, 15);
        assert_eq!(files, 6);
        assert_eq!(blocks, 10);
    }
}