okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
9caf39495
main
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 ) { 10if ( ! previous || ! ids . length ) return null ; 11let total = 0 , idle = 0 ; 12for ( const id of ids ) { 13const before = previous [ id ]?. times , after = current [ id ]?. times ; 14if ( ! before ||! after ) return null ; 15const elapsed = Object . values ( after ). reduce (( n , v ) => n + v , 0 ) - Object . values ( before ). reduce (( n , v ) => n + v , 0 ); 16if ( elapsed < 0 || after . idle < before . idle ) return null ; 17total += elapsed ; idle += after . idle - before . idle ; 18} 19return total > 0 ?Math . round ( Math . max ( 0 , Math . min ( 100 , 100 * ( 1 - idle / total )))) :null ; 20} 21 22export function diskRate ( previous , current , time ) { 23const elapsed = previous ?(( current ?. at ?? time ) - ( previous . counters ?. at ?? previous . time )) / 1000 :0 ; 24if ( elapsed <= 0 ||! current ||! previous ?. counters ) return { readMbs :null , writeMbs :null }; 25const read = current . read - previous . counters . read , write = current . write - previous . counters . write ; 26return { readMbs :read >= 0 ?read / 1024 ** 2 / elapsed :null , writeMbs :write >= 0 ?write / 1024 ** 2 / elapsed :null }; 27} 28 29export function parseLinuxDiskCounters ( raw , devices ) { 30let read = 0 , write = 0 , found = false ; 31for ( const line of raw . trim (). split ( '\n' )) { 32const fields = line . trim (). split ( / \s +/ ); 33if ( ! devices . includes ( fields [ 2 ]) || fields . length < 14 ) continue ; 34const reads = Number ( fields [ 5 ]), writes = Number ( fields [ 9 ]); 35if ( ! Number . isFinite ( reads ) ||! Number . isFinite ( writes )) continue ; 36read += reads * 512 ; write += writes * 512 ; found = true ; 37} 38return found ?{ read, write} :null ; 39} 40 41export function parseMacDiskCounters ( raw ) { 42const reads = [ ...raw . matchAll ( / "Bytes \(Read\)"\s * =\s * ( \d + ) / g )], writes = [ ...raw . matchAll ( / "Bytes \(Write\)"\s * =\s * ( \d + ) / g )]; 43return 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 ) { 47const m = /^\s * ( \d + ) \s + ( \d + ) \s * $ / . exec ( String ( line )); 48return 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 } = {}) { 53let latest = null ; 54const 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 } }` ; 55const loop = createPowerShellLoop ({ script, spawnFn, maxStarts, onLine :line => { 56const parsed = parseWindowsDiskLine ( line ); 57if ( parsed ) latest = { ...parsed , at :now ()}; 58return !! parsed ; 59}}); 60return { 61read () { loop . start (); return latest && now () - latest . at < 5 * intervalSec * 1000 ?latest :null ; }, 62stop () { loop . stop (); }, 63get starts () { return loop . starts ; }, 64}; 65} 66 67let windowsReader = null ; 68function windowsDisks () { 69windowsReader ??= endWithHost ( createWindowsDiskReader ()); 70return windowsReader . read (); 71} 72 73async function disks () { 74try { 75if ( process . platform === 'linux' ) { 76const [ raw , devices ] = await Promise . all ([ readFile ( '/proc/diskstats' , 'utf8' ), readdir ( '/sys/block' )]); 77return parseLinuxDiskCounters ( raw , devices . filter ( d =>! /^ ( loop | ram | dm- | md | zram ) / . test ( d ))); 78} 79if ( process . platform === 'darwin' ) return parseMacDiskCounters ( await probe ( 'ioreg' ,[ '-r' , '-c' , 'IOBlockStorageDriver' , '-l' ], 1500 )); 80if ( process . platform === 'win32' ) { 81return windowsDisks (); 82} 83} catch { /* An unsupported counter stays unavailable. */ } 84return null ; 85} 86 87export function createSystemSampler () { 88let previousCpu = null , previousDisk = null , lastRate = { readMbs :null , writeMbs :null }; 89return async processors => { 90const current = os . cpus (), time = Date . now (); 91const cpuLoad = cpuUtilization ( previousCpu , current , current . map (( _ , i ) => i )); 92const cpus = processors . map ( p => ({ id :p . id , utilizationPct :cpuUtilization ( previousCpu , current , p . logicalIds ?? ( processors . length === 1 ?current . map (( _ , i ) => i ) :[]))})); 93previousCpu = current ; 94const [ available , counters ] = await Promise . all ([ availableMemoryGb ( process . platform ), disks ()]); 95let rate = lastRate ; 96if ( ! ( counters && counters . at !== undefined && previousDisk ?. counters ?. at === counters . at )) { 97rate = diskRate ( previousDisk , counters , time ); 98previousDisk = { time, counters}; 99lastRate = rate ; 100} 101const total = os . totalmem () / 1024 ** 3 , free = available ?? os . freemem () / 1024 ** 3 ; 102return { 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}