wsb 0.258.6441

Workspace tools for every project under $PRJ: git across submodules, template stamping, GitHub, and the workbench
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
//! What the machine is doing right now.
//!
//! Five numbers, sampled cheaply enough to ask for every couple of seconds:
//! processor, memory, graphics memory, graphics load, and free space on the
//! volume the workspace is on. They exist for one purpose — a strip in the
//! title bar that answers "is this machine all right" without being read, only
//! glanced at — so every one of them is a FRACTION between 0 and 1 plus one
//! number a person would say out loud.
//!
//! # Absent is a state
//!
//! Not every host can answer every question. A machine with no discrete GPU
//! has no VRAM; a Mac has no per-process GPU load without root. A missing
//! answer is reported as missing rather than as zero: a graph pinned at the
//! bottom says "idle", which is a claim, and the wrong one.
//!
//! # Cost
//!
//! Everything here is a file read or one short-lived process, and the process
//! (`nvidia-smi`) is only run where it exists. A sampler that cost anything
//! would be a strip that made the machine it describes slower.

use crate::prelude::*;
use std::path::Path;

/// One sample of the host.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Sample {
    /// Processor time in use since the previous sample, 0..1. None on the very
    /// first sample, which has nothing to compare against.
    pub cpu: Option<f32>,
    /// Memory in use, 0..1, and the bytes behind it.
    pub memory: Option<Fraction>,
    /// Graphics memory in use. None where there is no discrete GPU.
    pub vram: Option<Fraction>,
    /// Graphics load, 0..1.
    pub gpu: Option<f32>,
    /// The volume the workspace is on.
    pub disk: Option<Fraction>,
    /// What the GPU is, when there is one — for the tooltip, not the graph.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub gpu_name: Option<String>,
    /// Logical processors, for the tooltip.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cpu_count: Option<u32>,
}

/// A used/total pair, so a page can show either the bar or the number.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct Fraction {
    pub used: u64,
    pub total: u64,
}

impl Fraction {
    pub fn ratio(&self) -> f32 {
        if self.total == 0 {
            return 0.0;
        }
        (self.used as f64 / self.total as f64) as f32
    }

    pub fn free(&self) -> u64 {
        self.total.saturating_sub(self.used)
    }
}

/// Keeps what the processor needs: a delta against the previous reading.
#[derive(Debug, Default)]
pub struct Sampler {
    previous_cpu: Option<CpuTimes>,
    /// The last figure actually computed.
    ///
    /// Kept because the counters do not always move. macOS updates
    /// `HOST_CPU_LOAD_INFO` on its own schedule — measured at roughly twice a
    /// second — so two readings a quarter of a second apart are often
    /// byte-identical. A window in which the counters did not move carries no
    /// news, and the honest answer to "what is the processor doing" is the
    /// last thing it was doing, not a gap in the line.
    ///
    /// None only until the first real delta, which is the one case where
    /// there genuinely is no answer yet.
    last_cpu: Option<f32>,
}

#[derive(Debug, Clone, Copy)]
struct CpuTimes {
    busy: u64,
    total: u64,
}

impl Sampler {
    pub fn new() -> Self {
        Self::default()
    }

    /// Read everything this host can answer.
    ///
    /// `workspace_root` decides which volume the disk figure is about: the one
    /// the workspace is on, which is the one a build fills. The root volume of
    /// a machine with the workspace on an external disk is not the answer to
    /// any question somebody is asking here.
    pub fn sample(&mut self, workspace_root: &Path) -> Sample {
        let cpu_now = cpu_times();
        let cpu = match (self.previous_cpu, cpu_now) {
            (Some(before), Some(now)) => {
                let busy = now.busy.saturating_sub(before.busy) as f64;
                let total = now.total.saturating_sub(before.total) as f64;
                if total > 0.0 {
                    let fraction = (busy / total) as f32;
                    self.last_cpu = Some(fraction);
                    // The counters moved, so the baseline moves with them.
                    // Advanced only here: keeping a stale baseline would make
                    // the next reading a delta over both windows, which is the
                    // right answer for a window that produced no news.
                    self.previous_cpu = Some(now);
                    Some(fraction)
                } else {
                    // The kernel has not updated its accounting since the last
                    // reading. Nothing changed, so nothing is reported as
                    // changing — the previous figure stands.
                    self.last_cpu
                }
            }
            (None, Some(now)) => {
                self.previous_cpu = Some(now);
                None
            }
            _ => self.last_cpu,
        };

        let graphics = graphics();
        Sample {
            cpu,
            memory: memory(),
            vram: graphics.as_ref().and_then(|g| g.vram),
            gpu: graphics.as_ref().and_then(|g| g.load),
            gpu_name: graphics.and_then(|g| g.name),
            disk: disk(workspace_root),
            cpu_count: cpu_count(),
        }
    }
}

fn cpu_count() -> Option<u32> {
    std::thread::available_parallelism()
        .ok()
        .map(|n| n.get() as u32)
}

/// Busy and total jiffies since boot.
#[cfg(target_os = "linux")]
fn cpu_times() -> Option<CpuTimes> {
    let stat = std::fs::read_to_string("/proc/stat").ok()?;
    let line = stat.lines().find(|line| line.starts_with("cpu "))?;
    let fields: Vec<u64> = line
        .split_whitespace()
        .skip(1)
        .filter_map(|f| f.parse().ok())
        .collect();
    if fields.len() < 4 {
        return None;
    }
    let total: u64 = fields.iter().sum();
    // Idle is the fourth field, iowait the fifth: time the processor had
    // nothing to do, and time it spent waiting for a disk. Both are "not
    // working", and counting iowait as busy is what makes a machine reading a
    // large file look pinned.
    let idle = fields[3] + fields.get(4).copied().unwrap_or(0);
    Some(CpuTimes {
        busy: total.saturating_sub(idle),
        total,
    })
}

#[cfg(target_os = "macos")]
extern "C" {
    /// Give back a port right.
    ///
    /// Not in `libc`, so it is declared here. It has to be called: every
    /// `mach_host_self()` hands back a send right this task owns until it says
    /// otherwise, and a sampler that asks every two seconds and never gives
    /// one back accumulates 43,000 a day. The port table fills,
    /// `host_statistics` starts refusing, and the processor figure disappears
    /// — hours in, on a long-running daemon, having worked perfectly for
    /// whoever tested it.
    ///
    /// Nor is that hypothetical: five tests in a row was enough to exhaust it,
    /// which is how it was found.
    fn mach_port_deallocate(
        task: libc::mach_port_t,
        name: libc::mach_port_t,
    ) -> libc::kern_return_t;
}

/// The same counters on macOS, from the kernel rather than from a file.
///
/// `host_statistics(HOST_CPU_LOAD_INFO)` returns cumulative ticks per state
/// across all processors — user, system, idle, nice — which is exactly the
/// shape `/proc/stat` has, so the delta between two samples means the same
/// thing on both hosts.
///
/// Updated on the KERNEL's schedule, roughly twice a second, so two readings
/// closer together than that can be byte-identical. That is a window with no
/// news in it, not an idle processor — see [`Sampler::last_cpu`].
///
/// The alternatives were worse in ways that matter: `ps` totals average each
/// process over its whole lifetime rather than the last two seconds, and
/// `top -l 2` runs for a second every time it is asked, which is a second of
/// processor spent measuring the processor.
#[cfg(target_os = "macos")]
fn cpu_times() -> Option<CpuTimes> {
    // SAFETY: `host_statistics64` fills a fixed-size struct whose size is what
    // `count` says, and every pointer handed to it points at a live local. The
    // return is checked; nothing is read unless the kernel said it wrote it.
    // The host port is released on every path out.
    unsafe {
        let host = libc::mach_host_self();
        let mut info: libc::host_cpu_load_info = std::mem::zeroed();
        let mut count = libc::HOST_CPU_LOAD_INFO_COUNT;
        // `host_statistics`, NOT the `64` variant: the processor counters are
        // a 32-bit flavour, and the 64-bit call refuses the flavour rather
        // than filling anything — which reads as "this host has no processor
        // counters" and is how the Mac's strip came to show only memory and
        // disk. `HOST_VM_INFO64` is what the other call is for.
        let result = libc::host_statistics(
            host,
            libc::HOST_CPU_LOAD_INFO,
            &mut info as *mut _ as libc::host_info_t,
            &mut count,
        );
        // Released whatever the answer was. A failed call still handed us the
        // right, and leaking on the failure path is how a transient error
        // becomes a permanent one.
        let _ = mach_port_deallocate(libc::mach_task_self(), host);
        if result != libc::KERN_SUCCESS {
            return None;
        }
        let ticks = info.cpu_ticks;
        let total: u64 = ticks.iter().map(|t| *t as u64).sum();
        let idle = ticks[libc::CPU_STATE_IDLE as usize] as u64;
        Some(CpuTimes {
            busy: total.saturating_sub(idle),
            total,
        })
    }
}

/// Anywhere else, the processor is not reported rather than reported wrongly.
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
fn cpu_times() -> Option<CpuTimes> {
    None
}

#[cfg(target_os = "linux")]
fn memory() -> Option<Fraction> {
    let info = std::fs::read_to_string("/proc/meminfo").ok()?;
    let read = |key: &str| -> Option<u64> {
        info.lines()
            .find(|line| line.starts_with(key))?
            .split_whitespace()
            .nth(1)?
            .parse::<u64>()
            .ok()
            .map(|kb| kb * 1024)
    };
    let total = read("MemTotal:")?;
    // AVAILABLE, not free: free excludes the page cache, which the kernel
    // hands back the moment anything asks. A machine with 30 GB of cache is
    // not a machine with no memory left, and reporting it as one makes the
    // indicator useless on exactly the machines that are working hardest.
    let available = read("MemAvailable:").or_else(|| read("MemFree:"))?;
    Some(Fraction {
        used: total.saturating_sub(available),
        total,
    })
}

#[cfg(not(target_os = "linux"))]
fn memory() -> Option<Fraction> {
    let total: u64 = sysctl("hw.memsize")?;
    // `vm_stat` reports pages; free memory is what is free plus what is
    // reclaimable, which is the same distinction MemAvailable makes.
    let output = crate::git_backend::command_without_repo_scope("vm_stat")
        .output()
        .ok()?;
    let text = String::from_utf8_lossy(&output.stdout);
    let page_size: u64 = text
        .lines()
        .next()
        .and_then(|line| line.split("page size of ").nth(1))
        .and_then(|rest| rest.split_whitespace().next())
        .and_then(|n| n.parse().ok())
        .unwrap_or(4096);
    let pages = |key: &str| -> u64 {
        text.lines()
            .find(|line| line.starts_with(key))
            .and_then(|line| line.split(':').nth(1))
            .map(|v| v.trim().trim_end_matches('.'))
            .and_then(|v| v.parse::<u64>().ok())
            .unwrap_or(0)
    };
    let free = (pages("Pages free") + pages("Pages inactive") + pages("Pages purgeable")) * page_size;
    Some(Fraction {
        used: total.saturating_sub(free),
        total,
    })
}

#[cfg(not(target_os = "linux"))]
fn sysctl(name: &str) -> Option<u64> {
    let output = crate::git_backend::command_without_repo_scope("sysctl")
        .args(["-n", name])
        .output()
        .ok()?;
    String::from_utf8_lossy(&output.stdout).trim().parse().ok()
}

struct Graphics {
    name: Option<String>,
    load: Option<f32>,
    vram: Option<Fraction>,
}

/// The GPU, where one can be asked.
///
/// `nvidia-smi` where it exists, and nothing otherwise. An integrated GPU has
/// no separate memory to report and no counter to read without a vendor tool,
/// so the honest answer on those machines is that there is no answer.
fn graphics() -> Option<Graphics> {
    #[cfg(target_os = "macos")]
    if let Some(found) = apple_graphics() {
        return Some(found);
    }
    nvidia_graphics()
}

/// The Apple GPU, from the accelerator's own performance statistics.
///
/// `Device Utilization %` is what Activity Monitor shows, and it is readable
/// without privilege.
///
/// No VRAM figure, deliberately. Apple GPUs share system memory, so the
/// numbers beside it — `In use system memory` — are a slice of the RAM the
/// memory indicator already counts. Reporting them as a separate pool would
/// draw the same bytes twice and imply a capacity that does not exist.
#[cfg(target_os = "macos")]
fn apple_graphics() -> Option<Graphics> {
    let output = crate::git_backend::command_without_repo_scope("ioreg")
        .args(["-r", "-d", "1", "-w", "0", "-c", "IOAccelerator"])
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    let text = String::from_utf8_lossy(&output.stdout);
    // `"Device Utilization %"=37` inside the PerformanceStatistics dictionary.
    let after = text.split("\"Device Utilization %\"=").nth(1)?;
    let digits: String = after.chars().take_while(char::is_ascii_digit).collect();
    let percent: f32 = digits.parse().ok()?;
    Some(Graphics {
        name: text
            .split("\"model\" = <\"")
            .nth(1)
            .and_then(|rest| rest.split('"').next())
            .map(str::to_string),
        load: Some((percent / 100.0).clamp(0.0, 1.0)),
        vram: None,
    })
}

fn nvidia_graphics() -> Option<Graphics> {
    let output = crate::git_backend::command_without_repo_scope("nvidia-smi")
        .args([
            "--query-gpu=name,utilization.gpu,memory.used,memory.total",
            "--format=csv,noheader,nounits",
        ])
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    let text = String::from_utf8_lossy(&output.stdout);
    let line = text.lines().next()?;
    let fields: Vec<&str> = line.split(',').map(str::trim).collect();
    if fields.len() < 4 {
        return None;
    }
    // Megabytes, as nvidia-smi reports them with --nounits.
    let mib = |value: &str| value.parse::<u64>().ok().map(|mb| mb * 1024 * 1024);
    Some(Graphics {
        name: Some(fields[0].to_string()),
        load: fields[1].parse::<f32>().ok().map(|pct| pct / 100.0),
        vram: match (mib(fields[2]), mib(fields[3])) {
            (Some(used), Some(total)) => Some(Fraction { used, total }),
            _ => None,
        },
    })
}

/// Free space on the volume the workspace is on.
fn disk(workspace_root: &Path) -> Option<Fraction> {
    let space = crate::capped::volume_space(workspace_root).ok()?;
    Some(Fraction {
        // What is USED is what is not available to this user — not
        // total-minus-free, which counts the reserved blocks a non-root
        // process can never have as though they were on offer.
        used: space.total.saturating_sub(space.available),
        total: space.total,
    })
}

#[cfg(test)]
#[path = "host_tests.rs"]
mod tests;