#include "Session.h" #include #include #include #include #include #include #include #include #include // ---- Link --------------------------------------------------------------------------------- Link::Link(const ServerConfig &c, QObject *parent) : QObject(parent), m_c(c) {} Link::~Link() { for (QProcess *p : findChildren()) { p->disconnect(this); if (p->state() != QProcess::NotRunning) p->kill(), p->waitForFinished(500); } } QProcess *Link::spawn(const QStringList &shell) { auto *p = new QProcess(this); QStringList a; if (m_c.transport == Transport::Local) { p->setProgram(shell[0]), p->setArguments(shell.mid(1)); } else { for (const char *o : {"ConnectTimeout=10", "ServerAliveInterval=10", "ServerAliveCountMax=3", "StrictHostKeyChecking=accept-new", "LogLevel=ERROR"}) a << "-o" << o; auto env = QProcessEnvironment::systemEnvironment(); if (m_c.password.isEmpty()) a << "-o" << "BatchMode=yes"; else { // our own executable answers ssh's password prompt (see main.cpp) a << "-o" << "NumberOfPasswordPrompts=1"; env.insert("SSH_ASKPASS", QDir::toNativeSeparators(QCoreApplication::applicationFilePath())); env.insert("SSH_ASKPASS_REQUIRE", "force"); env.insert("SERVERMONITOR_ASKPASS", m_c.password); if (!env.contains("DISPLAY")) env.insert("DISPLAY", ":0"); } p->setProcessEnvironment(env); if (!m_c.keyFile.isEmpty()) a << "-i" << (m_c.keyFile.startsWith("~/") ? QDir::homePath() + m_c.keyFile.mid(1) : m_c.keyFile); if (m_c.port != 22) a << "-p" << QString::number(m_c.port); p->setProgram("ssh"), p->setArguments(a << "-T" << (m_c.user.isEmpty() ? m_c.host : m_c.user + "@" + m_c.host) << shell.join(' ')); } return p; } // Started only after the signals are connected: on Windows a failed start is reported inside start(). static void feed(QProcess *p, const QByteArray &input) { p->start(); if (p->state() != QProcess::NotRunning) p->write(input), p->closeWriteChannel(); } void Link::start() { QProcess *p = spawn(P::shell(m_c.interval)); connect(p, &QProcess::readyReadStandardOutput, this, [this, p] { m_buf += p->readAllStandardOutput(); for (int end; (end = m_buf.indexOf("@@SNAP_END")) >= 0;) { const int begin = m_buf.lastIndexOf("@@SNAP_BEGIN", end); if (begin >= 0) emit snapshot(m_buf.mid(begin, end - begin)); m_buf.remove(0, end + 10); } if (m_buf.size() > 8 << 20) m_buf.clear(); }); connect(p, &QProcess::readyReadStandardError, this, [this, p] { m_err = (m_err + p->readAllStandardError()).right(4096); }); connect(p, QOverload::of(&QProcess::finished), this, [this](int code) { const QStringList l = QString(m_err).split('\n', Qt::SkipEmptyParts); emit disconnected(l.isEmpty() ? QString("connection closed (exit code %1)").arg(code) : l.last()); }); connect(p, &QProcess::errorOccurred, this, [this, p](QProcess::ProcessError e) { if (e == QProcess::FailedToStart) emit disconnected("cannot start " + p->program() + ": " + p->errorString()); }); feed(p, P::collector(m_c.interval)); } int Link::exec(const QByteArray &input, int timeoutMs) { const int id = m_next++; QProcess *p = spawn(P::shell()); p->setProcessChannelMode(QProcess::MergedChannels); QTimer::singleShot(timeoutMs, p, [p] { p->kill(); }); connect(p, QOverload::of(&QProcess::finished), this, [this, p, id](int code, QProcess::ExitStatus st) { emit execFinished(id, st == QProcess::CrashExit ? -1 : code, p->readAll() + (st == QProcess::CrashExit ? "\n[killed or timed out]" : "")); p->deleteLater(); }); connect(p, &QProcess::errorOccurred, this, [this, p, id](QProcess::ProcessError e) { if (e == QProcess::FailedToStart) emit execFinished(id, -1, p->errorString()), p->deleteLater(); }, Qt::QueuedConnection); // queued: the caller has to learn the id first feed(p, input); return id; } // ---- live history ----------------------------------------------------------------------- QString statusName(Status s) { return QStringList{"Disabled", "Connecting", "Online", "Offline"}.value(int(s)); } void Live::push(const Metrics &m) { const int cap = 1800, n = t.size() + 1; auto add = [&](QVector &v, double x) { if (v.size() < n - 1) v.insert(0, n - 1 - v.size(), 0.0); // align series that appeared later v << x; if (v.size() > cap) v.remove(0, v.size() - cap); }; t << m.timestamp; if (t.size() > cap) t.remove(0, t.size() - cap); const double vals[N] = {m.cpuUsage, m.cpuUser, m.cpuSystem + m.cpuIrq, m.cpuIowait, m.cpuSteal, m.memPct, m.memTotal > 0 ? (m.cached + m.buffers) * 100 / m.memTotal : 0, m.swapPct, m.netRxBps, m.netTxBps, m.diskReadBps, m.diskWriteBps, m.load1}; for (int i = 0; i < N; ++i) add(s[i], vals[i]); for (const NetIf &i : m.nets) add(ifRx[i.name], i.rxBps), add(ifTx[i.name], i.txBps); } // ---- session ---------------------------------------------------------------------------- ServerSession::ServerSession(const ServerConfig &c, QObject *parent) : QObject(parent), m_cfg(c), m_store(ServerManager::configDir() + "/history/" + c.id) { m_retry.setSingleShot(true), m_watchdog.setSingleShot(true); connect(&m_retry, &QTimer::timeout, this, &ServerSession::start); connect(&m_watchdog, &QTimer::timeout, this, [this] { onLost("no data received (timeout)"); }); connect(&m_analysisTimer, &QTimer::timeout, this, &ServerSession::analyzeNow); connect(&m_offlineTick, &QTimer::timeout, this, [this] { // downtime -> availability: one sample per interval, like uptime if (m_status == Status::Offline || (m_status == Status::Connecting && m_retries)) record(false); }); m_analysisTimer.start(60000), m_offlineTick.start(c.interval * 1000); QTimer::singleShot(3000, this, &ServerSession::analyzeNow); } ServerSession::~ServerSession() { stop(); } void ServerSession::setConfig(const ServerConfig &c) { const bool reconnect = c.transport != m_cfg.transport || c.host != m_cfg.host || c.port != m_cfg.port || c.user != m_cfg.user || c.keyFile != m_cfg.keyFile || c.password != m_cfg.password || c.interval != m_cfg.interval || c.enabled != m_cfg.enabled; m_cfg = c, m_offlineTick.setInterval(c.interval * 1000); if (reconnect) m_live = Live(), m_m = Metrics(), m_procs.clear(), m_svcs.clear(), c.enabled ? start() : stop(); // may be another machine now emit updated(); } void ServerSession::drop(const QString &why) { if (m_link) m_link->disconnect(this), m_link->deleteLater(); m_link = nullptr; for (const Done &d : std::exchange(m_pending, {})) d(-1, why); } void ServerSession::start() { drop("connection restarted"); m_retry.stop(); if (!m_cfg.enabled) return setStatus(Status::Disabled); m_engine.reset(), m_m.valid = false; // online() only again with a fresh sample m_link = new Link(m_cfg, this); connect(m_link, &Link::snapshot, this, &ServerSession::onFrame); connect(m_link, &Link::disconnected, this, &ServerSession::onLost); connect(m_link, &Link::execFinished, this, [this](int id, int code, const QString &out) { if (Done d = m_pending.take(id)) d(code, out); }); setStatus(Status::Connecting), m_watchdog.start(25000), m_link->start(); } void ServerSession::stop() { m_retry.stop(), m_watchdog.stop(), drop("connection stopped"); setStatus(m_cfg.enabled ? Status::Offline : Status::Disabled); } void ServerSession::setStatus(Status s, const QString &err) { if (!err.isEmpty() || s == Status::Online) m_err = err; if (s != m_status) m_status = s, emit updated(); } void ServerSession::onFrame(const QByteArray &raw) { const qint64 now = QDateTime::currentMSecsSinceEpoch(); m_watchdog.start(qMax(15, m_cfg.interval * 5 + 10) * 1000); Metrics m = m_engine.process(raw, now); if (m.uptime <= 0) return; if (m_status != Status::Online) { m_retries = 0; if (std::exchange(m_offlineAlerted, false)) raise("resolved", "Server is back online"); setStatus(Status::Online); } if (!m.valid || m_paused) return; // first sample has no rates yet if (m.uptime < m_m.uptime) m_procs.clear(); // rebooted: PIDs start again, old trends would be blamed on new processes const bool first = !m_m.valid; // first sample of this connection: analyze at once, the last analysis saw "unreachable" m_m = m, m_live.push(m), record(true), track(now), evaluateRules(); if (first) analyzeNow(); emit updated(); } void ServerSession::onLost(const QString &why) { m_watchdog.stop(), drop("connection lost: " + why); const bool was = m_status == Status::Online; setStatus(Status::Offline, why); if ((was || m_retries == 1) && !m_offlineAlerted) raise("critical", "Server is unreachable: " + why), m_offlineAlerted = true; if (m_cfg.enabled) m_retry.start(QVector{3, 5, 10, 20, 30, 60}[qMin(m_retries++, 5)] * 1000); // back-off } void ServerSession::exec(const QString &cmd, bool privileged, Done done, int timeoutMs) { if (!m_link || m_status != Status::Online) { if (done) QTimer::singleShot(0, this, [done] { done(-1, "server is not connected"); }); return; } const int id = m_link->exec(P::wrap(cmd, privileged && m_cfg.useSudo), timeoutMs); if (done) m_pending[id] = done; } double ServerSession::metricValue(const QString &k) const { const Metrics &m = m_m; const QHash v = {{"cpu", m.cpuUsage}, {"iowait", m.cpuIowait}, {"load", m.load1 * 100 / qMax(1, m.cpuCount)}, {"mem", m.memPct}, {"swap", m.swapPct}, {"disk", m.maxDiskPct}, {"diskio", m.maxDiskUtil}, {"temp", m.maxTemp}, {"rx", m.netRxBps / 1e6}, {"tx", m.netTxBps / 1e6}, {"failed", double(m.servicesFailed)}, {"procs", double(m.procs.size())}, {"gpu", m.gpuMax(false)}, {"gputemp", m.gpuMax(true)}}; return v.value(k); } QStringList ServerSession::activeAlerts() const { QStringList out; if (m_status == Status::Offline) out << "Unreachable: " + m_err; for (const Rule &r : m_cfg.rules) if (m_rules.value(r.id).active) out << r.conditionText(); return out; } void ServerSession::raise(const QString &sev, const QString &msg) { emit alertRaised({QDateTime::currentDateTime(), m_cfg.name, sev, msg}); } void ServerSession::record(bool up) { const Metrics &m = m_m; const float v[H_COUNT] = {float(m.cpuUsage), float(m.cpuIowait), float(m.load1), float(m.memPct), m.swapTotal > 0 ? float(m.swapPct) : NAN, m.mounts.isEmpty() ? NAN : float(m.maxDiskPct), float(m.maxDiskUtil), float(m.netRxBps), float(m.netTxBps), float(m.diskReadBps), float(m.diskWriteBps), m.temps.isEmpty() ? NAN : float(m.maxTemp), float(m.procs.size()), m.gpus.isEmpty() ? NAN : float(m.gpuMax(false)), float(m.servicesFailed)}; m_store.add(QDateTime::currentSecsSinceEpoch(), v, up); } // per-process CPU streaks + RSS per minute; service failure transitions void ServerSession::track(qint64 now) { QHash procs; for (const ProcInfo &p : qAsConst(m_m.procs)) { ProcTrack t = m_procs.value(p.pid); if (t.name != p.name) t = ProcTrack{p.name}; // new or pid reused t.kernel = P::isProtected(p.pid, p.ppid, p.rss, p.name); t.highSince = p.cpu < m_cfg.autopilot.runawayCpu ? 0 : t.highSince ? t.highSince : now; if (now - t.lastMinute >= 60000) t.lastMinute = now, t.rss << p.rss; if (t.rss.size() > 60) t.rss.removeFirst(); procs[p.pid] = t; } m_procs = procs; QHash svcs; for (const ServiceInfo &s : qAsConst(m_m.services)) { SvcTrack &t = svcs[s.unit] = m_svcs.value(s.unit); const bool failed = s.active == "failed"; if (t.last.isEmpty()) t.preexisting = failed; // failed before monitoring started: leave it alone else if (failed && t.last != "failed") t.fails << now, t.preexisting = false; else if (!failed) t.preexisting = false; t.last = s.active; for (auto *v : {&t.fails, &t.restarts}) while (!v->isEmpty() && now - v->first() > 3600000) v->removeFirst(); } if (!svcs.isEmpty()) m_svcs = svcs; // forgets removed services; a sample without a service list changes nothing } void ServerSession::evaluateRules() { const qint64 now = QDateTime::currentMSecsSinceEpoch(); for (const Rule &r : qAsConst(m_cfg.rules)) { RuleState &st = m_rules[r.id]; if (!r.enabled || ((r.metric == "gpu" || r.metric == "gputemp") && m_m.gpus.isEmpty()) || (r.metric == "temp" && m_m.temps.isEmpty())) { st = {}; continue; } const double v = metricValue(r.metric); const QString now1 = QString::number(v, 'f', 1); if (r.op == "<" ? v >= r.value : v <= r.value) { if (st.active) raise("resolved", QString("Recovered: %1 (now %2)").arg(r.conditionText(), now1)); st = {}; continue; } if (!st.since) st.since = now; if (now - st.since < r.duration * 1000LL) continue; if (st.active && (r.action == "notify" || now - st.lastFire < r.cooldown * 1000LL)) continue; const QString unit = defLabel(ruleMetrics(), r.metric, true); if (!st.active) raise(r.severity, QString("%1 (now %2%3)").arg(r.conditionText(), now1, unit.isEmpty() ? "" : " " + unit)); st.active = true, st.lastFire = now; if (r.action == "notify") continue; QString action = r.action, arg = r.arg; if (action.startsWith("kill_top")) { // heaviest user process, never a protected one const ProcInfo *best = nullptr; for (const ProcInfo &p : m_m.procs) if (!P::isProtected(p.pid, p.ppid, p.rss, p.name) && (!best || (action == "kill_top_mem" ? p.rss > best->rss : p.cpu > best->cpu))) best = &p; if (!best) continue; action = "kill_pid", arg = QString::number(best->pid); } run(action, arg, QString("Automation \"%1\": %2").arg(r.conditionText(), r.actionText())); } } void ServerSession::run(const QString &action, const QString &arg, const QString &what, Done done) { const QString cmd = action == "command" ? arg : action == "disk_cleanup" ? m_cfg.autopilot.diskCleanupCommand : P::command(action, arg); if (cmd.isEmpty()) return done ? done(-1, "nothing to do") : void(); exec(cmd, true, [=](int code, const QString &out) { const QString tail = out.simplified().right(300); // one line: events are lines in alerts.log raise("action", what + " -> " + (code ? QString("failed (%1)").arg(code) : "OK") + (tail.isEmpty() ? "" : " | " + tail)); if (done) done(code, out); }, 300000); } void ServerSession::runFinding(const Finding &f, bool automatic, Done done) { if (automatic && f.action == "restart_service") m_svcs[f.actionArg].restarts << QDateTime::currentMSecsSinceEpoch(); run(f.action, f.action == "disk_cleanup" ? QString() : f.actionArg, (automatic ? "Autopilot: " : "Manual fix: ") + f.actionLabel + " (" + f.title + ")", done); } void ServerSession::analyzeNow() { const qint64 now = QDateTime::currentMSecsSinceEpoch(); QVector procs; for (const ProcInfo &p : qAsConst(m_m.procs)) { const ProcTrack t = m_procs.value(p.pid); ProcTrend pt{p.pid, int(t.rss.size()), p.name, p.user, p.cpu, t.highSince ? (now - t.highSince) / 60000.0 : 0, p.rss}; pt.kernel = t.kernel; if (t.rss.size() >= 2) { int grew = 0; for (int i = 1; i < t.rss.size(); ++i) grew += t.rss[i] > t.rss[i - 1]; pt.rssGrowth = t.rss.last() - t.rss[0], pt.rssGrowthPct = t.rss[0] > 0 ? pt.rssGrowth * 100 / t.rss[0] : 0; pt.rssMonotonic = double(grew) / (t.rss.size() - 1); } if (pt.highCpuMinutes > 0 || pt.minutesTracked >= 30) procs << pt; } QVector svcs; for (auto it = m_svcs.cbegin(); it != m_svcs.cend(); ++it) if (it->last == "failed" || !it->fails.isEmpty()) svcs << ServiceTrend{it.key(), it->last == "failed", it->preexisting, int(it->fails.size()), int(it->restarts.size())}; m_an = analyze(m_store, m_m, m_cfg.autopilot, procs, svcs, online()); QSet keys; // announce each new finding once for (const Finding &f : qAsConst(m_an.findings)) if (keys << f.key, !m_reported.contains(f.key) && f.category != "Availability") raise(f.severity, "Insight: " + f.title + " - " + f.detail); m_reported = keys; const AutopilotConfig &ap = m_cfg.autopilot; // act on eligible findings, with cooldowns; a dry run says once what it would do QSet dry; if (ap.enabled && online()) for (const Finding &f : qAsConst(m_an.findings)) { const qint64 cd = f.action == "disk_cleanup" ? 6 * 3600000LL : f.action == "restart_service" ? 120000 : 900000; if (!f.autoEligible) continue; if (ap.dryRun) { if (dry << f.key, !m_dry.contains(f.key)) raise("action", "Autopilot (dry run) would: " + f.actionLabel + " - " + f.title); } else if (now - m_cooldown.value(f.key) >= cd) m_cooldown[f.key] = now, runFinding(f, true); } m_dry = dry; emit analysisUpdated(); } void ServerSession::deleteHistory() { m_store.removeFiles(), m_an = Analysis(); emit analysisUpdated(); } // ---- manager ---------------------------------------------------------------------------- QString ServerManager::configDir() { static const QString d = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation); QDir().mkpath(d); return d; } ServerSession *ServerManager::session(const QString &id) const { for (ServerSession *s : m_s) if (s->config().id == id) return s; return nullptr; } ServerSession *ServerManager::attach(const ServerConfig &c) { auto *s = new ServerSession(c, this); connect(s, &ServerSession::alertRaised, this, [this](const AlertEvent &e) { m_alerts.prepend(e); m_alerts.resize(qMin(m_alerts.size(), 2000)); QFile f(configDir() + "/alerts.log"); if (f.size() > 5 << 20) f.resize(0); if (f.open(QIODevice::Append | QIODevice::Text)) QTextStream(&f) << e.time.toString(Qt::ISODate) << '\t' << e.severity << '\t' << e.serverName << '\t' << e.message << '\n'; emit alertRaised(e); }); m_s << s; return s; } void ServerManager::load() { QFile f(configDir() + "/servers.json"); if (f.open(QIODevice::ReadOnly)) for (const auto &v : QJsonDocument::fromJson(f.readAll())["servers"].toArray()) attach(ServerConfig::fromJson(v.toObject())); else { // first start: monitor this machine ServerConfig c; c.id = ServerConfig::newId(), c.name = "This computer", c.group = "Local", c.transport = Transport::Local; attach(c); save(); } for (ServerSession *s : qAsConst(m_s)) s->start(); emit listChanged(); } void ServerManager::save() const { QJsonArray a; for (const ServerSession *s : m_s) a << s->config().toJson(); QSaveFile f(configDir() + "/servers.json"); if (f.open(QIODevice::WriteOnly)) f.write(QJsonDocument(QJsonObject{{"version", 1}, {"servers", a}}).toJson()), f.commit(); QFile::setPermissions(f.fileName(), QFileDevice::ReadOwner | QFileDevice::WriteOwner); } ServerSession *ServerManager::add(const ServerConfig &c) { ServerSession *s = attach(c); save(), s->start(); emit listChanged(); return s; } void ServerManager::update(const ServerConfig &c) { if (ServerSession *s = session(c.id)) s->setConfig(c), save(), emit listChanged(); } void ServerManager::remove(const QString &id, bool deleteHistory) { ServerSession *s = session(id); if (!s) return; m_s.removeOne(s); s->disconnect(this), s->stop(); if (deleteHistory) s->deleteHistory(), QDir(configDir() + "/history").rmdir(id); // the store keeps an empty folder s->deleteLater(); save(); emit listChanged(); } void ServerManager::move(const QString &id, int d) { const int i = m_s.indexOf(session(id)), j = qBound(0, i + d, m_s.size() - 1); if (i >= 0 && i != j) m_s.move(i, j), save(), emit listChanged(); }