Skip to content

Crawlee—A web scraping and browser automation library for Node.js to build reliable crawlers. In JavaScript and TypeScript. Extract data for AI, LLMs, RAG, or GPTs. Download HTML, PDF, JPG, PNG, and other files from websites. Works with Puppeteer, Playwright, Cheerio, JSDOM, and raw HTTP. Both headful and headless mode. With proxy rotation.

More efficient implementation of getMemoryInfo() function

Jan Curn7692636a7f6d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 376eefb9a..ab77ff181 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,6 +1,7 @@
xxx
===================
- PuppeteerCrawler's default page load timeout changed from 30 to 60 seconds.
+- More efficient implementation of `getMemoryInfo` function
0.5.51 / 2018-08-09
===================
diff --git a/package.json b/package.json
index ebd2186be..c04c2dc45 100644
--- a/package.json
+++ b/package.json
@@ -52,9 +52,8 @@
"fs-extra": "^5.0.0",
"jquery": "^3.3.1",
"mime": "^2.3.1",
- "pidusage": "=2.0.9",
"proxy-chain": "^0.1.26",
- "ps-tree": "^1.1.0",
+ "ps-tree": "git://github.com/apifytech/ps-tree.git#master",
"request-promise": "^4.2.2",
"underscore": "^1.9.0",
"ws": "^5.1.0",
diff --git a/src/utils.js b/src/utils.js
index b82512887..8155e7a01 100644
--- a/src/utils.js
+++ b/src/utils.js
@@ -5,7 +5,6 @@ import fs from 'fs';
import fsExtra from 'fs-extra';
import ApifyClient from 'apify-client';
import psTree from 'ps-tree';
-import pidusage from 'pidusage';
import requestPromise from 'request-promise';
import _ from 'underscore';
import XRegExp from 'xregexp';
@@ -13,7 +12,8 @@ import { delayPromise, getRandomInt } from 'apify-shared/utilities';
import { checkParamOrThrow } from 'apify-client/build/utils';
import { ENV_VARS, USER_AGENT_LIST } from './constants';
-export const PID_USAGE_NOT_FOUND_ERROR = 'No maching pid found';
+/* globals process */
+
/**
* Default regular expression to match URLs in a string that may be plain text, JSON, CSV or other. It supports common URL characters
@@ -158,25 +158,31 @@ export const sum = arr => arr.reduce((total, c) => total + c, 0);
export const avg = arr => sum(arr) / arr.length;
/**
- * Returns memory statistics of the container, which is an object with the following properties:
+ * Returns memory statistics of the process and the system, which is an object with the following properties:
*
* ```javascript
* {
- * // Total memory available to the actor
+ * // Total memory available in the system or container
* totalBytes: Number,
*  
- * // Amount of free memory
+ * // Amount of free memory in the system or container
* freeBytes: Number,
*  
* // Amount of memory used (= totalBytes - freeBytes)
* usedBytes: Number,
- * // Amount of memory used by main NodeJS process
+ * // Amount of memory used the current Node.js process
* mainProcessBytes: Number,
- * // Amount of memory used by child processes of main NodeJS process
+ * // Amount of memory used by child processes of the current Node.js process
* childProcessesBytes: Number,
* }
* ```
*
+ * If the process runs inside of Docker, the `getMemoryInfo` gets container memory limits,
+ * otherwise it gets system memory limits.
+ *
+ * Beware that the function is quite inefficient because it spawns a new process.
+ * Therefore you shouldn't call it too often, like more than once per second.
+ *
* @returns {Promise} Returns a promise.
*
* @memberof module:Apify
@@ -184,68 +190,49 @@ export const avg = arr => sum(arr) / arr.length;
* @instance
* @function
*/
-export const getMemoryInfo = () => {
- // module.exports must be here so that we can mock it.
- const isDockerPromise = module.exports.isDocker();
-
- const childProcessesUsagePromise = psTreePromised(process.pid)
- .then((childProcesses) => {
- const pids = _.pluck(childProcesses, 'PID');
-
- const promises = pids.map((pid) => {
- return pidusage(pid)
- .then(info => info.memory)
- .catch((err) => {
- if (err.message === PID_USAGE_NOT_FOUND_ERROR) return 0;
-
- throw err;
- });
- });
-
- return Promise.all(promises).then(infos => sum(infos));
- });
+export const getMemoryInfo = async () => {
+ const [isDockerVar, childProcesses] = await Promise.all([
+ // module.exports must be here so that we can mock it.
+ module.exports.isDocker(),
+ psTreePromised(process.pid),
+ ]);
+
+ const childProcessesBytes = _.reduce(childProcesses, (memo, rec) => {
+ // Skip the 'ps' or 'wmic' command that used to query the processes
+ if (rec.COMM === 'ps' || rec.COMM === 'WMIC.exe') return memo;
+ return memo + parseInt(rec.RSS, 10);
+ }, 0);
+
+ let totalBytes;
+ let freeBytes;
+ let usedBytes;
+
+ if (!isDockerVar) {
+ totalBytes = os.totalmem();
+ freeBytes = os.freemem();
+ usedBytes = totalBytes - freeBytes;
+ } else {
+ // When running inside Docker container, use container memory limits
+ // This must be promisified here so that we can mock it.
+ const readPromised = Promise.promisify(fs.readFile);
+
+ const [totalBytesStr, usedBytesStr] = await Promise.all([
+ readPromised('/sys/fs/cgroup/memory/memory.limit_in_bytes'),
+ readPromised('/sys/fs/cgroup/memory/memory.usage_in_bytes'),
+ ]);
+
+ totalBytes = parseInt(totalBytesStr, 10);
+ usedBytes = parseInt(usedBytesStr, 10);
+ freeBytes = totalBytes - usedBytes;
+ }
- return Promise
- .all([
- isDockerPromise,
- childProcessesUsagePromise,
- ])
- .then(([isDockerVar, childProcessesBytes]) => {
- if (!isDockerVar) {
- const freeBytes = os.freemem();
- const totalBytes = os.totalmem();
- const usedBytes = totalBytes - freeBytes;
-
- return Promise.resolve({
- totalBytes,
- freeBytes,
- usedBytes,
- mainProcessBytes: usedBytes - childProcessesBytes,
- childProcessesBytes,
- });
- }
-
- // This must be promisified here so that we can Mock it.
- const readPromised = Promise.promisify(fs.readFile);
-
- return Promise
- .all([
- readPromised('/sys/fs/cgroup/memory/memory.limit_in_bytes'),
- readPromised('/sys/fs/cgroup/memory/memory.usage_in_bytes'),
- ])
- .then(([totalBytesStr, usedBytesStr]) => {
- const totalBytes = parseInt(totalBytesStr, 10);
- const usedBytes = parseInt(usedBytesStr, 10);
-
- return {
- totalBytes,
- freeBytes: totalBytes - usedBytes,
- usedBytes,
- mainProcessBytes: usedBytes - childProcessesBytes,
- childProcessesBytes,
- };
- });
- });
+ return {
+ totalBytes,
+ freeBytes,
+ usedBytes,
+ mainProcessBytes: usedBytes - childProcessesBytes,
+ childProcessesBytes,
+ };
};
/**
diff --git a/test/utils.js b/test/utils.js
index 31d2e4630..71dbf6aa9 100644
--- a/test/utils.js
+++ b/test/utils.js
@@ -4,7 +4,6 @@ import sinon from 'sinon';
import fs from 'fs';
import path from 'path';
import os from 'os';
-import pidusage from 'pidusage';
import Promise from 'bluebird';
import requestPromise from 'request-promise';
import * as utils from '../build/utils';
@@ -294,15 +293,6 @@ describe('utils.isAtHome()', () => {
});
});
-describe('pidusage NPM package', () => {
- it('throws correct error message when process not found', () => {
- const NONEXISTING_PID = 9999;
- const promise = pidusage(NONEXISTING_PID);
-
- return expect(promise).to.be.rejectedWith(utils.PID_USAGE_NOT_FOUND_ERROR);
- });
-});
-
describe('utils.sum()', () => {
it('works', () => {
expect(utils.sum([1, 2, 3, 1.2])).to.be.eql(7.2);