运行 Nodejs OOM 崩溃前的一个函数

Run A Function Right Before Nodejs Crashes Due to OOM

是否可以在 Node.js 应用因 OOM 而崩溃之前强制 运行 一个函数(即发送 API 调用)?

我正在尝试记录 OOM 崩溃的时间戳,但这需要能够在进程被终止之前 运行 一个函数。 PM2 当前用于管理此 Node.js 流程。

Medium: Detect heap overflow on Node.js: JavaScript heap out of memory

使用集群模块。分叉一个工人,在 exit 事件上分叉另一个工人记录:

total_heap_size: The size V8 has allocated for the heap. This can grow if used_heap_size needs more. heap_size_limit: The absolute size limit the heap cannot exceed. e.g.: max_old_space_size

然后它退出并生成一个新的 worker 并再次运行 main 函数。这可以防止内存不足时崩溃,因为它会在内存不足错误被触发之前退出并生成一个新的 worker。如果您仍然希望它崩溃,您可以删除 process.exit().

heavyHeapConsumer是一个占用内存比较大的demo函数

const cluster = require('cluster');
const v8 = require('v8');

let heavyHeapConsumer = () => {
  let arrays = [];
  setInterval(() => {
    arrays.push(new Array(1000000));
  }, 100);
};

if (cluster.isMaster) {
  cluster.fork();
  cluster.on('exit', (deadWorker, code, signal) => {
    // Restart the worker
    let worker = cluster.fork();
    
    // Note the process IDs
    let newPID = worker.process.pid;
    let oldPID = deadWorker.process.pid;
    
    // Log the event
    console.log('worker ' + oldPID + ' died.');
    console.log('worker ' + newPID + ' born.');
  });
} else { // worker
  const initialStats = v8.getHeapStatistics();
  
  const totalHeapSizeThreshold = 
    initialStats.heap_size_limit * 85 / 100;
  console.log("totalHeapSizeThreshold: " + totalHeapSizeThreshold);
  
  let detectHeapOverflow = () => {
    let stats = v8.getHeapStatistics();
    
    console.log("total_heap_size: " + (stats.total_heap_size));
    
    if ((stats.total_heap_size) > totalHeapSizeThreshold) {
      process.exit();
    }
  };
  setInterval(detectHeapOverflow, 1000);
  
  // here goes the main logic
  heavyHeapConsumer();
}