okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-0243-guifix into f-0243-rel9caf39495

main
4.8 KiB104 linesraw
1/** Host counters. CPU sockets are measured only when their logical CPU IDs are known. */
2import os from 'node:os';
3import { spawn } from 'node:child_process';
4import { createPowerShellLoop, endWithHost } from './windows-poll.mjs';
5import { readFile, readdir } from 'node:fs/promises';
6import { availableMemoryGb } from './hardware.mjs';
7import { probe } from './util.mjs';
8
9export function cpuUtilization(previous, current, ids) {
10  if (!previous || !ids.length) return null;
11  let total=0,idle=0;
12  for (const id of ids) {
13    const before=previous[id]?.times,after=current[id]?.times;
14    if(!before||!after)return null;
15    const elapsed=Object.values(after).reduce((n,v)=>n+v,0)-Object.values(before).reduce((n,v)=>n+v,0);
16    if(elapsed<0||after.idle<before.idle)return null;
17    total+=elapsed; idle+=after.idle-before.idle;
18  }
19  return total>0?Math.round(Math.max(0,Math.min(100,100*(1-idle/total)))):null;
20}
21
22export function diskRate(previous, current, time) {
23  const elapsed=previous?((current?.at??time)-(previous.counters?.at??previous.time))/1000:0;
24  if(elapsed<=0||!current||!previous?.counters)return {readMbs:null,writeMbs:null};
25  const read=current.read-previous.counters.read,write=current.write-previous.counters.write;
26  return {readMbs:read>=0?read/1024**2/elapsed:null,writeMbs:write>=0?write/1024**2/elapsed:null};
27}
28
29export function parseLinuxDiskCounters(raw, devices) {
30  let read=0,write=0,found=false;
31  for(const line of raw.trim().split('\n')) {
32    const fields=line.trim().split(/\s+/);
33    if(!devices.includes(fields[2])||fields.length<14)continue;
34    const reads=Number(fields[5]),writes=Number(fields[9]);
35    if(!Number.isFinite(reads)||!Number.isFinite(writes))continue;
36    read+=reads*512; write+=writes*512; found=true;
37  }
38  return found?{read,write}:null;
39}
40
41export function parseMacDiskCounters(raw) {
42  const reads=[...raw.matchAll(/"Bytes \(Read\)"\s*=\s*(\d+)/g)],writes=[...raw.matchAll(/"Bytes \(Write\)"\s*=\s*(\d+)/g)];
43  return reads.length&&writes.length?{read:reads.reduce((n,m)=>n+Number(m[1]),0),write:writes.reduce((n,m)=>n+Number(m[1]),0)}:null;
44}
45
46export function parseWindowsDiskLine(line) {
47  const m=/^\s*(\d+)\s+(\d+)\s*$/.exec(String(line));
48  return m?{read:Number(m[1]),write:Number(m[2])}:null;
49}
50
51/** The disk counters, read by one long-lived PowerShell (windows-poll.mjs; #3939). */
52export function createWindowsDiskReader({ spawnFn=spawn, intervalSec=4, maxStarts=3, now=Date.now }={}) {
53  let latest=null;
54  const script=`while($true){$d=Get-CimInstance Win32_PerfRawData_PerfDisk_PhysicalDisk -Filter "Name='_Total'";if($d){[Console]::Out.WriteLine(([string]$d.DiskReadBytesPersec)+' '+([string]$d.DiskWriteBytesPersec));[Console]::Out.Flush()};Start-Sleep -Seconds ${intervalSec}}`;
55  const loop=createPowerShellLoop({script,spawnFn,maxStarts,onLine:line=>{
56    const parsed=parseWindowsDiskLine(line);
57    if(parsed)latest={...parsed,at:now()};
58    return !!parsed;
59  }});
60  return {
61    read() { loop.start(); return latest&&now()-latest.at<5*intervalSec*1000?latest:null; },
62    stop() { loop.stop(); },
63    get starts() { return loop.starts; },
64  };
65}
66
67let windowsReader=null;
68function windowsDisks() {
69  windowsReader??=endWithHost(createWindowsDiskReader());
70  return windowsReader.read();
71}
72
73async function disks() {
74  try {
75    if(process.platform==='linux') {
76      const [raw,devices]=await Promise.all([readFile('/proc/diskstats','utf8'),readdir('/sys/block')]);
77      return parseLinuxDiskCounters(raw,devices.filter(d=>!/^(loop|ram|dm-|md|zram)/.test(d)));
78    }
79    if(process.platform==='darwin')return parseMacDiskCounters(await probe('ioreg',['-r','-c','IOBlockStorageDriver','-l'],1500));
80    if(process.platform==='win32') {
81      return windowsDisks();
82    }
83  } catch { /* An unsupported counter stays unavailable. */ }
84  return null;
85}
86
87export function createSystemSampler() {
88  let previousCpu=null,previousDisk=null,lastRate={readMbs:null,writeMbs:null};
89  return async processors => {
90    const current=os.cpus(),time=Date.now();
91    const cpuLoad=cpuUtilization(previousCpu,current,current.map((_,i)=>i));
92    const cpus=processors.map(p=>({id:p.id,utilizationPct:cpuUtilization(previousCpu,current,p.logicalIds??(processors.length===1?current.map((_,i)=>i):[]))}));
93    previousCpu=current;
94    const [available,counters]=await Promise.all([availableMemoryGb(process.platform),disks()]);
95    let rate=lastRate;
96    if(!(counters&&counters.at!==undefined&&previousDisk?.counters?.at===counters.at)) {
97      rate=diskRate(previousDisk,counters,time);
98      previousDisk={time,counters};
99      lastRate=rate;
100    }
101    const total=os.totalmem()/1024**3,free=available??os.freemem()/1024**3;
102    return {cpuLoad,cpus,ramUsedGb:Math.max(0,Math.min(total,total-free)),ramTotalGb:total,diskReadGbs:rate.readMbs===null?null:rate.readMbs/1024,diskWriteMbs:rate.writeMbs};
103  };
104}