File size: 20,772 Bytes
bad179a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 | #include "Session.h"
#include <QCoreApplication>
#include <QDir>
#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
#include <QSaveFile>
#include <QStandardPaths>
#include <QTextStream>
#include <utility>
// ---- Link ---------------------------------------------------------------------------------
Link::Link(const ServerConfig &c, QObject *parent) : QObject(parent), m_c(c) {}
Link::~Link()
{
for (QProcess *p : findChildren<QProcess *>()) {
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<int, QProcess::ExitStatus>::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<int, QProcess::ExitStatus>::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<double> &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<int>{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<QString, double> 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<int, ProcTrack> 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<QString, SvcTrack> 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<ProcTrend> 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<ServiceTrend> 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<QString> 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<QString> 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();
}
|