Skip to content

Commit

Permalink
fix(webserver): os.freemem() isn't what it appears to be
Browse files Browse the repository at this point in the history
  • Loading branch information
Hypfer committed May 29, 2021
1 parent fd908f6 commit 80743f4
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
6 changes: 4 additions & 2 deletions backend/lib/Valetudo.js
Original file line number Diff line number Diff line change
Expand Up @@ -110,9 +110,11 @@ class Valetudo {
* With node v15, we could use process.memoryUsage.rss() which doesn't do that,
* but we don't have that version available yet
*
* Therefore, we'll only act when the overall memory usage gets somewhat critical
* Unfortunately, os.freemem() doesn't return the actual free memory including buffers, caches etc.
* Therefore, we're using a rather small value here, since the value reported will be much lower
* than the actual available memory
*/
if (os.freemem() <= 52*1024*1024) {
if (os.freemem() <= os.totalmem()*0.1) {
const rss = process.memoryUsage().rss;

if (rss > overLimit) {
Expand Down
20 changes: 19 additions & 1 deletion backend/lib/webserver/SystemRouter.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const express = require("express");
const fs = require("fs");
const os = require("os");

class SystemRouter {
Expand All @@ -20,7 +21,7 @@ class SystemRouter {
arch: os.arch(),
mem: {
total: os.totalmem(),
free: os.freemem(),
free: this.getFreeMemory(),
valetudo_current: process.memoryUsage()?.rss,
valetudo_max: process.resourceUsage()?.maxRSS * 1024
},
Expand All @@ -45,6 +46,23 @@ class SystemRouter {
});
}

/**
* @private
*/
getFreeMemory() {
let free;

try {
const meminfo = fs.readFileSync("/proc/meminfo").toString();
free = /MemAvailable:\s*(?<mem_available>\d+) kB/.exec(meminfo)?.groups?.mem_available;
free = parseInt(free) * 1024;
} catch (e) {
//intentional
}

return free ?? os.freemem();
}

getRouter() {
return this.router;
}
Expand Down

0 comments on commit 80743f4

Please sign in to comment.