|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const allSettled = require('promise.allsettled'); |
| 4 | +const os = require('os'); |
| 5 | +const Runner = require('./runner'); |
| 6 | +const {EVENT_RUN_BEGIN, EVENT_RUN_END} = Runner.constants; |
| 7 | +const debug = require('debug')('mocha:parallel:buffered-runner'); |
| 8 | +const workerpool = require('workerpool'); |
| 9 | +const {deserialize} = require('./serializer'); |
| 10 | +const WORKER_PATH = require.resolve('./worker.js'); |
| 11 | +const {setInterval, clearInterval} = global; |
| 12 | +const {createMap, warn} = require('./utils'); |
| 13 | +const debugStats = pool => { |
| 14 | + const {totalWorkers, busyWorkers, idleWorkers, pendingTasks} = pool.stats(); |
| 15 | + debug( |
| 16 | + '%d/%d busy workers; %d idle; %d tasks queued', |
| 17 | + busyWorkers, |
| 18 | + totalWorkers, |
| 19 | + idleWorkers, |
| 20 | + pendingTasks |
| 21 | + ); |
| 22 | +}; |
| 23 | + |
| 24 | +/** |
| 25 | + * The interval at which we will display stats for worker processes in debug mode |
| 26 | + */ |
| 27 | +const DEBUG_STATS_INTERVAL = 5000; |
| 28 | + |
| 29 | +const ABORTED = 'ABORTED'; |
| 30 | +const IDLE = 'IDLE'; |
| 31 | +const ABORTING = 'ABORTING'; |
| 32 | +const RUNNING = 'RUNNING'; |
| 33 | +const BAILING = 'BAILING'; |
| 34 | +const BAILED = 'BAILED'; |
| 35 | +const COMPLETE = 'COMPLETE'; |
| 36 | + |
| 37 | +const states = createMap({ |
| 38 | + [IDLE]: new Set([RUNNING, ABORTING]), |
| 39 | + [RUNNING]: new Set([COMPLETE, BAILING, ABORTING]), |
| 40 | + [COMPLETE]: new Set(), |
| 41 | + [ABORTED]: new Set(), |
| 42 | + [ABORTING]: new Set([ABORTED]), |
| 43 | + [BAILING]: new Set([BAILED, ABORTING]), |
| 44 | + [BAILED]: new Set([COMPLETE, ABORTING]) |
| 45 | +}); |
| 46 | + |
| 47 | +/** |
| 48 | + * This `Runner` delegates tests runs to worker threads. Does not execute any |
| 49 | + * {@link Runnable}s by itself! |
| 50 | + */ |
| 51 | +class BufferedRunner extends Runner { |
| 52 | + constructor(...args) { |
| 53 | + super(...args); |
| 54 | + |
| 55 | + let state = IDLE; |
| 56 | + Object.defineProperty(this, '_state', { |
| 57 | + get() { |
| 58 | + return state; |
| 59 | + }, |
| 60 | + set(newState) { |
| 61 | + if (states[state].has(newState)) { |
| 62 | + state = newState; |
| 63 | + } else { |
| 64 | + throw new Error(`invalid state transition: ${state} => ${newState}`); |
| 65 | + } |
| 66 | + } |
| 67 | + }); |
| 68 | + |
| 69 | + this.once('EVENT_RUN_END', () => { |
| 70 | + this._state = COMPLETE; |
| 71 | + }); |
| 72 | + } |
| 73 | + |
| 74 | + /** |
| 75 | + * Runs Mocha tests by creating a thread pool, then delegating work to the |
| 76 | + * worker threads. |
| 77 | + * |
| 78 | + * Each worker receives one file, and as workers become available, they take a |
| 79 | + * file from the queue and run it. The worker thread execution is treated like |
| 80 | + * an RPC--it returns a `Promise` containing serialized information about the |
| 81 | + * run. The information is processed as it's received, and emitted to a |
| 82 | + * {@link Reporter}, which is likely listening for these events. |
| 83 | + * |
| 84 | + * @todo handle delayed runs? |
| 85 | + * @param {Function} callback - Called with an exit code corresponding to |
| 86 | + * number of test failures. |
| 87 | + * @param {{files: string[], options: Options}} opts - Files to run and |
| 88 | + * command-line options, respectively. |
| 89 | + */ |
| 90 | + run(callback, {files, options} = {}) { |
| 91 | + /** |
| 92 | + * Listener on `Process.SIGINT` which tries to cleanly terminate the worker pool. |
| 93 | + */ |
| 94 | + let sigIntListener; |
| 95 | + // This function should _not_ return a `Promise`; its parent (`Runner#run`) |
| 96 | + // returns this instance, so this should do the same. However, we want to make |
| 97 | + // use of `async`/`await`, so we use this IIFE. |
| 98 | + |
| 99 | + (async () => { |
| 100 | + /** |
| 101 | + * This is an interval that outputs stats about the worker pool every so often |
| 102 | + */ |
| 103 | + let debugInterval; |
| 104 | + |
| 105 | + /** |
| 106 | + * @type {WorkerPool} |
| 107 | + */ |
| 108 | + let pool; |
| 109 | + |
| 110 | + try { |
| 111 | + const cpuCount = os.cpus().length; |
| 112 | + const maxJobs = cpuCount - 1; |
| 113 | + const jobs = Math.max(1, Math.min(options.jobs || maxJobs, maxJobs)); |
| 114 | + if (maxJobs < 2) { |
| 115 | + warn( |
| 116 | + `(Mocha) not enough CPU cores available (${cpuCount}) to run multiple jobs; avoid --parallel on this machine` |
| 117 | + ); |
| 118 | + } else if (options.jobs && options.jobs > maxJobs) { |
| 119 | + warn( |
| 120 | + `(Mocha) ${options.jobs} concurrent jobs requested, but only enough cores available for ${maxJobs}` |
| 121 | + ); |
| 122 | + } |
| 123 | + debug( |
| 124 | + 'run(): starting worker pool of size %d, using node args: %s', |
| 125 | + jobs, |
| 126 | + process.execArgv.join(' ') |
| 127 | + ); |
| 128 | + pool = workerpool.pool(WORKER_PATH, { |
| 129 | + workerType: 'process', |
| 130 | + maxWorkers: jobs, |
| 131 | + forkOpts: {execArgv: process.execArgv} |
| 132 | + }); |
| 133 | + |
| 134 | + sigIntListener = async () => { |
| 135 | + if (this._state !== ABORTING) { |
| 136 | + debug('run(): caught a SIGINT'); |
| 137 | + this._state = ABORTING; |
| 138 | + |
| 139 | + try { |
| 140 | + debug('run(): shutting down %d (max) workers', jobs); |
| 141 | + await pool.terminate(true); |
| 142 | + } catch (err) { |
| 143 | + console.error( |
| 144 | + `Error while attempting to force-terminate worker pool: ${err}` |
| 145 | + ); |
| 146 | + } finally { |
| 147 | + process.nextTick(() => { |
| 148 | + debug('run(): imminent death'); |
| 149 | + this._state = ABORTED; |
| 150 | + process.kill(process.pid, 'SIGINT'); |
| 151 | + }); |
| 152 | + } |
| 153 | + } |
| 154 | + }; |
| 155 | + |
| 156 | + process.once('SIGINT', sigIntListener); |
| 157 | + |
| 158 | + // the "pool proxy" object is essentially just syntactic sugar to call a |
| 159 | + // worker's procedure as one would a regular function. |
| 160 | + const poolProxy = await pool.proxy(); |
| 161 | + |
| 162 | + debugInterval = setInterval( |
| 163 | + () => debugStats(pool), |
| 164 | + DEBUG_STATS_INTERVAL |
| 165 | + ).unref(); |
| 166 | + |
| 167 | + // this is set for uncaught exception handling in `Runner#uncaught` |
| 168 | + this.started = true; |
| 169 | + this._state = RUNNING; |
| 170 | + |
| 171 | + this.emit(EVENT_RUN_BEGIN); |
| 172 | + |
| 173 | + const results = await allSettled( |
| 174 | + files.map(async file => { |
| 175 | + debug('run(): enqueueing test file %s', file); |
| 176 | + try { |
| 177 | + const result = await poolProxy.run(file, options); |
| 178 | + if (this._state === BAILED) { |
| 179 | + // short-circuit after a graceful bail |
| 180 | + return; |
| 181 | + } |
| 182 | + const {failureCount, events} = deserialize(result); |
| 183 | + debug( |
| 184 | + 'run(): completed run of file %s; %d failures / %d events', |
| 185 | + file, |
| 186 | + failureCount, |
| 187 | + events.length |
| 188 | + ); |
| 189 | + this.failures += failureCount; // can this ever be non-numeric? |
| 190 | + /** |
| 191 | + * If we set this, then we encountered a "bail" flag, and will |
| 192 | + * terminate the pool once all events have been emitted. |
| 193 | + */ |
| 194 | + let event = events.shift(); |
| 195 | + while (event) { |
| 196 | + this.emit(event.eventName, event.data, event.error); |
| 197 | + if ( |
| 198 | + this._state !== BAILING && |
| 199 | + event.data && |
| 200 | + event.data._bail && |
| 201 | + (failureCount || event.error) |
| 202 | + ) { |
| 203 | + debug('run(): nonzero failure count & found bail flag'); |
| 204 | + // we need to let the events complete for this file, as the worker |
| 205 | + // should run any cleanup hooks |
| 206 | + this._state = BAILING; |
| 207 | + } |
| 208 | + event = events.shift(); |
| 209 | + } |
| 210 | + if (this._state === BAILING) { |
| 211 | + debug('run(): terminating pool due to "bail" flag'); |
| 212 | + this._state = BAILED; |
| 213 | + await pool.terminate(); |
| 214 | + } |
| 215 | + } catch (err) { |
| 216 | + if (this._state === BAILED || this._state === ABORTING) { |
| 217 | + debug( |
| 218 | + 'run(): worker pool terminated with intent; skipping file %s', |
| 219 | + file |
| 220 | + ); |
| 221 | + } else { |
| 222 | + // this is an uncaught exception |
| 223 | + debug('run(): encountered uncaught exception: %O', err); |
| 224 | + if (this.allowUncaught) { |
| 225 | + // still have to clean up |
| 226 | + this._state = ABORTING; |
| 227 | + await pool.terminate(true); |
| 228 | + } |
| 229 | + throw err; |
| 230 | + } |
| 231 | + } finally { |
| 232 | + debug('run(): done running file %s', file); |
| 233 | + } |
| 234 | + }) |
| 235 | + ); |
| 236 | + |
| 237 | + // note that pool may already be terminated due to --bail |
| 238 | + await pool.terminate(); |
| 239 | + |
| 240 | + results |
| 241 | + .filter(({status}) => status === 'rejected') |
| 242 | + .forEach(({reason}) => { |
| 243 | + if (this.allowUncaught) { |
| 244 | + // yep, just the first one. |
| 245 | + throw reason; |
| 246 | + } |
| 247 | + // "rejected" will correspond to uncaught exceptions. |
| 248 | + // unlike the serial runner, the parallel runner can always recover. |
| 249 | + this.uncaught(reason); |
| 250 | + }); |
| 251 | + |
| 252 | + if (this._state === ABORTING) { |
| 253 | + return; |
| 254 | + } |
| 255 | + this.emit(EVENT_RUN_END); |
| 256 | + debug('run(): completing with failure count %d', this.failures); |
| 257 | + callback(this.failures); |
| 258 | + } catch (err) { |
| 259 | + process.nextTick(() => { |
| 260 | + debug('run(): throwing uncaught exception'); |
| 261 | + throw err; |
| 262 | + }); |
| 263 | + } finally { |
| 264 | + clearInterval(debugInterval); |
| 265 | + process.removeListener('SIGINT', sigIntListener); |
| 266 | + } |
| 267 | + })(); |
| 268 | + return this; |
| 269 | + } |
| 270 | +} |
| 271 | + |
| 272 | +module.exports = BufferedRunner; |
0 commit comments