-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathmaster.js
489 lines (427 loc) · 13 KB
/
master.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
const os = require('os'),
cluster = require('cluster'),
ClusterProcess = require('./cluster_process'),
WorkerWrapper = require('./worker_wrapper'),
Port = require('./port'),
RestartQueue = require('./restart_queue'),
RPC = require('./rpc');
/**
* @constructor
* @class Master
* @augments ClusterProcess
*/
class Master extends ClusterProcess {
constructor() {
super();
/**
* @type {Object}
* @property {WorkerWrapper} *
* @public
* @todo make it private or public immutable
*/
this.workers = {};
/**
* Workers restart queue.
* @type {RestartQueue}
* @private
*/
this._restartQueue = new RestartQueue();
this.id = 0;
this.wid = 0;
this.pid = process.pid;
this.on('worker state', this._cleanupUnixSockets.bind(this));
this.on('worker exit', this._checkWorkersAlive.bind(this));
// @todo make it optional?
process.on('SIGINT', this._onSignalQuit.bind(this));
process.on('SIGQUIT', this._onSignalQuit.bind(this));
}
/**
* Allows same object structure as cluster.setupMaster().
* This function must be used instead of cluster.setupMaster(),
* An instance of Master will call it, when running.
* @param {Object} opts
* @see {@link https://nodejs.org/api/cluster.html#clustersetupmastersettings}
*/
setup(opts) {
cluster.setupMaster({...cluster.settings, ...opts});
}
/**
* SIGINT and SIGQUIT handler
* @private
*/
_onSignalQuit() {
this
.once('shutdown', () => process.exit(0))
.shutdown();
}
/**
* Remove not used unix socket before worker will try to listen it.
* @param {WorkerWrapper} worker
* @param {WorkerWrapperState} state
* @private
*/
_cleanupUnixSockets(worker, state) {
const port = worker.options.port;
if (this._restartQueue.has(worker) ||
state !== WorkerWrapper.STATES.LAUNCHING ||
port.family !== Port.UNIX) {
return;
}
const inUse = this.getWorkersArray().some(w =>
worker.wid !== w.wid &&
w.isRunning() &&
port.isEqualTo(w.options.port)
);
if (!inUse) {
port.unlink(err => {
if (err) {
this.emit('error', err);
}
});
}
}
/**
* Check for alive workers, if no one here, then emit "shutdown".
* @private
*/
_checkWorkersAlive() {
const workers = this.getWorkersArray(),
alive = workers.reduce(
(count, w) => w.dead ? count - 1 : count,
workers.length
);
if (alive === 0) {
this.emit('shutdown');
}
}
/**
* Repeat WorkerWrapper events on Master and add 'worker ' prefix to event names
* so for example 'online' became 'worker online'
* @private
* @param {WorkerWrapper} worker
*/
_proxyWorkerEvents(worker) {
WorkerWrapper.EVENTS
.forEach(eventName => {
const proxyEventName = 'worker ' + eventName;
worker.on(eventName, this.emit.bind(this, proxyEventName, worker));
});
}
/**
* @returns {number[]} workers ids array
*/
getWorkersIds() {
if (!this._workersIdsCache) {
this._workersIdsCache = this.getWorkersArray().map(w => w.wid);
}
return this._workersIdsCache;
}
/**
* @returns {WorkerWrapper[]} workers array
*/
getWorkersArray() {
if (!this._workersArrayCache) {
this._workersArrayCache = Object.values(this.workers);
}
return this._workersArrayCache;
}
/**
* Add worker to the pool
* @param {WorkerWrapper} worker
* @returns {Master} self
* @public
*/
add(worker) {
// invalidate Master#getWorkersIds and Master#getWorkersArray cache
this._workersIdsCache = null;
this._workersArrayCache = null;
this.workers[worker.wid] = worker;
this._proxyWorkerEvents(worker);
return this;
}
/**
* Iterate over workers in the pool.
* @param {Function} fn
* @public
* @returns {Master} self
*
* @description Shortcut for:
* master.getWorkersArray().forEach(fn);
*/
forEach(fn) {
this.getWorkersArray()
.forEach(fn);
return this;
}
/**
* Broadcast an event received by IPC from worker as 'worker <event>'.
* @param {WorkerWrapper} worker
* @param {String} event
* @param {...*} args
*/
broadcastWorkerEvent(worker, event, ...args) {
this.emit('received worker ' + event, worker, ...args);
}
/**
* Configure cluster
* @override ClusterProcess
* @private
*/
_onConfigured() {
super._onConfigured();
// register global remote command in the context of master to receive events from master
if (!this.hasRegisteredRemoteCommand(RPC.fns.master.broadcastWorkerEvent)) {
this.registerRemoteCommand(
RPC.fns.master.broadcastWorkerEvent,
this.broadcastWorkerEvent.bind(this)
);
}
const // WorkerWrapper options
forkTimeout = this.config.get('control.forkTimeout'),
stopTimeout = this.config.get('control.stopTimeout'),
exitThreshold = this.config.get('control.exitThreshold'),
allowedSequentialDeaths = this.config.get('control.allowedSequentialDeaths'),
count = this.config.get('workers', os.cpus().length),
isServerPortSet = this.config.has('server.port'),
groups = this.config.get('server.groups', 1),
portsPerGroup = this.config.get('server.portsPerGroup', 1),
masterInspectPort = this.config.get('properties.masterInspectPort'),
workersPerGroup = Math.floor(count / groups);
let port,
// workers and groups count
i = 0,
group = 0,
workersInGroup = 0;
if (isServerPortSet) {
port = new Port(this.config.get('server.port'));
}
// create pool of workers
while (count > i++) {
this.add(new WorkerWrapper(this, {
forkTimeout,
stopTimeout,
exitThreshold,
allowedSequentialDeaths,
port: isServerPortSet ? port.next(group * portsPerGroup) : 0,
masterInspectPort,
maxListeners: this.getMaxListeners(),
}));
// groups > 1, current group is full and
// last workers can form at least more one group
if (groups > 1 &&
++workersInGroup >= workersPerGroup &&
count - (group + 1) * workersPerGroup >= workersPerGroup) {
workersInGroup = 0;
group++;
}
}
}
/**
* @param {Number[]} wids Array of `WorkerWrapper#wid` values
* @param {String} event wait for
* @public
* @returns {Promise<void>}
*/
waitForWorkers(wids, event) {
const pendingWids = new Set(wids);
return new Promise(resolve => {
if (pendingWids.size === 0) {
resolve();
}
const onWorkerState = worker => {
const wid = worker.wid;
pendingWids.delete(wid);
if (pendingWids.size === 0) {
this.removeListener(event, onWorkerState);
resolve();
}
};
this.on(event, onWorkerState);
});
}
/**
* @param {String} event wait for
* @public
* @returns {Promise<void>}
*/
waitForAllWorkers(event) {
return this.waitForWorkers(
this.getWorkersIds(),
event
);
}
/**
* @event Master#running
*/
/**
* @event Master#restarted
*/
async _restart() {
// TODO maybe run this after starting waitForAllWorkers
this.forEach(worker => worker.restart());
await this.waitForAllWorkers('worker ready');
this.emit('restarted');
}
/**
* Hard workers restart: all workers will be restarted at same time.
* CAUTION: if dead worker is restarted, it will emit 'error' event.
* @public
* @returns {Master} self
* @fires Master#restarted when workers spawned and ready.
*/
restart() {
this._restart();
return this;
}
/**
* Workers will be restarted one by one using RestartQueue.
* If a worker becomes dead, it will be just removed from restart queue. However, if already dead worker is pushed
* into the queue, it will emit 'error' on restart.
* @public
* @returns {Master} self
* @fires Master#restarted when workers spawned and ready.
*/
softRestart() {
this.forEach(worker => worker.softRestart());
this._restartQueue.once('drain', this.emit.bind(this, 'restarted'));
return this;
}
/**
* Schedules one worker restart using RestartQueue.
* If a worker becomes dead, it will be just removed from restart queue. However, if already dead worker is pushed
* into the queue, it will emit 'error' on restart.
* @public
* @param {WorkerWrapper} worker
* @returns {Master} self
*/
scheduleWorkerRestart(worker) {
this._restartQueue.push(worker);
return this;
}
/**
* @override
* @see ClusterProcess
* @private
*/
_setupIPCMessagesHandler() {
this.on('worker message', this._onMessage.bind(this));
}
/**
* RPC to all workers
* @method
* @param {String} name of called command in the worker
* @param {...*} args
* @public
*/
remoteCallToAll(name, ...args) {
this.forEach(worker => {
if (worker.ready) {
worker.remoteCall(name, ...args);
} else {
worker.on('ready', () => {
worker.remoteCall(name, ...args);
});
}
});
}
/**
* Broadcast event to all workers.
* @method
* @param {String} event of called command in the worker
* @param {...*} args
* @public
*/
broadcastEventToAll(event, ...args) {
this.forEach(worker => {
if (worker.ready) {
worker.broadcastEvent(event, ...args);
}
});
}
/**
* Emit event on master and all workers in "ready" state.
* @method
* @param {String} event of called command in the worker
* @param {...*} args
* @public
*/
emitToAll(event, ...args) {
this.emit(event, ...args);
this.broadcastEventToAll(event, ...args);
}
/**
* @event Master#shutdown
*/
async _shutdown() {
const stoppedWorkers = [];
this.forEach(worker => {
if (worker.isRunning()) {
worker.stop();
stoppedWorkers.push(worker.wid);
}
});
await this.waitForWorkers(
stoppedWorkers,
'worker exit',
);
this.emit('shutdown');
}
/**
* Stop all workers and emit `Master#shutdown` event after successful shutdown of all workers.
* @fires Master#shutdown
* @returns {Master}
*/
shutdown() {
this._shutdown();
return this;
}
/**
* Do a remote call to all workers, callbacks are registered and then executed separately for each worker
* @method
* @param {String} opts.command
* @param {Function} opts.callback
* @param {Number} [opts.timeout] in milliseconds
* @param {*} [opts.data]
* @public
*/
remoteCallToAllWithCallback(opts) {
this.forEach(worker => {
if (worker.isRunning()) {
worker.remoteCallWithCallback(opts);
}
});
}
async _run() {
await this.whenInitialized();
// TODO maybe run this after starting waitForAllWorkers
this.forEach(worker => worker.run());
await this.waitForAllWorkers('worker ready');
this.emit('running');
}
/**
* Fork workers.
* Execution will be delayed until Master became configured
* (`configured` event fired).
* @method
* @returns {Master} self
* @public
* @fires Master#running then workers spawned and ready.
*
* @example
* // file: master.js
* var master = require('luster');
*
* master
* .configure({ app : 'worker' })
* .run();
*
* // there is master is still not running anyway
* // it will run immediate once configured and
* // current thread execution done
*/
run() {
this._run();
return this;
}
}
module.exports = Master;