Download Server Monitor(cqt-window)/src/core/Platform.cpp from mchuca/ServerMonitor: direct link, hf CLI and curl.
- Browser
- Download file 22.4 kB
-
https://huggingface.co/mchuca/ServerMonitor/resolve/main/Server%20Monitor(cqt-window)/src/core/Platform.cpp
- Command line
-
hf download 'hf://mchuca/ServerMonitor/Server Monitor(cqt-window)/src/core/Platform.cpp'
-
curl -L -o Platform.cpp 'https://huggingface.co/mchuca/ServerMonitor/resolve/main/Server%20Monitor(cqt-window)/src/core/Platform.cpp'
22.4 kB
| // Windows: PowerShell collector (CIM classes + .NET), its parser, and the control commands. | |
| static const char *const kCollector = R"SMSCRIPT( | |
| # 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) } | |
| } | |
| )SMSCRIPT"; | |
| static const char *const kFailed = "Get-CimInstance Win32_Service | Where-Object { $_.StartMode -eq 'Auto' -and $_.State -eq 'Stopped' -and $_.ExitCode -notin 0, 1077 }"; | |
| static const char *const kRestartFailed = R"PS( | ForEach-Object { "restart $($_.Name)"; Start-Service -Name $_.Name })PS"; | |
| namespace P { | |
| const char *const prioLabel = "Priority", *const kernelPrefix = "build ", | |
| *const sshHint = "Uses your system <b>ssh</b> 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 <code>authorized_keys</code>.", | |
| *const cleanup = R"(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 bool sudo = false, posixCpu = false; | |
| const int interval = 3, normalPrio = 8; | |
| // PowerShell runs whatever script arrives on stdin: the encoded command is iex (@($input) -join [char]10) | |
| QStringList shell(int) | |
| { | |
| return {"powershell", "-NoLogo", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-OutputFormat", "Text", "-EncodedCommand", | |
| "aQBlAHgAIAAoAEAAKAAkAGkAbgBwAHUAdAApACAALQBqAG8AaQBuACAAWwBjAGgAYQByAF0AMQAwACkA"}; | |
| } | |
| QByteArray collector(int iv) { return QString("$iv = %1; $once = $false\n").arg(iv).toUtf8() + kCollector; } | |
| QByteArray wrap(const QString &cmd, bool) // no sudo on Windows: 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\nif ($LASTEXITCODE) { exit $LASTEXITCODE }\n" | |
| "if ($Error | Where-Object { $_.FullyQualifiedErrorId -notlike 'NativeCommandError*' }) { exit 1 }; exit 0\n").toUtf8(); // stderr text of a program is not a failure | |
| } | |
| QString quote(QString s) { return "'" + s.replace("'", "''") + "'"; } | |
| QString command(const QString &action, const QString &arg) | |
| { | |
| const QString n = QString::number(arg.toInt()); | |
| return QHash<QString, QString>{{"kill_pid", "Stop-Process -Id " + n + " -Force"}, {"renice", "(Get-Process -Id " + n + ").PriorityClass = 'Idle'"}, | |
| {"restart_service", "Restart-Service -Name " + quote(arg) + " -Force"}, {"restart_failed", QString(kFailed) + kRestartFailed}}.value(action); | |
| } | |
| QString serviceLogs(const QString &unit, int lines) | |
| { | |
| return QString(R"($s = Get-CimInstance Win32_Service | Where-Object Name -eq %1; $s | Format-List Name, DisplayName, State, StartMode, ExitCode, ProcessId, PathName; )" | |
| R"(Get-WinEvent -FilterHashtable @{ LogName = 'System'; ProviderName = 'Service Control Manager' } -MaxEvents 3000 -ErrorAction Ignore | )" | |
| R"(Where-Object { $_.Message -like ('*' + $s.DisplayName + '*') } | Select-Object -First %2 | Format-Table TimeCreated, LevelDisplayName, Message -Wrap)") | |
| .arg(quote(unit)).arg(lines); | |
| } | |
| QString power(bool reboot) { return reboot ? "shutdown /r /t 5" : "shutdown /s /t 5"; } | |
| bool isProtected(int pid, int, double rss, const QString &name) | |
| { | |
| static const QSet<QString> system = {"System", "Registry", "Memory Compression", "smss.exe", "csrss.exe", "wininit.exe", "winlogon.exe", "services.exe", | |
| "lsass.exe", "svchost.exe", "sshd.exe", "dwm.exe"}; | |
| return pid <= 4 || rss <= 0 || system.contains(name); | |
| } | |
| const QVector<Def> &ruleActions() | |
| { | |
| static const QVector<Def> d = {{"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"}}; | |
| return d; | |
| } | |
| const QVector<Cmd> &procActions() | |
| { | |
| static const QVector<Cmd> d = {{"End task", "taskkill /PID %1"}, {"Kill", "taskkill /F /PID %1", true}, {"Kill tree", "taskkill /F /T /PID %1", true}}; | |
| return d; | |
| } | |
| const QVector<Cmd> &priorities() | |
| { | |
| static const QVector<Cmd> d = [] { | |
| QVector<Cmd> v; | |
| for (const char *p : {"Idle", "BelowNormal", "Normal", "AboveNormal", "High"}) v << Cmd{p, QString("(Get-Process -Id %1).PriorityClass = '") + p + "'"}; | |
| return v; | |
| }(); | |
| return d; | |
| } | |
| const QVector<Cmd> &serviceActions() | |
| { | |
| static const QVector<Cmd> d = {{"Start", "Start-Service -Name %1", false, false}, {"Stop", "Stop-Service -Name %1 -Force", true}, {"Restart", "Restart-Service -Name %1 -Force"}, | |
| {"Enable", "Set-Service -Name %1 -StartupType Automatic", false, false}, {"Disable", "Set-Service -Name %1 -StartupType Disabled", true}}; | |
| return d; | |
| } | |
| const QVector<Cmd> &diagnostics() | |
| { | |
| static const QVector<Cmd> d = { | |
| {"Disk usage", R"(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:\\", R"(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", QString(kFailed) + " | 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"}}; | |
| return d; | |
| } | |
| const QVector<Cmd> &systemActions() | |
| { | |
| static const QVector<Cmd> d = {{"Clean temp files", cleanup}, {"Flush DNS cache", "Clear-DnsClientCache; 'done'"}, {"Restart failed services", QString(kFailed) + kRestartFailed}, | |
| {"Reboot", "shutdown /r /t 5", true}, {"Shut down", "shutdown /s /t 5", true}}; | |
| return d; | |
| } | |
| } // namespace P | |
| // ---- collector frame parser: rows are key=value or |-separated; most values are already rates ---------- | |
| Metrics MetricsEngine::process(const QByteArray &raw, qint64 now) | |
| { | |
| QHash<QString, QStringList> sec; | |
| QStringList *cur = nullptr; | |
| for (const QByteArray &line : raw.split('\n')) { | |
| const QString l = QString::fromUtf8(line).trimmed(); | |
| if (l.startsWith("@@S ")) cur = &sec[l.mid(4)]; | |
| else if (cur && !l.isEmpty() && !l.startsWith("@@")) cur->append(l); | |
| } | |
| auto kv = [&](const char *k) { | |
| QHash<QString, QString> h; | |
| for (const QString &l : sec.value(k)) | |
| if (const int e = l.indexOf('='); e > 0) h[l.left(e)] = l.mid(e + 1); | |
| return h; | |
| }; | |
| auto rows = [&](const char *k, int minFields) { | |
| QVector<QStringList> r; | |
| for (const QString &l : sec.value(k)) | |
| if (const QStringList f = l.split('|'); f.size() >= minFields) r << f; | |
| return r; | |
| }; | |
| Metrics m; | |
| m.timestamp = now; | |
| if (sec.contains("info")) m_info = kv("info"); | |
| if (sec.contains("users")) { | |
| m_users.clear(); | |
| for (const auto &f : rows("users", 2)) | |
| if (!f[1].isEmpty()) m_users[f[0].toInt()] = f[1]; | |
| } | |
| m.hostname = m_info["hostname"], m.os = m_info["os"], m.kernel = m_info["kernel"], m.arch = m_info["arch"]; | |
| m.cpuModel = m_info["cpumodel"], m.virt = m_info["virt"]; | |
| const auto os = kv("os"); | |
| const double ts = os["ts"].toDouble() / 1000; // collector clock, seconds | |
| m.uptime = os["uptime"].toDouble(); | |
| if (m.uptime <= 0 || ts <= 0) return m; | |
| const double dt = m_upt > 0 ? ts - m_upt : 0; | |
| const bool rates = dt > 0.05; | |
| QHash<QString, QVector<double>> next; | |
| auto delta = [&](const QString &key, const QVector<double> &v) { // per-second rates of a counter vector | |
| QVector<double> d(v.size(), 0.0); | |
| const auto p = m_ctr.value(key); | |
| if (rates && p.size() == v.size()) | |
| for (int i = 0; i < v.size(); ++i) d[i] = qMax(0.0, (v[i] - p[i]) / dt); | |
| next[key] = v; | |
| return d; | |
| }; | |
| auto pct = [](const QString &s) { return qBound(0.0, s.toDouble(), 100.0); }; | |
| // CPU: privileged time includes interrupts + DPCs; show them apart | |
| QMap<int, CoreStat> cores; | |
| m.avgMhz = m_info["mhz"].toDouble(); | |
| for (const auto &f : rows("cpu", 5)) { | |
| if (f[0] != "_Total") { cores[f[0].toInt()] = {pct(f[1]), m.avgMhz}; continue; } | |
| m.cpuUsage = pct(f[1]), m.cpuUser = pct(f[2]), m.cpuIrq = pct(f[4]), m.cpuSystem = qMax(0.0, pct(f[3]) - m.cpuIrq), m.intrPerSec = f.value(5).toDouble(); | |
| } | |
| m.cores = cores.values().toVector(); | |
| m.cpuCount = qMax(1, m.cores.size()); | |
| // load average with the Unix meaning: running + waiting threads, smoothed over 1 / 5 / 15 minutes | |
| const auto sys = kv("sys"); | |
| const double queue = sys["queue"].toDouble(), inst = m.cpuUsage / 100 * m.cpuCount + queue, spans[3] = {60, 300, 900}; | |
| QVector<double> load = m_ctr.value("load", {inst, inst, inst}); | |
| for (int i = 0; i < 3; ++i) load[i] += (inst - load[i]) * (1 - std::exp(-qMax(0.0, dt) / spans[i])); // dt < 0: the clock was set back | |
| next["load"] = load; | |
| m.load1 = load[0], m.load5 = load[1], m.load15 = load[2]; | |
| m.ctxtPerSec = sys["ctxt"].toDouble(), m.procsRunning = qRound(m.cpuUsage / 100 * m.cpuCount), m.procsBlocked = int(queue); | |
| // memory: standby pages are the file cache, the page file is swap | |
| const auto mem = kv("mem"); | |
| m.memTotal = os["memtotal"].toDouble(), m.memAvailable = mem["avail"].toDouble(), m.memFree = mem["free"].toDouble(); | |
| m.cached = mem["standby"].toDouble() + mem["syscache"].toDouble(), m.slab = mem["pool"].toDouble(), m.dirty = mem["modified"].toDouble(); | |
| m.memUsed = qMax(0.0, m.memTotal - m.memAvailable), m.swapTotal = os["swaptotal"].toDouble(), m.swapUsed = qMax(0.0, m.swapTotal - os["swapfree"].toDouble()); | |
| m.memPct = m.memTotal > 0 ? m.memUsed * 100 / m.memTotal : 0; | |
| m.swapPct = m.swapTotal > 0 ? m.swapUsed * 100 / m.swapTotal : 0; | |
| // network: a VM's own NIC ("Microsoft Hyper-V Network Adapter") counts as physical, host-side virtual switches do not | |
| static const QRegularExpression virt("virtual ethernet|virtualbox|vmware virtual|vethernet|loopback|pseudo|tap-|bluetooth|wan miniport|wsl|docker", QRegularExpression::CaseInsensitiveOption); | |
| for (const auto &f : rows("net", 10)) { | |
| NetIf n; | |
| n.name = f[0], n.state = f[1].toLower(), n.speed = f[2].toInt() > 0 ? f[2].toInt() : -1; | |
| n.virt = f[3] == "Loopback" || f[3] == "Tunnel" || virt.match(f[0] + " " + f.value(10)).hasMatch(); | |
| n.rxBytes = f[4].toDouble(), n.txBytes = f[5].toDouble(), n.errors = f[8].toDouble(), n.drops = f[9].toDouble(); | |
| const auto d = delta("net:" + n.name, {n.rxBytes, n.txBytes, f[6].toDouble(), f[7].toDouble()}); | |
| n.rxBps = d[0], n.txBps = d[1], n.rxPps = d[2], n.txPps = d[3]; | |
| if (!n.virt) m.netRxBps += n.rxBps, m.netTxBps += n.txBps; | |
| m.nets << n; | |
| } | |
| std::sort(m.nets.begin(), m.nets.end(), [](const NetIf &a, const NetIf &b) { return a.virt != b.virt ? !a.virt : a.name < b.name; }); | |
| static const QHash<QString, QString> tcpNames = {{"Established", "ESTABLISHED"}, {"Listen", "LISTEN"}, {"TimeWait", "TIME_WAIT"}, {"CloseWait", "CLOSE_WAIT"}}; | |
| for (const QString &l : sec.value("tcp")) { | |
| const QStringList f = l.split(' '); | |
| m.tcp[tcpNames.value(f[0], f[0].toUpper())] += f.value(1).toInt(), m.socketsUsed += f.value(1).toInt(); | |
| } | |
| // disks and volumes | |
| for (const auto &f : rows("disk", 6)) { | |
| DiskIO d; | |
| d.name = f[0], d.readBps = f[1].toDouble(), d.writeBps = f[2].toDouble(), d.readIops = f[3].toDouble(), d.writeIops = f[4].toDouble(); | |
| d.util = f[5].isEmpty() ? 0 : 100 - pct(f[5]); // field = idle % | |
| m.diskReadBps += d.readBps, m.diskWriteBps += d.writeBps; | |
| if (d.util >= m.maxDiskUtil) m.maxDiskUtil = d.util, m.busiestDisk = d.name; | |
| m.disks << d; | |
| } | |
| for (const auto &f : rows("df", 5)) { | |
| MountInfo mt; | |
| mt.mount = f[0], mt.device = f[1], mt.type = f[2], mt.total = f[3].toDouble(), mt.avail = f[4].toDouble(), mt.used = mt.total - mt.avail; | |
| if (mt.total <= 0) continue; | |
| mt.pct = mt.used * 100 / mt.total; | |
| if (mt.pct >= m.maxDiskPct) m.maxDiskPct = mt.pct, m.fullestMount = mt.mount; | |
| m.mounts << mt; | |
| } | |
| // processes: "pid|ppid|cpuTime (100 ns)|priority|threads|created (unix s)|vsz|rss|name" | |
| QHash<int, double> ticks; | |
| int fresh = 0; | |
| for (const auto &f : rows("procs", 9)) { | |
| ProcInfo p; | |
| if ((p.pid = f[0].toInt()) <= 0) continue; // 0 = idle process | |
| const double born = f[5].toDouble(); | |
| p.ppid = f[1].toInt(), p.nice = f[3].toInt(), p.threads = f[4].toInt(), p.age = born > 0 ? qMax(0.0, ts - born) : 0; | |
| p.vsz = f[6].toDouble(), p.rss = f[7].toDouble(), p.name = f.mid(8).join('|'); | |
| ticks[p.pid] = f[2].toDouble(); | |
| if (!m_ticks.contains(p.pid)) ++fresh; | |
| else if (rates) p.cpu = qBound(0.0, (ticks[p.pid] - m_ticks[p.pid]) / 1e7 / dt * 100, 100.0 * m.cpuCount); | |
| p.state = p.cpu > 0.5 ? 'R' : 'S'; | |
| p.memPct = m.memTotal > 0 ? p.rss * 100 / m.memTotal : 0; | |
| p.user = m_users.value(p.pid, "—"); | |
| m.threadsTotal += p.threads; | |
| m.procs << p; | |
| } | |
| m.forksPerSec = rates ? fresh / dt : 0; | |
| std::sort(m.procs.begin(), m.procs.end(), [](const ProcInfo &a, const ProcInfo &b) { return a.cpu != b.cpu ? a.cpu > b.cpu : a.rss > b.rss; }); | |
| m.loggedUsers = sec.value("sessions").value(0).toInt(); | |
| // services / GPUs arrive every few samples: keep the last list. "Failed" = automatic, stopped, with an error exit code | |
| if (sec.contains("services")) { | |
| m_services.clear(); | |
| for (const auto &f : rows("services", 5)) { | |
| const bool failed = f[2] == "Auto" && f[1] == "Stopped" && f[3].toInt() != 0 && f[3].toInt() != 1077; | |
| m_services << ServiceInfo{f[0], f[2], failed ? "failed" : f[1] == "Running" ? "active" : "inactive", f[1].toLower(), f.mid(4).join('|')}; | |
| } | |
| } | |
| m.services = m_services; | |
| for (const auto &s : m.services) m.servicesFailed += s.active == "failed", m.servicesRunning += s.sub == "running"; | |
| if (sec.contains("gpu")) { | |
| m_gpus.clear(); | |
| for (const QString &l : sec.value("gpu")) { | |
| const QStringList f = l.split(','); | |
| auto n = [&](int i) { return f[i].trimmed().toDouble(); }; | |
| if (f.size() >= 8) m_gpus << GpuInfo{int(n(0)), f[1].trimmed(), n(2), n(3), n(4), n(5), n(6), n(7)}; | |
| } | |
| } | |
| m.gpus = m_gpus; | |
| QSet<QString> tn; | |
| for (const auto &f : rows("thermal", 2)) { | |
| TempSensor t{f[0], f[1].toDouble()}; | |
| if (t.celsius <= 0 || t.celsius > 150 || tn.contains(t.name)) continue; | |
| tn << t.name, m.temps << t, m.maxTemp = qMax(m.maxTemp, t.celsius); | |
| } | |
| m_ctr = next, m_ticks = ticks, m_upt = ts; | |
| m.valid = rates; // the first sample has no rates yet | |
| return m; | |
| } | |