1'use strict'; 2const common = require('../common'); 3const assert = require('assert'); 4const child_process = require('child_process'); 5 6// Test that workers fail with meaningful error message 7// when their initialization fails. 8 9if (common.isWindows) { 10 common.skip('ulimit does not work on Windows.'); 11} 12 13// A reasonably low fd count. An empty node process 14// creates around 30 fds for its internal purposes, 15// so making it too low will crash the process early, 16// making it too high will cause too much resource use. 17const OPENFILES = 128; 18 19// Double the open files - so that some workers fail for sure. 20const WORKERCOUNT = 256; 21 22if (process.argv[2] === 'child') { 23 const { Worker } = require('worker_threads'); 24 for (let i = 0; i < WORKERCOUNT; ++i) { 25 const worker = new Worker( 26 'require(\'worker_threads\').parentPort.postMessage(2 + 2)', 27 { eval: true }); 28 worker.on('message', (result) => { 29 assert.strictEqual(result, 4); 30 }); 31 32 // We want to test that if there is an error in a constrained running 33 // environment, it will be one of `ENFILE`, `EMFILE`, 'ENOENT', or 34 // `ERR_WORKER_INIT_FAILED`. 35 const expected = ['ERR_WORKER_INIT_FAILED', 'EMFILE', 'ENFILE', 'ENOENT']; 36 37 // `common.mustCall*` cannot be used here as in some environments 38 // (i.e. single cpu) `ulimit` may not lead to such an error. 39 worker.on('error', (e) => { 40 assert.ok(expected.includes(e.code), `${e.code} not expected`); 41 }); 42 } 43 44} else { 45 // Limit the number of open files, to force workers to fail. 46 let testCmd = `ulimit -n ${OPENFILES} && `; 47 testCmd += `${process.execPath} ${__filename} child`; 48 const cp = child_process.exec(testCmd); 49 50 // Turn on the child streams for debugging purposes. 51 let stdout = ''; 52 cp.stdout.setEncoding('utf8'); 53 cp.stdout.on('data', (chunk) => { 54 stdout += chunk; 55 }); 56 let stderr = ''; 57 cp.stderr.setEncoding('utf8'); 58 cp.stderr.on('data', (chunk) => { 59 stderr += chunk; 60 }); 61 62 cp.on('exit', common.mustCall((code, signal) => { 63 console.log(`child stdout: ${stdout}\n`); 64 console.log(`child stderr: ${stderr}\n`); 65 assert.strictEqual(code, 0); 66 assert.strictEqual(signal, null); 67 })); 68} 69