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
21.3 kB
#include "History.h"
#include <QDateTime>
#include <QDir>
#include <QFile>
#include <QSaveFile>
#include <algorithm>
#include <cstring>
const char *const hKeys[H_COUNT] = {"cpu", "iowait", "load", "mem", "swap", "disk", "diskio", "rx", "tx", "rd", "wr", "temp", "procs", "gpu", "failed"};
const char *const hNames[H_COUNT] = {"CPU", "I/O wait", "Load (1m)", "Memory", "Swap", "Disk usage", "Disk busy", "Net download",
"Net upload", "Disk read", "Disk write", "Temperature", "Processes", "GPU", "Failed services"};
QString tierName(Tier t) { return QStringList{"every sample", "1 minute", "1 hour", "1 day"}.value(int(t)); }
static const QByteArray kHeader = QByteArray("SMH1") + char(H_COUNT) + char(0) + char(sizeof(HPoint) & 0xff) + char(sizeof(HPoint) >> 8);
// ---- accumulator ----------------------------------------------------------------
HistoryStore::Acc::Acc(qint64 b) : bucket(b) { std::fill(mx, mx + H_COUNT, NAN); }
void HistoryStore::Acc::add(const HPoint &p)
{
n += p.n, nUp += p.nUp;
if (p.nUp)
for (int i = 0; i < H_COUNT; ++i)
if (!std::isnan(p.avg[i])) {
sum[i] += double(p.avg[i]) * p.nUp, cnt[i] += p.nUp;
if (std::isnan(mx[i]) || p.max[i] > mx[i]) mx[i] = p.max[i];
}
}
HPoint HistoryStore::Acc::point() const
{
HPoint p;
p.ts = bucket, p.n = n, p.nUp = nUp;
for (int i = 0; i < H_COUNT; ++i) p.avg[i] = cnt[i] ? float(sum[i] / cnt[i]) : NAN, p.max[i] = mx[i];
return p;
}
// ---- store ----------------------------------------------------------------------
QString HistoryStore::file(int t) const { return m_dir + "/" + QStringList{"raw", "minute", "hour", "day"}[t] + ".bin"; }
qint64 HistoryStore::bucketOf(int t, qint64 ts) const { return t == 3 ? (ts + m_tz) / 86400 * 86400 - m_tz : ts / step[t] * step[t]; } // days at local midnight
HistoryStore::HistoryStore(const QString &dir) : m_dir(dir), m_tz(QDateTime::currentDateTime().offsetFromUtc())
{
QDir().mkpath(dir);
const qint64 now = QDateTime::currentSecsSinceEpoch();
for (int t = 0; t < 4; ++t) {
QFile f(file(t));
if (!f.open(QIODevice::ReadOnly)) continue;
const QByteArray d = f.readAll();
if (!d.startsWith(kHeader)) { f.close(), QFile::remove(f.fileName() + ".old"), f.rename(f.fileName() + ".old"); continue; }
int bad = int((d.size() - kHeader.size()) % sizeof(HPoint)); // a cut-off record would misalign everything appended after it
for (int off = kHeader.size(); off + int(sizeof(HPoint)) <= d.size(); off += sizeof(HPoint)) {
HPoint p;
std::memcpy(&p, d.constData() + off, sizeof p);
if (p.ts < now - keep[t] || p.ts > now + 86400 || (!m_t[t].isEmpty() && p.ts <= m_t[t].last().ts)) ++bad;
else m_t[t] << p;
}
if (bad) rewrite(t);
}
for (int t = 1; t < 4; ++t) { // rebuild from finer data what is not stored yet: buckets the last run left open, and the current one
const qint64 stored = m_t[t].isEmpty() ? -1 : m_t[t].last().ts;
auto feed = [&](const HPoint &p) {
const qint64 b = bucketOf(t, p.ts);
if (b <= stored) return;
if (b != m_acc[t].bucket) {
if (m_acc[t].n) append(t, m_acc[t].point());
m_acc[t] = Acc(b);
}
m_acc[t].add(p);
};
for (const HPoint &p : qAsConst(m_t[t - 1])) feed(p);
if (m_acc[t - 1].n) feed(m_acc[t - 1].point());
}
}
void HistoryStore::rewrite(int t)
{
QSaveFile f(file(t));
if (!f.open(QIODevice::WriteOnly)) return;
f.write(kHeader);
f.write(reinterpret_cast<const char *>(m_t[t].constData()), qint64(m_t[t].size()) * sizeof(HPoint));
f.commit();
}
void HistoryStore::append(int t, const HPoint &p)
{
auto &v = m_t[t];
if (!v.isEmpty() && p.ts <= v.last().ts) return;
v << p;
QFile f(file(t));
if (f.open(QIODevice::Append)) {
if (f.size() < kHeader.size()) f.resize(0), f.write(kHeader);
f.write(reinterpret_cast<const char *>(&p), sizeof p);
}
if (++m_appends[t] % 500) return; // trim expired points now and then
const auto it = std::find_if(v.begin(), v.end(), [&](const HPoint &x) { return x.ts >= p.ts - keep[t]; });
if (it != v.begin()) v.erase(v.begin(), it), rewrite(t);
}
void HistoryStore::add(qint64 ts, const float *val, bool up)
{
HPoint raw;
raw.ts = ts, raw.n = 1, raw.nUp = up;
for (int i = 0; i < H_COUNT; ++i) raw.avg[i] = raw.max[i] = up ? val[i] : NAN;
append(0, raw);
for (int t = 1; t < 4; ++t) { // every coarser tier accumulates every raw sample
const qint64 b = bucketOf(t, ts);
if (m_acc[t].bucket != b) {
if (m_acc[t].n && m_acc[t].bucket < b) append(t, m_acc[t].point());
m_acc[t] = Acc(b);
}
m_acc[t].add(raw);
}
}
QVector<HPoint> HistoryStore::range(qint64 from, qint64 to, Tier tier) const
{
const int t = int(tier);
const auto &v = m_t[t];
auto it = std::lower_bound(v.begin(), v.end(), from, [](const HPoint &p, qint64 x) { return p.ts < x; });
QVector<HPoint> out;
for (; it != v.end() && it->ts <= to; ++it) out << *it;
const Acc &a = m_acc[t];
if (t && a.n && a.bucket >= from && a.bucket <= to && (out.isEmpty() || out.last().ts < a.bucket)) out << a.point();
return out;
}
QVector<HPoint> HistoryStore::range(qint64 from, qint64 to, Tier *used) const
{
const qint64 now = QDateTime::currentSecsSinceEpoch(), maxSpan[3] = {6 * 3600, 8 * 86400, 400 * 86400};
int t = 0;
while (t < 3 && (from < now - keep[t] || to - from > maxSpan[t])) ++t;
if (used) *used = Tier(t);
return range(from, to, Tier(t));
}
void HistoryStore::removeFiles() { QDir(m_dir).removeRecursively(), *this = HistoryStore(m_dir); }
qint64 HistoryStore::firstTs() const
{
qint64 f = 0;
for (const auto &v : m_t)
if (!v.isEmpty() && (!f || v[0].ts < f)) f = v[0].ts;
return f;
}
qint64 HistoryStore::diskBytes() const
{
qint64 b = 0;
for (int t = 0; t < 4; ++t) b += QFileInfo(file(t)).size();
return b;
}
Stats stats(const QVector<HPoint> &pts, int m)
{
Stats s;
QVector<double> v;
double sum = 0, w = 0;
for (const HPoint &p : pts) {
if (!p.nUp || std::isnan(p.avg[m])) continue;
v << p.avg[m], sum += double(p.avg[m]) * p.nUp, w += p.nUp;
if (std::isnan(s.max) || p.max[m] > s.max) s.max = p.max[m];
}
if (v.isEmpty()) return s;
std::sort(v.begin(), v.end());
s.count = v.size(), s.avg = sum / w, s.min = v[0], s.p95 = v[qMin(v.size() - 1, int(v.size() * 0.95))];
return s;
}
QString fmtMetric(int m, double v)
{
if (std::isnan(v)) return "—";
switch (m) {
case H_RX: case H_TX: case H_RD: case H_WR: return Fmt::rate(v);
case H_LOAD: return QString::number(v, 'f', 2);
case H_TEMP: return Fmt::temp(v);
case H_PROCS: case H_FAILED: return QString::number(v, 'f', 0);
default: return Fmt::pct(v);
}
}
// ---- analysis -------------------------------------------------------------------
Analysis::Analysis() { std::fill(&heat[0][0][0], &heat[0][0][0] + 336, NAN); }
double regression(const QVector<HPoint> &pts, int m, double *r2)
{
double n = 0, sx = 0, sy = 0, sxx = 0, sxy = 0, syy = 0, x0 = pts.isEmpty() ? 0 : pts[0].ts;
for (const HPoint &p : pts)
if (p.nUp && !std::isnan(p.avg[m])) {
const double x = p.ts - x0, y = p.avg[m];
n++, sx += x, sy += y, sxx += x * x, sxy += x * y, syy += y * y;
}
const double den = n * sxx - sx * sx, num = n * sxy - sx * sy, vy = n * syy - sy * sy;
*r2 = n >= 3 && den > 0 && vy > 1e-9 ? num * num / (den * vy) : 0; // squared correlation
return n >= 3 && den > 0 ? num / den : 0;
}
Analysis analyze(const HistoryStore &st, const Metrics &m, const AutopilotConfig &ap, const QVector<ProcTrend> &procs,
const QVector<ServiceTrend> &svcs, bool online)
{
Analysis a;
const qint64 now = a.when = QDateTime::currentSecsSinceEpoch();
const auto &minute = st.tier(Tier::Minute), &hour = st.tier(Tier::Hour);
auto add = [&](QString key, QString sev, QString cat, QString title, QString detail, QString advice, QString action = {},
QString arg = {}, QString label = {}, bool autoOk = false) {
a.findings << Finding{key, sev, cat, title, detail, advice, action, arg, label, autoOk};
};
auto sev = [](bool crit, bool warn) { return crit ? "critical" : warn ? "warning" : "info"; };
// availability
const qint64 spans[3] = {86400, 7 * 86400, 30 * 86400};
for (int i = 0; i < 3; ++i) {
double n = 0, up = 0;
for (const HPoint &p : st.range(now - spans[i], now)) n += p.n, up += p.nUp;
a.up[i] = n ? up * 100 / n : NAN;
a.down[i] = n ? (n - up) / n * qMin(spans[i], now - st.firstTs()) : 0; // share of the monitored part of the window
}
if (a.up[0] < 99)
add("avail24", sev(a.up[0] < 95, true), "Availability", QString("Availability last 24 h is %1").arg(Fmt::pct(a.up[0], 2)),
QString("The server could not be reached for about %1 in the last day.").arg(Fmt::duration(a.down[0])),
"Check network stability, power and whether the machine rebooted (uptime).");
const auto w30 = st.range(now - spans[2], now, Tier::Hour), w7 = st.range(now - spans[1], now, Tier::Minute);
a.cpu30 = stats(w30.size() >= 24 ? w30 : w7, H_CPU), a.mem30 = stats(w30.size() >= 24 ? w30 : w7, H_MEM);
// disk forecast: regression over 7 d of hours, or 24 h of minutes, whichever fits better
double r2 = 0, r2b = 0, slope = 0;
const auto week = st.range(now - spans[1], now, Tier::Hour), day = st.range(now - 86400, now, Tier::Minute);
if (week.size() >= 48) slope = regression(week, H_DISK, &r2), a.diskBasis = "hourly averages, last 7 days";
if (day.size() >= 120) {
const double s2 = regression(day, H_DISK, &r2b);
if (week.size() < 48 || r2b > r2) slope = s2, r2 = r2b, a.diskBasis = "minute averages, last 24 hours";
}
a.diskSlopePerDay = slope * 86400;
if (a.diskSlopePerDay > 0.05 && r2 >= 0.3 && m.maxDiskPct > 0) a.diskFullDays = (100 - m.maxDiskPct) / a.diskSlopePerDay;
if (a.diskFullDays >= 0 && a.diskFullDays < 30)
add("diskfull", sev(a.diskFullDays < ap.diskForecastDays, a.diskFullDays < 14), "Disk",
QString("Disk %1 will be full in %2").arg(m.fullestMount, Fmt::duration(a.diskFullDays * 86400)),
QString("Usage %1, growing %2 points/day (trend from %3, fit R² %4).").arg(Fmt::pct(m.maxDiskPct)).arg(a.diskSlopePerDay, 0, 'f', 2).arg(a.diskBasis).arg(r2, 0, 'f', 2),
"Clean logs/caches, rotate or move data, or grow the volume.", "disk_cleanup", "", "Run cleanup", ap.diskCleanup && a.diskFullDays < ap.diskForecastDays);
if (m.maxDiskPct >= ap.diskCleanupAt)
add("diskhigh", sev(m.maxDiskPct >= 97, true), "Disk", QString("Disk %1 is %2 full").arg(m.fullestMount, Fmt::pct(m.maxDiskPct)),
QString("Above the cleanup threshold of %1.").arg(Fmt::pct(ap.diskCleanupAt, 0)), "Free space soon: services fail when the disk is full.",
"disk_cleanup", "", "Run cleanup", ap.diskCleanup);
// whole-machine memory trend over 6 h
const auto six = st.range(now - 6 * 3600, now, Tier::Minute);
if (six.size() >= 90) {
a.memSlopePerHour = regression(six, H_MEM, &a.memTrendR2) * 3600;
const double left = (100 - m.memPct) / qMax(0.01, a.memSlopePerHour);
if (a.memSlopePerHour > 1 && a.memTrendR2 > 0.8 && m.memPct > 40)
add("memtrend", sev(false, left < 12), "Memory", QString("Memory keeps growing (+%1 points/hour)").arg(a.memSlopePerHour, 0, 'f', 1),
QString("Steady growth over 6 h (R² %1). At this rate memory is exhausted in about %2.").arg(a.memTrendR2, 0, 'f', 2).arg(Fmt::duration(left * 3600)),
"Look for a leaking process (Processes tab, sort by RSS).");
}
// processes: leaks and runaways
for (const ProcTrend &p : procs) {
if (p.kernel) continue;
const QString who = QString("%1 (PID %2)").arg(p.name).arg(p.pid), pid = QString::number(p.pid);
if (p.minutesTracked >= 30 && p.rssGrowthPct >= 25 && p.rssGrowth >= 100e6 && p.rssMonotonic >= 0.8)
add("leak:" + pid, sev(m.memPct >= ap.leakMemPressure, true), "Process", "Possible memory leak: " + who,
QString("RSS grew %1 (+%2) in %3 min and rose in %4% of the minutes; now %5.").arg(Fmt::bytes(p.rssGrowth), Fmt::pct(p.rssGrowthPct, 0))
.arg(p.minutesTracked).arg(qRound(p.rssMonotonic * 100)).arg(Fmt::bytes(p.rssNow)),
"Restart the program/service at a quiet time and report the leak upstream.", "kill_pid", pid, "Terminate",
ap.leakMode == "terminate" && m.memPct >= ap.leakMemPressure);
if (p.highCpuMinutes >= ap.runawayMinutes) {
const bool term = ap.runawayMode == "terminate";
add("runaway:" + pid, "warning", "Process", "Runaway process: " + who,
QString("Above %1 CPU for %2 min (now %3, user %4).").arg(Fmt::pct(ap.runawayCpu, 0)).arg(qRound(p.highCpuMinutes)).arg(Fmt::pct(p.cpuNow), p.user),
"Lower its priority (renice) or stop it if it is stuck.", term ? "kill_pid" : "renice", pid, term ? "Terminate" : "Renice to 19", ap.runawayMode != "none");
}
}
// services: failures and flapping
for (const ServiceTrend &s : svcs) {
const bool flap = s.failsLastHour >= 3 || s.autoRestartsLastHour >= ap.maxRestartsPerHour;
if (s.failedNow)
add("svc:" + s.unit, sev(flap, true), "Service", QString(flap ? "Service %1 keeps failing" : "Service %1 has failed").arg(s.unit),
s.preexisting ? "It was already failed when monitoring started, so the autopilot leaves it alone (it may be failed on purpose)."
: QString("Failed %1× in the last hour; autopilot restarted it %2×.").arg(s.failsLastHour).arg(s.autoRestartsLastHour),
flap ? "Automatic restarts were stopped. Read the logs (Services tab → Logs) and fix the cause." : "Restart it and check the logs.",
"restart_service", s.unit, "Restart", ap.restartFailed && !s.preexisting && s.autoRestartsLastHour < ap.maxRestartsPerHour);
else if (s.failsLastHour >= 3)
add("flap:" + s.unit, "warning", "Service", QString("Service %1 is unstable").arg(s.unit),
QString("It failed %1 times within the last hour.").arg(s.failsLastHour), "Inspect its logs and resource limits.");
}
// overload and swap thrashing
const auto last15 = st.range(now - 900, now, Tier::Minute);
const double load15 = stats(last15, H_LOAD).avg, io15 = stats(last15, H_IOWAIT).avg, cpu15 = stats(last15, H_CPU).avg, busy15 = stats(last15, H_DISKIO).avg;
if (online && load15 / m.cpuCount > 1.5)
add("load", sev(load15 / m.cpuCount > 3, true), "CPU", QString("CPU is overloaded (load %1 on %2 cores)").arg(load15, 0, 'f', 1).arg(m.cpuCount),
QString("15-minute average load is %1× the number of cores; tasks are waiting for CPU.").arg(load15 / m.cpuCount, 0, 'f', 1),
"Find the busiest processes, spread work over time, or add CPU.");
if (online && m.swapPct > 50 && (P::posixCpu ? io15 > 20 : m.memPct > 90 && busy15 > 50)) // no I/O wait counter on Windows: full memory + busy disks
add("thrash", "critical", "Memory", "Swap thrashing", P::posixCpu ? QString("Swap %1 used and CPU waits on I/O %2 of the time.").arg(Fmt::pct(m.swapPct), Fmt::pct(io15))
: QString("Swap %1 used, memory %2 full and disks %3 busy.").arg(Fmt::pct(m.swapPct), Fmt::pct(m.memPct), Fmt::pct(busy15)),
"Stop memory-hungry processes or add RAM.");
// anomalies: last 10 min vs same weekday+hour over 8 weeks (fallback: last 24 h)
const auto raw = st.range(now - 600, now, Tier::Raw);
const QDateTime lt = QDateTime::fromSecsSinceEpoch(now);
if (online && raw.size() >= 10)
for (auto [hm, floor, down] : {std::tuple{H_CPU, 5.0, false}, {H_MEM, 3.0, false}, {H_LOAD, 0.25 * qMax(1, m.cpuCount), false},
{H_IOWAIT, 3.0, false}, {H_RX, 256e3, true}, {H_TX, 256e3, true}}) {
if (hm == H_IOWAIT && !P::posixCpu) continue;
const double cur = stats(raw, hm).avg;
QVector<double> v;
for (const HPoint &p : hour) {
const QDateTime t = QDateTime::fromSecsSinceEpoch(p.ts);
if (p.nUp && !std::isnan(p.avg[hm]) && now - p.ts < 56 * 86400 && now - p.ts > 3600 && t.date().dayOfWeek() == lt.date().dayOfWeek() && t.time().hour() == lt.time().hour())
v << p.avg[hm];
}
QString basis = "same weekday & hour, last 8 weeks";
if (v.size() < 3) {
v.clear(), basis = "last 24 hours";
for (const HPoint &p : minute)
if (p.nUp && !std::isnan(p.avg[hm]) && now - p.ts <= 86400 && now - p.ts > 900) v << p.avg[hm];
if (v.size() < 360) continue;
}
double mean = 0, var = 0;
for (double x : v) mean += x / v.size();
for (double x : v) var += (x - mean) * (x - mean) / v.size();
const double sd = std::sqrt(var), z = (cur - mean) / qMax(sd, floor);
a.anomalies << Anomaly{hNames[hm], basis, hm, cur, mean, sd, z};
const bool hi = z >= ap.anomalyZ, lo = down && mean > 1e6 && cur < mean * 0.1;
if (ap.anomalyAlerts && (hi || lo))
add(QString("anomaly:") + hKeys[hm], sev(false, z >= ap.anomalyZ * 2), "Anomaly", QString(hi ? "Unusually high %1" : "Unusually low %1").arg(QString(hNames[hm]).toLower()),
QString("Last 10 min %1, usually %2 ± %3 (%4); %5σ.").arg(fmtMetric(hm, cur), fmtMetric(hm, mean), fmtMetric(hm, sd), basis).arg(z, 0, 'f', 1),
hi ? "Check what changed: deploys, cron jobs, traffic, attacks." : "Traffic dropped sharply - check the service is still serving.");
}
// weekly heatmaps from 4 weeks of hours
double sum[2][7][24] = {};
for (const HPoint &p : hour) {
if (now - p.ts > 28 * 86400 || !p.nUp || std::isnan(p.avg[H_CPU])) continue;
const QDateTime t = QDateTime::fromSecsSinceEpoch(p.ts);
const int d = t.date().dayOfWeek() - 1, h = t.time().hour(), n = ++a.heatN[d][h];
sum[0][d][h] += p.avg[H_CPU], sum[1][d][h] += std::isnan(p.avg[H_MEM]) ? 0 : p.avg[H_MEM];
a.heat[0][d][h] = sum[0][d][h] / n, a.heat[1][d][h] = sum[1][d][h] / n;
}
// capacity advice
for (auto [s, name, lo, hi, loTxt, hiTxt] : {std::tuple{a.cpu30, "CPU", 15.0, 80.0, "is mostly idle", "is often saturated - add cores or move work away"},
{a.mem30, "Memory", 30.0, 85.0, "is under-used", "is tight - add RAM or reduce caches/limits"}})
if (s.count >= 60)
a.capacity << QString("%1 %2 (p95 %3).").arg(name, s.p95 < lo ? loTxt : s.p95 > hi ? hiTxt : "headroom is healthy", Fmt::pct(s.p95));
if (a.diskFullDays >= 0) a.capacity << QString("Disk grows %1 points/day - full in about %2.").arg(a.diskSlopePerDay, 0, 'f', 2).arg(Fmt::duration(a.diskFullDays * 86400));
else if (!a.diskBasis.isEmpty()) a.capacity << "Disk usage is stable.";
if (a.capacity.isEmpty()) a.capacity << "Collecting history - capacity advice appears after about an hour of data.";
// health score
double score = 100, fp = 0;
auto pen = [&](bool when, double p, const QString &why) {
if (when && p > 0.5) score -= p, a.healthReasons << QString("−%1 %2").arg(qRound(p)).arg(why);
};
const double cpu = std::isnan(cpu15) ? m.cpuUsage : cpu15;
for (const Finding &f : a.findings) fp += f.category == "Availability" ? 0 : f.severity == "critical" ? 15 : f.severity == "warning" ? 7 : 2;
pen(!online, 60, "server unreachable");
pen(cpu > 70, qMin(24.0, (cpu - 70) * 0.8), "CPU busy (" + Fmt::pct(cpu) + ")");
pen(m.memPct > 80, qMin(30.0, (m.memPct - 80) * 1.5), "memory high (" + Fmt::pct(m.memPct) + ")");
pen(m.maxDiskPct > 80, qMin(40.0, (m.maxDiskPct - 80) * 2), "disk high (" + Fmt::pct(m.maxDiskPct) + ")");
pen(m.swapPct > 50, 10, "heavy swap use");
pen(m.maxTemp > 80, qMin(20.0, (m.maxTemp - 80) * 2), "hot (" + Fmt::temp(m.maxTemp) + ")");
pen(a.up[0] < 100, qMin(30.0, (100 - a.up[0]) * 5), "downtime in last 24 h");
pen(true, qMin(50.0, fp), QString("%1 finding(s)").arg(a.findings.size()));
a.health = qBound(0, qRound(score), 100);
a.grade = QString("FDCBA").at(a.health >= 90 ? 4 : a.health >= 75 ? 3 : a.health >= 60 ? 2 : a.health >= 40 ? 1 : 0);
auto rank = [](const QString &s) { return s == "critical" ? 0 : s == "warning" ? 1 : 2; };
std::stable_sort(a.findings.begin(), a.findings.end(), [&](const Finding &x, const Finding &y) { return rank(x.severity) < rank(y.severity); });
return a;
}