mchuca's picture
Server Monitor: six editions (C++/Qt, Python, web for Linux and Windows), requirements and developer kit
bad179a
Raw History Blame Contribute Delete
20 kB
"""Platform module (Windows): everything OS-specific - collector script, process spawning, frame parser,
command tables and the texts that differ between the editions."""
import atexit, functools, math, os, re, tempfile
from metrics import Core, Disk, Metrics, Mount, Net, Proc, Service, add_disk, add_mount, finish, num, rates, sections, to_int
NAME, HAS_SUDO, POSIX_CPU, INTERVAL = 'Windows', False, False, 3 # POSIX_CPU: I/O wait and steal exist; INTERVAL: default sample seconds
SPAWN = {'creationflags': 0x08000000} if os.name == 'nt' else {} # extra subprocess.Popen arguments: CREATE_NO_WINDOW
# PowerShell runs whatever script arrives on stdin: -EncodedCommand is "iex (@($input) -join [char]10)", so nothing needs quoting
PS_ARGS = ('-NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -OutputFormat Text -EncodedCommand '
'aQBlAHgAIAAoAEAAKAAkAGkAbgBwAHUAdAApACAALQBqAG8AaQBuACAAWwBjAGgAYQByAF0AMQAwACkA').split()
def config_dir(): return os.path.join(os.environ.get('APPDATA') or os.path.expanduser('~'), 'ServerMonitorPy')
def open_folder(path): os.startfile(path)
def shell(interval=None):
"""Command line that runs the script arriving on stdin (locally, or joined by spaces as the ssh remote command)."""
return ['powershell'] + PS_ARGS
def collector(interval):
"""Stdin for the collector process."""
return f'$iv = {interval}; $once = $false\n' + COLLECTOR
def kill(p): p.kill()
def quote(s): return "'" + s.replace("'", "''") + "'"
def wrap(cmd, privileged, sudo):
"""Stdin for a one-shot command (there is no sudo: run the app elevated for privileged actions)."""
return ("[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\n'
'if ($LASTEXITCODE) { exit $LASTEXITCODE }\n' # text a program writes to stderr is not a failure; its exit code or a failing cmdlet is
"if ($Error | Where-Object { $_.FullyQualifiedErrorId -notlike 'NativeCommandError*' }) { exit 1 }; exit 0\n")
@functools.lru_cache(None)
def askpass():
"""Helper script that answers ssh's password prompt from %SERVERMONITOR_ASKPASS%; removed on exit."""
fd, path = tempfile.mkstemp(prefix='servermonitor-askpass-', suffix='.cmd')
os.write(fd, b'@echo off\r\nsetlocal EnableDelayedExpansion\r\necho(!SERVERMONITOR_ASKPASS!\r\n')
os.close(fd)
atexit.register(os.remove, path)
return path
def protected(p):
"""Processes that are never killed automatically and get no leak / runaway findings."""
return p.pid <= 4 or p.rss <= 0 or p.name in PROTECTED
def thrashing(iowait, mem, disk_busy):
"""Rest of the sentence "Swap … used" when heavy swap use is thrashing ('' = it is not); iowait and disk_busy are 15-minute averages."""
return f', memory {mem:.1f}% full and disks {disk_busy:.1f}% busy' if mem > 90 and disk_busy > 50 else ''
def priority_level(priority):
"""How the priority column value compares with normal: > 0 raised, < 0 lowered."""
return priority - 8
def cpu_tile(m):
"""(value, sub text, warn) of the CPU tab tile TEXT['cpu_tile']."""
return f'{m.cpu_irq:.1f}%', 'hardware interrupts and deferred calls', m.cpu_irq > 15
# ---- command tables (PowerShell): {q} = quoted argument, {n} = integer argument ----------------
PROTECTED = {'System', 'Registry', 'Memory Compression', 'smss.exe', 'csrss.exe', 'wininit.exe', 'winlogon.exe', 'services.exe', 'lsass.exe',
'svchost.exe', 'sshd.exe', 'dwm.exe'}
FAILED = "Get-CimInstance Win32_Service | Where-Object { $_.StartMode -eq 'Auto' -and $_.State -eq 'Stopped' -and $_.ExitCode -notin 0, 1077 }"
CMD = {
'kill_pid': 'Stop-Process -Id {n} -Force', 'renice': "(Get-Process -Id {n}).PriorityClass = 'Idle'",
'restart_service': 'Restart-Service -Name {q} -Force',
'restart_failed': FAILED + ' | ForEach-Object { "restart $($_.Name)"; Start-Service -Name $_.Name }'}
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')
HINTS = {'restart_service': 'Spooler', 'command': 'Clear-DnsClientCache'} # rule-argument placeholders
POWER = {'Reboot': 'shutdown /r /t 5', 'Shut down': 'shutdown /s /t 5'}
# (label, command, flags): b = toolbar button, c = ask first, d = dangerous
PROC_ACTIONS = [('End task', 'taskkill /PID {n}', 'bc'), ('Kill', 'taskkill /F /PID {n}', 'bcd'), ('Kill tree', 'taskkill /F /T /PID {n}', 'bcd')]
PRIORITIES = {v: v for v in ('Idle', 'BelowNormal', 'Normal', 'AboveNormal', 'High')}
PRIORITY_CMD = "(Get-Process -Id {n}).PriorityClass = '{v}'"
SERVICE_VERBS = {
'start': 'Start-Service -Name {q}', 'stop': 'Stop-Service -Name {q} -Force', 'restart': 'Restart-Service -Name {q} -Force',
'enable': 'Set-Service -Name {q} -StartupType Automatic', 'disable': 'Set-Service -Name {q} -StartupType Disabled'}
SERVICE_LOGS = ('$s = Get-CimInstance Win32_Service | Where-Object Name -eq {q}; $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 {n} | "
'Format-Table TimeCreated, LevelDisplayName, Message -Wrap')
QUICK = [ # console: quick diagnostics
('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', "Get-WinEvent -FilterHashtable @{ LogName = 'System'; Level = 1, 2 } -MaxEvents 40 | Format-Table TimeCreated, ProviderName, Message -Wrap"),
('Application errors', "Get-WinEvent -FilterHashtable @{ LogName = 'Application'; Level = 1, 2 } -MaxEvents 40 | Format-Table TimeCreated, ProviderName, Message -Wrap"),
('Failed services', FAILED + ' | Format-Table Name, ExitCode, DisplayName'),
('Logged-in users', 'quser'),
('Last boots', "Get-WinEvent -FilterHashtable @{ LogName = 'System'; Id = 6005, 6006, 1074 } -MaxEvents 15 | Format-Table TimeCreated, Id, Message -Wrap")]
ACTIONS = [ # console: system actions (confirmed, privileged); the POWER ones are shown as dangerous
('Clean temp files', CLEANUP), ('Flush DNS cache', "Clear-DnsClientCache; 'done'"), ('Restart failed services', CMD['restart_failed']),
('Reboot', POWER['Reboot']), ('Shut down', POWER['Shut down'])]
TEXT = {
'cpu_tile': 'Interrupts + DPC', 'priority': 'Priority', 'kernel': 'build ',
'renice': 'Set priority to Idle', 'renice_mode': 'Lower priority (Idle class)', 'renice_advice': 'Lower its priority or stop it if it is stuck.',
'ssh_hint': '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.",
'key_hint': 'default keys / ssh-agent (%USERPROFILE%\\.ssh\\id_*)',
'console_hint': 'Type a PowerShell command and press Enter (↑/↓ history)'}
# ---- collector frame parser -------------------------------------------------------------------
VIRTUAL_IF = re.compile(r'virtual ethernet|virtualbox|vmware virtual|vethernet|loopback|pseudo|tap-|bluetooth|wan miniport|wsl|docker', re.I)
TCP_STATES = {'Established': 'ESTABLISHED', 'Listen': 'LISTEN', 'TimeWait': 'TIME_WAIT', 'CloseWait': 'CLOSE_WAIT'}
def parse(frame, st, now):
"""Collector frame -> Metrics; st keeps the counters of the previous frame (rates), the load averages and the slow sections."""
sec, m = sections(frame), Metrics(now)
def rows(name, fields): # |-separated rows of a section with at least that many fields
return [f for f in (l.split('|') for l in sec.get(name, ())) if len(f) >= fields]
def values(name): # key=value section -> number lookup (missing or empty = 0)
kv = dict(l.split('=', 1) for l in sec.get(name, ()) if '=' in l)
return lambda k: num(kv.get(k))
if 'info' in sec: st['info'] = dict(l.split('=', 1) for l in sec['info'] if '=' in l)
if 'users' in sec: st['users'] = {to_int(f[0]): f[1] for f in rows('users', 2)}
info, osv, sysv, mem = st.get('info', {}), values('os'), values('sys'), values('mem')
m.hostname, m.os, m.kernel, m.arch, m.cpu_model, m.virt = (info.get(k, '').strip() for k in ('hostname', 'os', 'kernel', 'arch', 'cpumodel', 'virt'))
m.uptime = osv('uptime')
if m.uptime <= 0: return m
ts = osv('ts') or now
dt = max(0.0, (ts - st['ts']) / 1000) if 'ts' in st else 0.0
live, delta = dt > 0.05, rates(st, dt)
# CPU: name|total%|user%|privileged%|irq%|interrupts/s; "_Total" is the machine, the other names are cores
mhz, cores = num(info.get('mhz')), []
for f in rows('cpu', 2):
total, user, privileged, irq, interrupts = (num(x) for x in (f[1:6] + [''] * 5)[:5])
if f[0] == '_Total':
m.cpu_usage, m.cpu_user, m.cpu_irq, m.cpu_system, m.intr_per_sec = total, user, irq, max(0.0, privileged - irq), interrupts
else:
cores.append((to_int(f[0]), Core(total, mhz)))
m.cores, m.avg_mhz = [c for _, c in sorted(cores)], mhz
m.cpu_count = max(1, len(cores))
# load average with the Unix meaning: running + waiting tasks, as 1 / 5 / 15 minute exponential moving averages
queue = sysv('queue')
instant = m.cpu_usage / 100 * m.cpu_count + queue
st['load'] = [l + (instant - l) * (1 - math.exp(-dt / t)) for l, t in zip(st['load'], (60, 300, 900))] if 'load' in st else [instant] * 3
m.load1, m.load5, m.load15 = st['load']
m.procs_running, m.procs_blocked, m.ctxt_per_sec = math.floor(m.cpu_usage / 100 * m.cpu_count + 0.5), int(queue), sysv('ctxt')
# memory
m.mem_total, m.swap_total, m.mem_available, m.mem_free = osv('memtotal'), osv('swaptotal'), mem('avail'), mem('free')
m.cached, m.slab, m.dirty = mem('standby') + mem('syscache'), mem('pool'), mem('modified')
m.mem_used, m.swap_used = max(0.0, m.mem_total - m.mem_available), m.swap_total - osv('swapfree')
# network: name|status|speedMbps|type|rxBytes|txBytes|rxPkts|txPkts|errors|drops|description
for f in rows('net', 10):
rx, tx = num(f[4]), num(f[5])
virtual = f[3] in ('Loopback', 'Tunnel') or bool(VIRTUAL_IF.search(' '.join([f[0]] + f[10:])))
m.nets.append(Net(f[0], f[1].lower(), to_int(f[2]), virtual, *delta('net:' + f[0], [rx, tx, num(f[6]), num(f[7])]), rx, tx, num(f[8]), num(f[9])))
for f in map(str.split, sec.get('tcp', ())):
if len(f) > 1:
name = TCP_STATES.get(f[0], f[0].upper())
m.tcp[name] = m.tcp.get(name, 0) + to_int(f[1])
m.sockets_used = sum(m.tcp.values())
# disks: name|readBps|writeBps|readIops|writeIops|idle% file systems: mount|label|fs|total|free
for f in rows('disk', 5):
idle = ''.join(f[5:6]).strip()
add_disk(m, Disk(f[0], num(f[1]), num(f[2]), num(f[3]), num(f[4]), min(max(100 - num(idle), 0.0), 100.0) if idle else 0.0, 0.0, 0.0))
for f in rows('df', 5):
total, free = num(f[3]), num(f[4])
if total > 0: add_mount(m, Mount(f[1], f[2], f[0], total, total - free, free, (total - free) * 100 / total))
# processes: pid|ppid|cpuTime100ns|priority|threads|createdUnixSec|vsz|rss|name
old, users, ticks = st.get('ticks', {}), st.get('users', {}), {}
for f in rows('procs', 9):
pid, born, rss = to_int(f[0]), num(f[5]), num(f[7])
if not pid: continue
ticks[pid] = num(f[2])
cpu = min(max((ticks[pid] - old[pid]) / 1e7 / dt * 100, 0.0), 100.0 * m.cpu_count) if live and pid in old else 0.0
m.procs.append(Proc(pid, to_int(f[1]), to_int(f[4]), to_int(f[3]), '|'.join(f[8:]), users.get(pid) or '—', 'R' if cpu > 0.5 else 'S', cpu,
rss * 100 / m.mem_total if m.mem_total > 0 else 0, rss, num(f[6]), max(0.0, ts / 1000 - born) if born else 0.0))
m.forks_per_sec = sum(pid not in old for pid in ticks) / dt if live and old else 0.0
if 'services' in sec: # name|state|startmode|exitcode|display
st['services'] = [Service(f[0], f[2], 'failed' if f[2] == 'Auto' and f[1] == 'Stopped' and to_int(f[3]) not in (0, 1077)
else 'active' if f[1] == 'Running' else 'inactive', f[1].lower(), '|'.join(f[4:])) for f in rows('services', 4)]
m.logged_users = to_int(''.join(sec.get('sessions', [])[:1]))
st['ticks'], st['ts'] = ticks, ts
m.valid = live # the first sample has no rates yet
return finish(m, sec, st, 1)
COLLECTOR = r'''# Server Monitor collector for Windows (PowerShell 5.1+, ASCII only).
# The caller prepends "$iv = <seconds>; $once = $false". One frame per interval:
# "@@SNAP_BEGIN", "@@S <section>" + rows (key=value or |-separated), "@@SNAP_END".
$ErrorActionPreference = 'SilentlyContinue'
$ProgressPreference = 'SilentlyContinue'
[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false
function Cim($class, $ns = 'root/cimv2') { Get-CimInstance -ClassName $class -Namespace $ns }
function Clean($s) { ("$s" -replace '[|\r\n]', ' ').Trim() }
$epoch = [DateTime]'1970-01-01'
$smi = Get-Command nvidia-smi.exe | Select-Object -First 1 -ExpandProperty Path
# Console.Out reports no error when the pipe is closed, so the collector also ends when its parent process is gone.
$parent = Get-Process -Id (Get-CimInstance Win32_Process -Filter "ProcessId = $PID").ParentProcessId
$n = 0
while ($true) {
$t0 = Get-Date
$out = New-Object System.Collections.Generic.List[string]
$out.Add('@@SNAP_BEGIN')
$os = Cim Win32_OperatingSystem
if ($n % 15 -eq 0) {
$cs = Cim Win32_ComputerSystem
$cpu = @(Cim Win32_Processor)[0]
$virt = Clean ($cs.Manufacturer + ' ' + $cs.Model)
$admin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
$out.Add('@@S info')
$out.Add("hostname=$($cs.Name)")
$out.Add("os=$(Clean $os.Caption)")
$out.Add("kernel=$($os.Version)")
$out.Add("arch=$($os.OSArchitecture)")
$out.Add("cpumodel=$(Clean $cpu.Name)")
$out.Add("mhz=$($cpu.MaxClockSpeed)")
$out.Add("virt=$virt")
$out.Add("admin=$([int]$admin)")
if ($admin) {
$out.Add('@@S users')
Get-Process -IncludeUserName | ForEach-Object { $out.Add("$($_.Id)|$($_.UserName)") }
}
}
$out.Add('@@S os')
$out.Add("ts=$([long](([DateTime]::UtcNow - $epoch).TotalMilliseconds))")
$out.Add("uptime=$([long](((Get-Date) - $os.LastBootUpTime).TotalSeconds))")
$out.Add("memtotal=$([long]$os.TotalVisibleMemorySize * 1024)")
$out.Add("swaptotal=$([long]$os.SizeStoredInPagingFiles * 1024)")
$out.Add("swapfree=$([long]$os.FreeSpaceInPagingFiles * 1024)")
$out.Add('@@S cpu')
Cim Win32_PerfFormattedData_PerfOS_Processor | ForEach-Object {
$out.Add("$($_.Name)|$($_.PercentProcessorTime)|$($_.PercentUserTime)|$($_.PercentPrivilegedTime)|$([long]$_.PercentInterruptTime + [long]$_.PercentDPCTime)|$($_.InterruptsPersec)")
}
$sys = Cim Win32_PerfFormattedData_PerfOS_System
$out.Add('@@S sys')
$out.Add("queue=$($sys.ProcessorQueueLength)")
$out.Add("ctxt=$($sys.ContextSwitchesPersec)")
$out.Add("threads=$($sys.Threads)")
$pm = Cim Win32_PerfFormattedData_PerfOS_Memory
$out.Add('@@S mem')
$out.Add("avail=$($pm.AvailableBytes)")
$out.Add("free=$($pm.FreeAndZeroPageListBytes)")
$out.Add("standby=$([long]$pm.StandbyCacheCoreBytes + [long]$pm.StandbyCacheNormalPriorityBytes + [long]$pm.StandbyCacheReserveBytes)")
$out.Add("syscache=$($pm.CacheBytes)")
$out.Add("modified=$($pm.ModifiedPageListBytes)")
$out.Add("pool=$([long]$pm.PoolPagedBytes + [long]$pm.PoolNonpagedBytes)")
$out.Add("commit=$($pm.CommittedBytes)")
$out.Add("commitlimit=$($pm.CommitLimit)")
$out.Add("pages=$($pm.PagesPersec)")
$out.Add('@@S net')
[System.Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces() | ForEach-Object {
$s = $null
$s = $_.GetIPStatistics()
if ($s) { $out.Add("$(Clean $_.Name)|$($_.OperationalStatus)|$([long]($_.Speed / 1000000))|$($_.NetworkInterfaceType)|$($s.BytesReceived)|$($s.BytesSent)|$($s.UnicastPacketsReceived)|$($s.UnicastPacketsSent)|$([long]$s.IncomingPacketsWithErrors + [long]$s.OutgoingPacketsWithErrors)|$([long]$s.IncomingPacketsDiscarded + [long]$s.OutgoingPacketsDiscarded)|$(Clean $_.Description)") }
}
$ip = [System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties()
$out.Add('@@S tcp')
$ip.GetActiveTcpConnections() | Group-Object State | ForEach-Object { $out.Add("$($_.Name) $($_.Count)") }
$out.Add("Listen $(@($ip.GetActiveTcpListeners()).Count)")
$out.Add('@@S disk')
Cim Win32_PerfFormattedData_PerfDisk_PhysicalDisk | Where-Object { $_.Name -ne '_Total' } | ForEach-Object {
$out.Add("$(Clean $_.Name)|$($_.DiskReadBytesPersec)|$($_.DiskWriteBytesPersec)|$($_.DiskReadsPersec)|$($_.DiskWritesPersec)|$($_.PercentIdleTime)")
}
$out.Add('@@S df')
[System.IO.DriveInfo]::GetDrives() | Where-Object { $_.IsReady -and $_.DriveType -eq 'Fixed' } | ForEach-Object {
$out.Add("$($_.Name)|$(Clean $_.VolumeLabel)|$($_.DriveFormat)|$($_.TotalSize)|$($_.AvailableFreeSpace)")
}
$sessions = @{}
$out.Add('@@S procs')
Cim Win32_Process | ForEach-Object {
$born = 0
if ($_.CreationDate) { $born = [long](($_.CreationDate.ToUniversalTime() - $epoch).TotalSeconds) }
if ($_.Name -eq 'explorer.exe') { $sessions[$_.SessionId] = 1 }
$out.Add("$($_.ProcessId)|$($_.ParentProcessId)|$([long]$_.KernelModeTime + [long]$_.UserModeTime)|$($_.Priority)|$($_.ThreadCount)|$born|$($_.VirtualSize)|$($_.WorkingSetSize)|$(Clean $_.Name)")
}
$out.Add('@@S sessions')
$out.Add("$($sessions.Count)")
if ($n % 5 -eq 0) {
$out.Add('@@S services')
Cim Win32_Service | ForEach-Object { $out.Add("$($_.Name)|$($_.State)|$($_.StartMode)|$($_.ExitCode)|$(Clean $_.DisplayName)") }
}
$out.Add('@@S thermal')
Cim MSAcpi_ThermalZoneTemperature 'root/wmi' | ForEach-Object { $out.Add("$(Clean $_.InstanceName)|$(($_.CurrentTemperature - 2732) / 10)") }
if ($smi -and $n % 3 -eq 0) {
$out.Add('@@S gpu')
& $smi '--query-gpu=index,name,utilization.gpu,memory.used,memory.total,temperature.gpu,power.draw,fan.speed' '--format=csv,noheader,nounits' | ForEach-Object { $out.Add("$_") }
}
$out.Add('@@SNAP_END')
try { [Console]::Out.Write(($out -join "`n") + "`n"); [Console]::Out.Flush() } catch { exit }
if ($once -or $parent.HasExited) { break }
$n++
$left = $iv * 1000 - ((Get-Date) - $t0).TotalMilliseconds
if ($left -gt 0) { Start-Sleep -Milliseconds ([int]$left) }
}
'''