Files
wekan/server/lib/ramMonitor.js
T
Lauri Ojansivu b6a3d98736 Admin Panel / Problems: Memory Usage and Disk usage reports.
The RAM and Disk usage pages were designs that no code carried out. Both
monitors now run beside the CPU one and, like it, record only the start and
the end of a sustained high-usage period:

- Memory: RAM from /proc/meminfo's MemAvailable - os.freemem() is MemFree,
  which counts the page cache as used and shows a healthy server as full -
  and swap, which alone also starts a period. Without /proc/meminfo it uses
  what Node reports. Settings WEKAN_RAM_* and WEKAN_SWAP_HIGH_PERCENT.
- Disk: each filesystem WeKan writes to - the files root, its temp directory
  for uploads and the snap's data directory - measured once per device, with
  an episode of its own. WEKAN_DISK_WATCH_PATHS replaces the paths.
- Each report has a live line above its rows and a URL
  (/admin/problems/ram, /admin/problems/disk). The menu and titles use the
  existing memory-usage and sandstorm-disk-usage keys, which every language
  translates, and the Summary names the cpu, ram and disk streams.

Observe and report only, as designed. The three monitors share one event
recorder (server/lib/resourceLog.js) and one intEnv (models/lib/intEnv.js),
which three files had each defined. The pure halves are tested without
Meteor, and resourceMonitorsWiring checks the wiring and that no copy of
either shared piece returns.

Thanks to xet7 !
2026-10-17 01:14:16 +03:00

102 lines
4.2 KiB
JavaScript

// ============================================================================
// WeKan RAM-usage monitor (Admin Panel → Problems → RAM usage).
// docs/Features/Admin-Panel/Problems/RAM-usage.md
// ----------------------------------------------------------------------------
// Samples system-wide memory and swap on an interval and records only the
// START and END of each sustained high-usage period to the 'ram' event stream,
// with WeKan's own memory and what it was doing. Observe-and-report only:
// nothing is slowed down or freed. Best-effort and never throws; without
// /proc/meminfo (not Linux) it uses what Node reports and has no swap.
// ============================================================================
import { Meteor } from 'meteor/meteor';
import os from 'os';
import fs from 'fs';
const { intEnv } = require('/models/lib/intEnv');
const { parseMeminfo, memoryUsage, HighRamTracker } = require('/models/lib/ramHighTracker');
const ENABLED = String(process.env.WEKAN_RAM_MONITOR || 'true').toLowerCase() !== 'false';
const INTERVAL_MS = Math.max(1000, intEnv('WEKAN_RAM_SAMPLE_INTERVAL_MS', 5000));
const HIGH_PCT = intEnv('WEKAN_RAM_HIGH_PERCENT', 90);
const LOW_PCT = intEnv('WEKAN_RAM_LOW_PERCENT', 80);
const SWAP_HIGH_PCT = intEnv('WEKAN_SWAP_HIGH_PERCENT', 25);
const ENTER_SAMPLES = Math.max(1, intEnv('WEKAN_RAM_HIGH_SAMPLES', 3));
const EXIT_SAMPLES = Math.max(1, intEnv('WEKAN_RAM_LOW_SAMPLES', 3));
const tracker = new HighRamTracker({
highPct: HIGH_PCT, lowPct: LOW_PCT, swapHighPct: SWAP_HIGH_PCT,
enterSamples: ENTER_SAMPLES, exitSamples: EXIT_SAMPLES,
});
let last = null;
function readMeminfo() {
try {
return parseMeminfo(fs.readFileSync('/proc/meminfo', 'utf8'));
} catch (e) {
return {};
}
}
export function sampleMemory() {
return memoryUsage({ totalmem: os.totalmem(), freemem: os.freemem(), meminfo: readMeminfo() });
}
const gb = bytes => (bytes / (1024 ** 3)).toFixed(1);
function describe(sample) {
const parts = [`RAM ${gb(sample.ramUsed)}/${gb(sample.ramTotal)} GB (${sample.ramPct}%)`];
parts.push(sample.swapPct == null
? 'no swap'
: `swap ${gb(sample.swapUsed)}/${gb(sample.swapTotal)} GB (${sample.swapPct}%)`);
parts.push(`WeKan RSS ${gb(process.memoryUsage().rss)} GB`);
try {
const { currentActivityLabel } = require('/server/lib/cpuMonitor');
const activity = currentActivityLabel();
if (activity) parts.push(`WeKan: ${activity}`);
} catch (e) { /* the CPU monitor is optional */ }
return parts.join(', ');
}
// For Admin Panel → Problems → RAM usage: the latest sample, and whether a
// high period is open. Reads module state; with the monitor off it samples now.
export function getCurrentMemory() {
const sample = ENABLED && last ? last : sampleMemory();
return { ...sample, high: tracker.isHigh(), highPercent: HIGH_PCT, swapHighPercent: SWAP_HIGH_PCT, monitored: ENABLED };
}
if (Meteor.isServer && ENABLED) {
Meteor.startup(() => {
const { record } = require('/server/lib/ramLog');
Meteor.setInterval(() => {
try {
const sample = sampleMemory();
if (sample.ramPct == null) return;
last = sample;
const now = Date.now();
const res = tracker.update(sample, now);
if (res.event === 'start') {
record({
action: 'detected',
severity: sample.ramPct >= 95 || (sample.swapPct != null && sample.swapPct >= SWAP_HIGH_PCT) ? 'high' : 'medium',
detail: `high RAM usage started (>= ${HIGH_PCT}%): ${describe(sample)}`,
});
} else if (res.event === 'end') {
const secs = Math.round((res.durationMs || 0) / 1000);
const peakSwap = res.peakSwap == null ? '' : `, peak swap ${res.peakSwap}%`;
record({
action: 'remediated',
severity: 'info',
at: new Date(now),
detail: `high RAM usage ended after ${secs}s (peak RAM ${res.peakRam}%${peakSwap}, back under ${LOW_PCT}%): ${describe(sample)}`,
});
}
} catch (e) {
if (process.env.DEBUG === 'true') console.warn('ramMonitor sample failed:', e && e.message);
}
}, INTERVAL_MS);
});
}
export default { getCurrentMemory, sampleMemory };