// Everything that depends on the operating system (Windows edition): where the config lives, how to start a shell, // the collector script with its frame parser, the control commands and the texts the page shows for them. // The Linux edition replaces this file and the collector script; every other file is identical. const fs = require('fs'), os = require('os'), path = require('path'), { spawn } = require('child_process'); const { num, blank, sections, kv, rater, addDisk, addMount, finish } = require('./metrics'); const collector = fs.readFileSync(path.join(__dirname, 'collector.ps1'), 'utf8'); // PowerShell 5.1+, reads CIM / .NET counters const quote = s => "'" + s.replace(/['\u2018-\u201b]/g, '$&$&') + "'"; // PowerShell also takes typographic quotes as string ends // PowerShell runs whatever script arrives on stdin: the encoded command is iex (@($input) -join [char]10) const SHELL = ['powershell', '-NoLogo', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-OutputFormat', 'Text', '-EncodedCommand', 'aQBlAHgAIAAoAEAAKAAkAGkAbgBwAHUAdAApACAALQBqAG8AaQBuACAAWwBjAGgAYQByAF0AMQAwACkA']; const failed = "Get-CimInstance Win32_Service | Where-Object { $_.StartMode -eq 'Auto' -and $_.State -eq 'Stopped' -and $_.ExitCode -notin 0, 1077 }"; const restartFailed = failed + ' | ForEach-Object { "restart $($_.Name)"; Start-Service -Name $_.Name }'; const cleanup = 'Get-ChildItem $env:TEMP, "$env:windir\\Temp" -Recurse -File -ErrorAction Ignore | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-7) } | ' + 'Remove-Item -Force -ErrorAction Ignore; Clear-RecycleBin -Force -ErrorAction Ignore'; const events = (filter, max, columns) => `Get-WinEvent -FilterHashtable @{ LogName = ${filter} } -MaxEvents ${max} | Format-Table TimeCreated, ${columns}, Message -Wrap`; // rows: label, command ({n} = pid, {q} = quoted name), danger, confirm, has a button const cmds = rows => rows.map(([label, cmd, danger = false, confirm = true, button = true]) => ({ label, cmd, danger, confirm, button })); // ---- collector frame parser: |-separated rows in, Metrics out; `st` keeps counters between frames ---- const VIRT = /virtual ethernet|virtualbox|vmware virtual|vethernet|loopback|pseudo|tap-|bluetooth|wan miniport|wsl|docker/i; // a VM's own NIC counts as physical const TCP = { Established: 'ESTABLISHED', Listen: 'LISTEN', TimeWait: 'TIME_WAIT', CloseWait: 'CLOSE_WAIT' }; const PROTECTED = new Set(['System', 'Registry', 'Memory Compression', 'smss.exe', 'csrss.exe', 'wininit.exe', 'winlogon.exe', 'services.exe', 'lsass.exe', 'svchost.exe', 'sshd.exe', 'dwm.exe']); const rows = lines => (lines || []).map(l => l.split('|')); function parse(frame, st, now) { const sec = sections(frame), m = blank(now), info = kv(sec.info, st.info ??= {}), sys = kv(sec.os, kv(sec.sys, kv(sec.mem))), v = k => num(sys[k]); if (sec.users) st.users = Object.fromEntries(rows(sec.users)); // only sent when the collector runs elevated m.hostname = info.hostname || '', m.os = info.os || '', m.kernel = info.kernel || '', m.arch = info.arch || ''; m.cpuModel = info.cpumodel || '', m.virt = info.virt || '', m.uptime = v('uptime'); if (m.uptime <= 0) return m; const ts = v('ts'), dt = st.ts ? Math.max(0, ts - st.ts) / 1000 : 0, rates = dt > 0.05, delta = rater(st, dt); // CPU: "_Total" is the machine, the other rows are cores; the load average is derived like the Unix one const cpu = rows(sec.cpu), [, total, user, privileged, irq, interrupts] = cpu.find(r => r[0] === '_Total') || []; m.cores = cpu.filter(r => r[0] !== '_Total').sort((a, b) => num(a[0]) - num(b[0])).map(r => ({ usage: num(r[1]), mhz: num(info.mhz) })); m.cpuCount = Math.max(1, m.cores.length), m.avgMhz = num(info.mhz); m.cpuUsage = num(total), m.cpuUser = num(user), m.cpuIrq = num(irq), m.cpuSystem = Math.max(0, num(privileged) - m.cpuIrq), m.intrPerSec = num(interrupts); const busy = m.cpuUsage / 100 * m.cpuCount, instant = busy + v('queue'); st.load = st.load ? st.load.map((l, i) => l + (instant - l) * (1 - Math.exp(-dt / [60, 300, 900][i]))) : [instant, instant, instant]; [m.load1, m.load5, m.load15] = st.load; m.procsRunning = Math.round(busy), m.procsBlocked = v('queue'), m.ctxtPerSec = v('ctxt'); // memory m.memTotal = v('memtotal'), m.memAvailable = v('avail'), m.memFree = v('free'), m.cached = v('standby') + v('syscache'), m.slab = v('pool'), m.dirty = v('modified'); m.swapTotal = v('swaptotal'), m.swapUsed = Math.max(0, m.swapTotal - v('swapfree')); // network: cumulative counters -> rates for (const [name, status = '', speed, type, rx, tx, rxPkts, txPkts, errors, drops, description] of rows(sec.net)) { const [rxBps, txBps, rxPps, txPps] = delta('net:' + name, [rx, tx, rxPkts, txPkts].map(num)); m.nets.push({ name, virt: type === 'Loopback' || type === 'Tunnel' || VIRT.test(name + ' ' + description), state: status.toLowerCase(), speed: num(speed), rxBps, txBps, rxPps, txPps, rxBytes: num(rx), txBytes: num(tx), errors: num(errors), drops: num(drops) }); } for (const [state, count] of (sec.tcp || []).map(l => l.trim().split(/\s+/))) { const name = TCP[state] || state.toUpperCase(); m.tcp[name] = (m.tcp[name] || 0) + num(count), m.socketsUsed += num(count); } // disks and volumes for (const [name, readBps, writeBps, readIops, writeIops, idle] of rows(sec.disk)) addDisk(m, { name, readBps: num(readBps), writeBps: num(writeBps), readIops: num(readIops), writeIops: num(writeIops), util: idle ? Math.min(100, Math.max(0, 100 - num(idle))) : 0, totalRead: 0, totalWritten: 0 }, true); for (const [mount, label, type, size, free] of rows(sec.df)) if (num(size) > 0) addMount(m, { device: label, type, mount, total: num(size), used: num(size) - num(free), avail: num(free) }); // processes: "pid|ppid|cpuTime100ns|priority|threads|createdUnixSec|vsz|rss|name" const times = {}; let started = 0; for (const [pid, ppid, cpuTime, priority, threads, created, vsz, rss, name = ''] of rows(sec.procs)) { if (!num(pid)) continue; const known = st.times && pid in st.times; times[pid] = num(cpuTime), started += !known; const cpu = rates && known ? Math.min(100 * m.cpuCount, Math.max(0, (times[pid] - st.times[pid]) / 1e7 / dt * 100)) : 0; // % of one core m.procs.push({ pid: num(pid), ppid: num(ppid), threads: num(threads), nice: num(priority), name, state: cpu > 0.5 ? 'R' : 'S', user: st.users?.[pid] || '—', cpu, rss: num(rss), vsz: num(vsz), age: num(created) ? Math.max(0, ts / 1000 - num(created)) : 0 }); } m.forksPerSec = rates && st.times ? started / dt : 0; // services arrive every few samples: keep the last list if (sec.services) st.services = rows(sec.services).map(([unit, state = '', mode, exitCode, description = '']) => ({ unit, load: mode, sub: state.toLowerCase(), description, active: mode === 'Auto' && state === 'Stopped' && ![0, 1077].includes(num(exitCode)) ? 'failed' : state === 'Running' ? 'active' : 'inactive' })); m.loggedUsers = num(sec.sessions?.[0]); finish(m, st, sec, 1); st.times = times, st.ts = ts; m.valid = rates; // the first sample has no rates yet return m; } module.exports = { quote, parse, cleanup, configDir: () => path.join(process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming'), 'ServerMonitorWeb'), shell: () => SHELL, // argv of a shell that runs a script from stdin collector: interval => `$iv = ${interval}; $once = $false\n` + collector, // stdin for the collector wrap: cmd => "[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false; $ProgressPreference = 'SilentlyContinue'; $Error.Clear(); $global:LASTEXITCODE = 0\n" + `& {\n${cmd}\n} 2>&1 | Out-String -Width 250 -Stream\nif ($LASTEXITCODE) { exit $LASTEXITCODE }\n` + // no sudo: run the monitor elevated "if ($Error | Where-Object { $_.FullyQualifiedErrorId -notlike 'NativeCommandError*' }) { exit 1 }; exit 0\n", // stderr text of a program is not a failure askpass: ['askpass.cmd', '@echo off\r\nsetlocal EnableDelayedExpansion\r\necho(!SERVERMONITOR_ASKPASS!\r\n'], // answers ssh's password prompt command: (action, arg) => ({ kill_pid: `Stop-Process -Id ${parseInt(arg) || 0} -Force`, renice: `(Get-Process -Id ${parseInt(arg) || 0}).PriorityClass = 'Idle'`, restart_service: `Restart-Service -Name ${quote(arg)} -Force`, restart_failed: restartFailed, })[action], serviceLogs: (unit, lines) => `$s = Get-CimInstance Win32_Service | Where-Object Name -eq ${quote(unit)}; $s | Format-List Name, DisplayName, State, StartMode, ExitCode, ProcessId, PathName; ` + "Get-WinEvent -FilterHashtable @{ LogName = 'System'; ProviderName = 'Service Control Manager' } -MaxEvents 3000 -ErrorAction Ignore | " + `Where-Object { $_.Message -like ('*' + $s.DisplayName + '*') } | Select-Object -First ${lines} | Format-Table TimeCreated, LevelDisplayName, Message -Wrap`, power: reboot => `shutdown /${reboot ? 'r' : 's'} /t 5`, detached: false, kill: p => { // with everything it started if (p.pid && !spawn('taskkill', ['/PID', String(p.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' }).on('error', () => {}).pid) p.kill(); }, reaper: null, // nothing to end children when the monitor is killed outright: the collector ends by itself when its parent is gone // never killed automatically, no leak / runaway findings: the system's own processes isProtected: p => p.pid <= 4 || p.rss <= 0 || PROTECTED.has(p.name), ui: { // sent to the page name: 'Windows', sudo: false, posixCpu: false, interval: 3, prioLabel: 'Priority', normalPrio: 8, kernelPrefix: 'build ', sshHint: 'Uses your system ssh client. The server needs the OpenSSH Server feature and PowerShell; nothing else is installed. ' + "For key login, add your public key to the server's authorized_keys.", keyHint: 'default keys / ssh-agent (%USERPROFILE%\\.ssh\\id_*)', ruleActions: [['notify', 'Notify only', ''], ['restart_failed', 'Restart failed services', ''], ['restart_service', 'Restart a service', 'Spooler'], ['kill_top_cpu', 'Terminate top CPU process', ''], ['kill_top_mem', 'Terminate top memory process', ''], ['command', 'Run a command', 'Clear-DnsClientCache']], procActions: cmds([['End task', 'taskkill /PID {n}'], ['Kill', 'taskkill /F /PID {n}', true], ['Kill tree', 'taskkill /F /T /PID {n}', true]]), priorities: cmds(['Idle', 'BelowNormal', 'Normal', 'AboveNormal', 'High'].map(p => [p, `(Get-Process -Id {n}).PriorityClass = '${p}'`])), serviceActions: cmds([['Start', 'Start-Service -Name {q}', false, false], ['Stop', 'Stop-Service -Name {q} -Force', true], ['Restart', 'Restart-Service -Name {q} -Force'], ['Enable', 'Set-Service -Name {q} -StartupType Automatic', false, false], ['Disable', 'Set-Service -Name {q} -StartupType Disabled', true]]), diagnostics: cmds([ ['Disk usage', "Get-PSDrive -PSProvider FileSystem | Format-Table Name, @{ n = 'Used GB'; e = { [math]::Round($_.Used / 1GB, 1) } }, @{ n = 'Free GB'; e = { [math]::Round($_.Free / 1GB, 1) } }, Root"], ['Largest folders in C:\\', 'Get-ChildItem C:\\ -Directory -Force -ErrorAction Ignore | ForEach-Object { [pscustomobject]@{ Folder = $_.FullName; GB = [math]::Round((Get-ChildItem $_.FullName ' + '-Recurse -File -Force -ErrorAction Ignore | Measure-Object Length -Sum).Sum / 1GB, 2) } } | Sort-Object GB -Descending | Select-Object -First 15'], ['Memory', 'Get-CimInstance Win32_OperatingSystem | Format-List TotalVisibleMemorySize, FreePhysicalMemory, TotalVirtualMemorySize, FreeVirtualMemory'], ['Top CPU processes', "Get-Process | Sort-Object CPU -Descending | Select-Object -First 20 Id, ProcessName, CPU, @{ n = 'MemMB'; e = { [int]($_.WorkingSet64 / 1MB) } }, StartTime"], ['Listening ports', 'Get-NetTCPConnection -State Listen | Sort-Object LocalPort | Format-Table LocalAddress, LocalPort, OwningProcess'], ['System errors', events("'System'; Level = 1, 2", 40, 'ProviderName')], ['Application errors', events("'Application'; Level = 1, 2", 40, 'ProviderName')], ['Failed services', failed + ' | Format-Table Name, ExitCode, DisplayName'], ['Logged-in users', 'quser'], ['Last boots', events("'System'; Id = 6005, 6006, 1074", 15, 'Id')]]), systemActions: cmds([['Clean temp files', cleanup], ['Flush DNS cache', "Clear-DnsClientCache; 'done'"], ['Restart failed services', restartFailed], ['Reboot', 'shutdown /r /t 5', true], ['Shut down', 'shutdown /s /t 5', true]]), }, };