forge
Explore
Log in

Don't you dare go Hollow

yumush

Clone
★ 0

0 watching0 forksRustAGPL-3.06.8 MiB27ceb05Tahinli8 hours ago399 commits

lib.rs232 lines, 6.4 KiBHistoryRawDownload
1use std::{
2 path::{Path, PathBuf},
3 sync::{Arc, Mutex},
4 thread,
5 time::{Duration, Instant},
6};
7
8use sysinfo::{
9 CpuRefreshKind, MemoryRefreshKind, Pid, ProcessRefreshKind, ProcessesToUpdate, RefreshKind,
10 System,
11};
12
13#[cfg(target_os = "linux")]
14mod drm;
15#[cfg(target_os = "macos")]
16mod mac;
17#[cfg(any(target_os = "linux", target_os = "windows"))]
18mod nvidia;
19mod threads;
20#[cfg(target_os = "windows")]
21mod windows;
22
23const INTERVAL: Duration = Duration::from_secs(1);
24const IDLE_AFTER: Duration = Duration::from_secs(3);
25
26pub use common::stats::{Gpu, GpuMachine, Memory, Storage, Threads, Usage};
27pub use threads::{Group, tick};
28
29struct Shared {
30 latest: Option<Usage>,
31 requested: Instant,
32 awake: bool,
33 disk: Option<PathBuf>,
34}
35
36pub struct Monitor {
37 shared: Arc<Mutex<Shared>>,
38}
39
40impl Default for Monitor {
41 fn default() -> Self {
42 let shared = Arc::new(Mutex::new(Shared {
43 latest: None,
44 requested: Instant::now(),
45 awake: false,
46 disk: None,
47 }));
48 let worker = Arc::downgrade(&shared);
49 let _ = thread::Builder::new()
50 .name("usage".to_string())
51 .spawn(move || run(worker));
52 Self { shared }
53 }
54}
55
56impl Monitor {
57 pub fn watch_disk(&self, path: PathBuf) {
58 if let Ok(mut shared) = self.shared.lock() {
59 shared.disk = Some(path);
60 }
61 }
62
63 pub fn stay_awake(&self) {
64 if let Ok(mut shared) = self.shared.lock() {
65 shared.awake = true;
66 }
67 }
68
69 pub fn latest(&self) -> Option<Usage> {
70 let mut shared = self.shared.lock().ok()?;
71 shared.requested = Instant::now();
72 shared.latest.clone()
73 }
74}
75
76fn run(shared: std::sync::Weak<Mutex<Shared>>) {
77 let mut sampler: Option<Sampler> = None;
78 loop {
79 thread::sleep(INTERVAL);
80 let Some(shared) = shared.upgrade() else {
81 return;
82 };
83 let Some((wanted, disk)) = shared.lock().ok().map(|shared| {
84 (
85 shared.awake || shared.requested.elapsed() < IDLE_AFTER,
86 shared.disk.clone(),
87 )
88 }) else {
89 return;
90 };
91 let usage = if wanted {
92 if sampler.is_none() {
93 sampler = Sampler::new();
94 }
95 sampler
96 .as_mut()
97 .and_then(|sampler| sampler.sample(disk.as_deref()))
98 } else {
99 sampler = None;
100 None
101 };
102 if let Ok(mut shared) = shared.lock() {
103 shared.latest = usage;
104 }
105 }
106}
107
108struct Sampler {
109 system: System,
110 pid: Pid,
111 cores: f32,
112 host: String,
113 os: String,
114 cpu_model: Arc<str>,
115 primed: bool,
116 gpu: GpuSampler,
117 threads: threads::Sampler,
118}
119
120impl Sampler {
121 fn new() -> Option<Self> {
122 let system = System::new_with_specifics(
123 RefreshKind::nothing().with_cpu(CpuRefreshKind::nothing().with_usage()),
124 )
125 .ok()?;
126 let cpu_model = system
127 .cpus()
128 .first()
129 .map(|cpu| cpu.brand().trim().to_string())
130 .unwrap_or_default()
131 .into();
132 Some(Self {
133 host: System::host_name().unwrap_or_default(),
134 os: os(),
135 cores: system.cpus().len().max(1) as f32,
136 system,
137 pid: Pid::from_u32(std::process::id()),
138 cpu_model,
139 primed: false,
140 gpu: GpuSampler::default(),
141 threads: threads::Sampler::default(),
142 })
143 }
144
145 fn sample(&mut self, disk: Option<&Path>) -> Option<Usage> {
146 self.system.refresh_cpu_usage();
147 self.system
148 .refresh_memory_specifics(MemoryRefreshKind::nothing().with_ram());
149 self.system.refresh_processes_specifics(
150 ProcessesToUpdate::Some(&[self.pid]),
151 true,
152 ProcessRefreshKind::nothing().with_cpu().with_memory(),
153 );
154 if !std::mem::replace(&mut self.primed, true) {
155 return None;
156 }
157 let process = self.system.process(self.pid)?;
158 let mb = |bytes: u64| (bytes / (1024 * 1024)) as u32;
159 let total = self.system.total_memory();
160 let threads = self.threads.sample(self.cores);
161 Some(Usage {
162 host: self.host.clone(),
163 os: self.os.clone(),
164 cpu_model: self.cpu_model.to_string(),
165 machine: self.system.global_cpu_usage(),
166 total: process.cpu_usage() / self.cores,
167 threads,
168 memory: Memory {
169 own_mb: mb(process.memory()),
170 used_mb: mb(total.saturating_sub(self.system.available_memory())),
171 total_mb: mb(total),
172 },
173 storage: disk.and_then(storage),
174 gpu: self.gpu.sample(),
175 })
176 }
177}
178
179#[derive(Default)]
180struct GpuSampler {
181 #[cfg(any(target_os = "linux", target_os = "windows"))]
182 nvidia: nvidia::Sampler,
183 #[cfg(target_os = "linux")]
184 native: drm::Sampler,
185 #[cfg(target_os = "windows")]
186 native: windows::Sampler,
187 #[cfg(target_os = "macos")]
188 native: mac::Sampler,
189}
190
191impl GpuSampler {
192 #[cfg(any(target_os = "linux", target_os = "windows"))]
193 fn sample(&mut self) -> Option<Gpu> {
194 self.nvidia.sample().or_else(|| self.native.sample())
195 }
196
197 #[cfg(target_os = "macos")]
198 fn sample(&mut self) -> Option<Gpu> {
199 self.native.sample()
200 }
201
202 #[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
203 fn sample(&mut self) -> Option<Gpu> {
204 None
205 }
206}
207
208fn os() -> String {
209 #[cfg(target_os = "windows")]
210 let kernel = windows::build();
211 #[cfg(not(target_os = "windows"))]
212 let kernel = System::kernel_version().ok();
213 let name = System::long_os_version().unwrap_or_default();
214 match kernel {
215 Some(kernel) => format!("{name} {kernel}"),
216 None => name,
217 }
218}
219
220fn storage(path: &Path) -> Option<Storage> {
221 let path = path.ancestors().find_map(|path| path.canonicalize().ok())?;
222 let disks = sysinfo::Disks::new_with_refreshed_list().ok()?;
223 let disk = disks
224 .iter()
225 .filter(|disk| path.starts_with(disk.mount_point()))
226 .max_by_key(|disk| disk.mount_point().as_os_str().len())?;
227 let mb = |bytes: u64| (bytes / (1024 * 1024)) as u32;
228 Some(Storage {
229 used_mb: mb(disk.total_space().saturating_sub(disk.available_space())),
230 total_mb: mb(disk.total_space()),
231 })
232}