Skip to content

Commit

Permalink
Improve calculation for used system memory
Browse files Browse the repository at this point in the history
The memory information reported by the supervisor currently
estimates the value of used memory as `MemTotal - MemFree`.
However, linux systems will try to cache and buffer as much
memory as possible, which will affect the output of `MemFree`
(from /proc/meminfo) and in consequence the memory usage seen
by the user on the dashboard, which will appear much greater than
it is.

The correct calculation should be `MemTotal - MemFree - Buffers - Cached`,
which the calculation performed by `htop` and the `free` commands.

Change-type: patch
Signed-off-by: Felipe Lalanne <felipe@balena.io>
Connects-to: #1471
  • Loading branch information
pipex committed Oct 12, 2020
1 parent 3bd8b86 commit b2adaa5
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/lib/system-info.ts
Expand Up @@ -54,7 +54,7 @@ export async function getStorageInfo() {
export async function getMemoryInformation() {
const mem = await systeminformation.mem();
return {
used: bytesToMb(mem.used),
used: bytesToMb(mem.used - mem.cached - mem.buffers),
total: bytesToMb(mem.total),
};
}
Expand Down
38 changes: 38 additions & 0 deletions test/35-system-info.spec.ts
@@ -0,0 +1,38 @@
import { SinonStub, stub } from 'sinon';
import * as systeminformation from 'systeminformation';

import { getMemoryInformation } from '../src/lib/system-info';
import { expect } from './lib/chai-config';

function kbToMb(kilobytes: number) {
return Math.floor(kilobytes / 1024);
}

describe('System information', function () {
it('Returns the correct memory values', async () => {
// Stub the output of the systeminformation module
stub(systeminformation, 'mem').resolves({
total: 763472 * 1024,
free: 143896 * 1024,
used: (763472 - 143896) * 1024,
cached: 368360 * 1024,
buffers: 16724 * 1024,
slab: 86736 * 1024,
buffcache: (368360 + 16724 + 86736) * 1024,
available: 558376 * 1024,
active: (763472 - 558376) * 1024,
swaptotal: 190864 * 1024,
swapfree: 190864 * 1024,
swapused: 0,
});

const { used, total } = await getMemoryInformation();
expect(total).to.be.equal(kbToMb(763472));

// used memory = total - free - (cached + buffers)
// this is how `htop` and `free` calculate it
expect(used).to.be.equal(kbToMb(763472 - 143896 - (368360 + 16724)));

(systeminformation.mem as SinonStub).restore();
});
});

0 comments on commit b2adaa5

Please sign in to comment.