In order to stress test a project i'm building, I need to write a Node script that attempts to consume all available RAM on the machine - allowing me to test if the mechanisms I have in place to detect and terminate such runaway processes work.
I wrote this script:
let buffer = [];
const MB = (bytes) => Math.round(bytes/1024/1024) + 'MB'
const memoryUsage = () => {
const mem = process.memoryUsage();
return MB(mem.rss) + '\t' + MB(mem.heapTotal) + '\t' + MB(mem.external);
}
setInterval(()=>{
buffer.push(Buffer.alloc(1024 * 1024* 1024)); // Eat 1GB of RAM every second
console.log(buffer.length + '\t' + memoryUsage());
}, 1000);
Which attempts to allocate one GB or RAM every second.
200 seconds in, this is my console output:
196 28MB 7MB 200704MB
197 28MB 7MB 201728MB
198 28MB 7MB 202752MB
199 28MB 7MB 203776MB
200 28MB 7MB 204800MB
201 28MB 7MB 205824MB
202 28MB 7MB 206848MB
203 28MB 7MB 207872MB
204 28MB 7MB 208896MB
205 28MB 7MB 209920MB
And this is the RAM usage in htop:
My questions are:
- Where does the Virtual memory live if it isn't in the RAM or Swap? How can the script allocate 245GB of Virt memory without actually allocating anything?
- How do I make the script work, and actually allocate the RAM to bring the machine down? i.e., how can I increase the numbers in the RES column of HTOP?
- My intention is to run untrusted, arbitrary scripts written and uploaded by users - Is runaway RAM usage a realistic scenario to check for in this case?
This is running inside the official Nodejs 8 Docker container.