forked from eggjs/egg-cluster
-
Notifications
You must be signed in to change notification settings - Fork 0
/
master.js
742 lines (658 loc) · 21.7 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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
'use strict';
const os = require('os');
const util = require('util');
const path = require('path');
const fs = require('fs');
const cluster = require('cluster');
const EventEmitter = require('events');
const childprocess = require('child_process');
const cfork = require('cfork');
const ready = require('get-ready');
const GetFreePort = require('detect-port');
const ConsoleLogger = require('egg-logger').EggConsoleLogger;
const utility = require('utility');
const semver = require('semver');
const co = require('co');
const { mkdirp } = require('mz-modules');
const Manager = require('./utils/manager');
const parseOptions = require('./utils/options');
const Messenger = require('./utils/messenger');
const terminate = require('./utils/terminate');
const PROTOCOL = Symbol('Master#protocol');
const REAL_PORT = Symbol('Master#real_port');
const APP_ADDRESS = Symbol('Master#appAddress');
class Master extends EventEmitter {
/**
* @class
* @param {Object} options
* - {String} [framework] - specify framework that can be absolute path or npm package
* - {String} [baseDir] directory of application, default to `process.cwd()`
* - {Object} [plugins] - customized plugins, for unittest
* - {Number} [workers] numbers of app workers, default to `os.cpus().length`
* - {Number} [port] listening port, default to 7001(http) or 8443(https)
* - {Object} [https] https options, { key, cert, ca }, full path
* - {Array|String} [require] will inject into worker/agent process
* - {String} [pidFile] will save master pid to this file
* - {json|advanced} [serialization] Advanced serialization for IPC since Node.js v12.16.0,
* see: https://github.com/nodejs/node/blob/master/doc/changelogs/CHANGELOG_V12.md#advanced-serialization-for-ipc
*/
constructor(options) {
super();
this.options = parseOptions(options);
this.workerManager = new Manager();
this.messenger = new Messenger(this);
ready.mixin(this);
this.isProduction = isProduction();
this.agentWorkerIndex = 0;
this.closed = false;
this[REAL_PORT] = this.options.port;
this[PROTOCOL] = this.options.https ? 'https' : 'http';
// app started or not
this.isStarted = false;
this.logger = new ConsoleLogger({ level: process.env.EGG_MASTER_LOGGER_LEVEL || 'INFO' });
this.logMethod = 'info';
if (process.env.EGG_SERVER_ENV === 'local' || process.env.NODE_ENV === 'development') {
this.logMethod = 'debug';
}
// get the real framework info
const frameworkPath = this.options.framework;
const frameworkPkg = utility.readJSONSync(path.join(frameworkPath, 'package.json'));
this.log(`[master] =================== ${frameworkPkg.name} start =====================`);
this.logger.info(`[master] node version ${process.version}`);
/* istanbul ignore next */
if (process.alinode) this.logger.info(`[master] alinode version ${process.alinode}`);
this.logger.info(`[master] ${frameworkPkg.name} version ${frameworkPkg.version}`);
if (this.isProduction) {
this.logger.info('[master] start with options:%s%s',
os.EOL, JSON.stringify(this.options, null, 2));
} else {
this.log('[master] start with options: %j', this.options);
}
this.log('[master] start with env: isProduction: %s, EGG_SERVER_ENV: %s, NODE_ENV: %s',
this.isProduction, process.env.EGG_SERVER_ENV, process.env.NODE_ENV);
const startTime = Date.now();
this.ready(() => {
this.isStarted = true;
const stickyMsg = this.options.sticky ? ' with STICKY MODE!' : '';
this.logger.info('[master] %s started on %s (%sms)%s',
frameworkPkg.name, this[APP_ADDRESS], Date.now() - startTime, stickyMsg);
const action = 'egg-ready';
this.messenger.send({
action,
to: 'parent',
data: {
port: this[REAL_PORT],
address: this[APP_ADDRESS],
protocol: this[PROTOCOL],
},
});
this.messenger.send({
action,
to: 'app',
data: this.options,
});
this.messenger.send({
action,
to: 'agent',
data: this.options,
});
// start check agent and worker status
if (this.isProduction) {
this.workerManager.startCheck();
}
});
this.on('agent-exit', this.onAgentExit.bind(this));
this.on('agent-start', this.onAgentStart.bind(this));
this.on('app-exit', this.onAppExit.bind(this));
this.on('app-start', this.onAppStart.bind(this));
this.on('reload-worker', this.onReload.bind(this));
// fork app workers after agent started
this.once('agent-start', this.forkAppWorkers.bind(this));
// get the real port from options and app.config
// app worker will send after loading
this.on('realport', ({ port, protocol }) => {
if (port) this[REAL_PORT] = port;
if (protocol) this[PROTOCOL] = protocol;
});
// https://nodejs.org/api/process.html#process_signal_events
// https://en.wikipedia.org/wiki/Unix_signal
// kill(2) Ctrl-C
process.once('SIGINT', this.onSignal.bind(this, 'SIGINT'));
// kill(3) Ctrl-\
process.once('SIGQUIT', this.onSignal.bind(this, 'SIGQUIT'));
// kill(15) default
process.once('SIGTERM', this.onSignal.bind(this, 'SIGTERM'));
process.once('exit', this.onExit.bind(this));
// write pid to file if provided
if (this.options.pidFile) {
mkdirp.sync(path.dirname(this.options.pidFile));
fs.writeFileSync(this.options.pidFile, process.pid, 'utf-8');
}
this.detectPorts()
.then(() => {
this.forkAgentWorker();
});
// exit when agent or worker exception
this.workerManager.on('exception', ({
agent,
worker,
}) => {
const err = new Error(`[master] ${agent} agent and ${worker} worker(s) alive, exit to avoid unknown state`);
err.name = 'ClusterWorkerExceptionError';
err.count = {
agent,
worker,
};
this.logger.error(err);
process.exit(1);
});
}
detectPorts() {
// Detect cluster client port
return GetFreePort()
.then(port => {
this.options.clusterPort = port;
// If sticky mode, detect worker port
if (this.options.sticky) {
return GetFreePort();
}
})
.then(port => {
if (this.options.sticky) {
this.options.stickyWorkerPort = port;
}
})
.catch(/* istanbul ignore next */ err => {
this.logger.error(err);
process.exit(1);
});
}
log(...args) {
this.logger[this.logMethod](...args);
}
get agentWorker() {
return this.workerManager.agent;
}
startMasterSocketServer(cb) {
// Create the outside facing server listening on our port.
require('net').createServer({
pauseOnConnect: true,
}, connection => {
// We received a connection and need to pass it to the appropriate
// worker. Get the worker for this connection's source IP and pass
// it the connection.
/* istanbul ignore next */
if (!connection.remoteAddress) {
// This will happen when a client sends an RST(which is set to 1) right
// after the three-way handshake to the server.
// Read https://en.wikipedia.org/wiki/TCP_reset_attack for more details.
connection.destroy();
} else {
const worker = this.stickyWorker(connection.remoteAddress);
worker.send('sticky-session:connection', connection);
}
}).listen(this[REAL_PORT], cb);
}
stickyWorker(ip) {
const workerNumbers = this.options.workers;
const ws = this.workerManager.listWorkerIds();
let s = '';
for (let i = 0; i < ip.length; i++) {
if (!isNaN(ip[i])) {
s += ip[i];
}
}
s = Number(s);
const pid = ws[s % workerNumbers];
return this.workerManager.getWorker(pid);
}
forkAgentWorker() {
this.agentStartTime = Date.now();
const args = [ JSON.stringify(this.options) ];
const opt = {};
if (process.platform === 'win32') opt.windowsHide = true;
// add debug execArgv
const debugPort = process.env.EGG_AGENT_DEBUG_PORT || 5800;
if (this.options.isDebug) opt.execArgv = process.execArgv.concat([ `--${semver.gte(process.version, '8.0.0') ? 'inspect' : 'debug'}-port=${debugPort}` ]);
/* istanbul ignore next */
if (semver.gte(process.version, '12.16.0')) {
/* istanbul ignore next */
if (this.options.serialization) {
opt.serialization = this.options.serialization;
}
}
const agentWorker = childprocess.fork(this.getAgentWorkerFile(), args, opt);
agentWorker.status = 'starting';
agentWorker.id = ++this.agentWorkerIndex;
this.workerManager.setAgent(agentWorker);
this.log('[master] agent_worker#%s:%s start with clusterPort:%s',
agentWorker.id, agentWorker.pid, this.options.clusterPort);
// send debug message
if (this.options.isDebug) {
this.messenger.send({
to: 'parent',
from: 'agent',
action: 'debug',
data: {
debugPort,
pid: agentWorker.pid,
},
});
}
// forwarding agent' message to messenger
agentWorker.on('message', msg => {
if (typeof msg === 'string') {
msg = {
action: msg,
data: msg,
};
}
msg.from = 'agent';
this.messenger.send(msg);
});
agentWorker.on('error', err => {
err.name = 'AgentWorkerError';
err.id = agentWorker.id;
err.pid = agentWorker.pid;
this.logger.error(err);
});
// agent exit message
agentWorker.once('exit', (code, signal) => {
this.messenger.send({
action: 'agent-exit',
data: {
code,
signal,
},
to: 'master',
from: 'agent',
});
});
}
forkAppWorkers() {
this.appStartTime = Date.now();
this.isAllAppWorkerStarted = false;
this.startSuccessCount = 0;
const args = [ JSON.stringify(this.options) ];
this.log('[master] start appWorker with args %j', args);
cfork({
exec: this.getAppWorkerFile(),
args,
silent: false,
count: this.options.workers,
// don't refork in local env
refork: this.isProduction,
windowsHide: process.platform === 'win32',
});
let debugPort = process.debugPort;
cluster.on('fork', worker => {
worker.disableRefork = true;
this.workerManager.setWorker(worker);
worker.on('message', msg => {
if (typeof msg === 'string') {
msg = {
action: msg,
data: msg,
};
}
msg.from = 'app';
this.messenger.send(msg);
});
this.log('[master] app_worker#%s:%s start, state: %s, current workers: %j',
worker.id, worker.process.pid, worker.state, Object.keys(cluster.workers));
// send debug message, due to `brk` scence, send here instead of app_worker.js
if (this.options.isDebug) {
debugPort++;
this.messenger.send({
to: 'parent',
from: 'app',
action: 'debug',
data: {
debugPort,
pid: worker.process.pid,
},
});
}
});
cluster.on('disconnect', worker => {
this.logger.info('[master] app_worker#%s:%s disconnect, suicide: %s, state: %s, current workers: %j',
worker.id, worker.process.pid, worker.exitedAfterDisconnect, worker.state, Object.keys(cluster.workers));
});
cluster.on('exit', (worker, code, signal) => {
this.messenger.send({
action: 'app-exit',
data: {
workerPid: worker.process.pid,
code,
signal,
},
to: 'master',
from: 'app',
});
});
cluster.on('listening', (worker, address) => {
this.messenger.send({
action: 'app-start',
data: {
workerPid: worker.process.pid,
address,
},
to: 'master',
from: 'app',
});
});
}
/**
* close agent worker, App Worker will closed by cluster
*
* https://www.exratione.com/2013/05/die-child-process-die/
* make sure Agent Worker exit before master exit
*
* @param {number} timeout - kill agent timeout
* @return {Promise} -
*/
killAgentWorker(timeout) {
const agentWorker = this.agentWorker;
if (agentWorker) {
this.log('[master] kill agent worker with signal SIGTERM');
agentWorker.removeAllListeners();
}
return co(function* () {
yield terminate(agentWorker, timeout);
});
}
killAppWorkers(timeout) {
return co(function* () {
yield Object.keys(cluster.workers).map(id => {
const worker = cluster.workers[id];
worker.disableRefork = true;
return terminate(worker, timeout);
});
});
}
/**
* Agent Worker exit handler
* Will exit during startup, and refork during running.
* @param {Object} data
* - {Number} code - exit code
* - {String} signal - received signal
*/
onAgentExit(data) {
if (this.closed) return;
this.messenger.send({
action: 'egg-pids',
to: 'app',
data: [],
});
const agentWorker = this.agentWorker;
this.workerManager.deleteAgent(this.agentWorker);
const err = new Error(util.format('[master] agent_worker#%s:%s died (code: %s, signal: %s)',
agentWorker.id, agentWorker.pid, data.code, data.signal));
err.name = 'AgentWorkerDiedError';
this.logger.error(err);
// remove all listeners to avoid memory leak
agentWorker.removeAllListeners();
if (this.isStarted) {
this.log('[master] try to start a new agent_worker after 1s ...');
setTimeout(() => {
this.logger.info('[master] new agent_worker starting...');
this.forkAgentWorker();
}, 1000);
this.messenger.send({
action: 'agent-worker-died',
to: 'parent',
});
} else {
this.logger.error('[master] agent_worker#%s:%s start fail, exiting with code:1',
agentWorker.id, agentWorker.pid);
process.exit(1);
}
}
onAgentStart() {
this.agentWorker.status = 'started';
// Send egg-ready when agent is started after launched
if (this.isAllAppWorkerStarted) {
this.messenger.send({
action: 'egg-ready',
to: 'agent',
data: this.options,
});
}
this.messenger.send({
action: 'egg-pids',
to: 'app',
data: [ this.agentWorker.pid ],
});
// should send current worker pids when agent restart
if (this.isStarted) {
this.messenger.send({
action: 'egg-pids',
to: 'agent',
data: this.workerManager.getListeningWorkerIds(),
});
}
this.messenger.send({
action: 'agent-start',
to: 'app',
});
this.logger.info('[master] agent_worker#%s:%s started (%sms)',
this.agentWorker.id, this.agentWorker.pid, Date.now() - this.agentStartTime);
}
/**
* App Worker exit handler
* @param {Object} data
* - {String} workerPid - worker id
* - {Number} code - exit code
* - {String} signal - received signal
*/
onAppExit(data) {
if (this.closed) return;
const worker = this.workerManager.getWorker(data.workerPid);
if (!worker.isDevReload) {
const signal = data.signal;
const message = util.format(
'[master] app_worker#%s:%s died (code: %s, signal: %s, suicide: %s, state: %s), current workers: %j',
worker.id, worker.process.pid, worker.process.exitCode, signal,
worker.exitedAfterDisconnect, worker.state,
Object.keys(cluster.workers)
);
if (this.options.isDebug && signal === 'SIGKILL') {
// exit if died during debug
this.logger.error(message);
this.logger.error('[master] worker kill by debugger, exiting...');
setTimeout(() => this.close(), 10);
} else {
const err = new Error(message);
err.name = 'AppWorkerDiedError';
this.logger.error(err);
}
}
// remove all listeners to avoid memory leak
worker.removeAllListeners();
this.workerManager.deleteWorker(data.workerPid);
// send message to agent with alive workers
this.messenger.send({
action: 'egg-pids',
to: 'agent',
data: this.workerManager.getListeningWorkerIds(),
});
if (this.isAllAppWorkerStarted) {
// cfork will only refork at production mode
this.messenger.send({
action: 'app-worker-died',
to: 'parent',
});
} else {
// exit if died during startup
this.logger.error('[master] app_worker#%s:%s start fail, exiting with code:1',
worker.id, worker.process.pid);
process.exit(1);
}
}
/**
* after app worker
* @param {Object} data
* - {String} workerPid - worker id
* - {Object} address - server address
*/
onAppStart(data) {
const worker = this.workerManager.getWorker(data.workerPid);
const address = data.address;
// worker should listen stickyWorkerPort when sticky mode
if (this.options.sticky) {
if (String(address.port) !== String(this.options.stickyWorkerPort)) {
return;
}
// worker should listen REALPORT when not sticky mode
} else if (!isUnixSock(address) &&
(String(address.port) !== String(this[REAL_PORT]))) {
return;
}
// send message to agent with alive workers
this.messenger.send({
action: 'egg-pids',
to: 'agent',
data: this.workerManager.getListeningWorkerIds(),
});
this.startSuccessCount++;
const remain = this.isAllAppWorkerStarted ? 0 : this.options.workers - this.startSuccessCount;
this.log('[master] app_worker#%s:%s started at %s, remain %s (%sms)',
worker.id, data.workerPid, address.port, remain, Date.now() - this.appStartTime);
// Send egg-ready when app is started after launched
if (this.isAllAppWorkerStarted) {
this.messenger.send({
action: 'egg-ready',
to: 'app',
data: this.options,
});
}
// if app is started, it should enable this worker
if (this.isAllAppWorkerStarted) {
worker.disableRefork = false;
}
if (this.isAllAppWorkerStarted || this.startSuccessCount < this.options.workers) {
return;
}
this.isAllAppWorkerStarted = true;
// enable all workers when app started
for (const id in cluster.workers) {
const worker = cluster.workers[id];
worker.disableRefork = false;
}
address.protocol = this[PROTOCOL];
address.port = this.options.sticky ? this[REAL_PORT] : address.port;
this[APP_ADDRESS] = getAddress(address);
if (this.options.sticky) {
this.startMasterSocketServer(err => {
if (err) return this.ready(err);
this.ready(true);
});
} else {
this.ready(true);
}
}
/**
* master exit handler
*/
onExit(code) {
if (this.options.pidFile && fs.existsSync(this.options.pidFile)) {
try {
fs.unlinkSync(this.options.pidFile);
} catch (err) {
/* istanbul ignore next */
this.logger.error('[master] delete pidfile %s fail with %s', this.options.pidFile, err.message);
}
}
// istanbul can't cover here
// https://github.com/gotwarlost/istanbul/issues/567
const level = code === 0 ? 'info' : 'error';
this.logger[level]('[master] exit with code:%s', code);
}
onSignal(signal) {
if (this.closed) return;
this.logger.info('[master] receive signal %s, closing', signal);
this.close();
}
/**
* reload workers, for develop purpose
*/
onReload() {
this.log('[master] reload workers...');
for (const id in cluster.workers) {
const worker = cluster.workers[id];
worker.isDevReload = true;
}
require('cluster-reload')(this.options.workers);
}
close() {
this.closed = true;
const self = this;
co(function* () {
try {
yield self._doClose();
self.log('[master] close done, exiting with code:0');
process.exit(0);
} catch (e) /* istanbul ignore next */ {
this.logger.error('[master] close with error: ', e);
process.exit(1);
}
});
}
getAgentWorkerFile() {
return path.join(__dirname, 'agent_worker.js');
}
getAppWorkerFile() {
return path.join(__dirname, 'app_worker.js');
}
* _doClose() {
// kill app workers
// kill agent worker
// exit itself
const legacyTimeout = process.env.EGG_MASTER_CLOSE_TIMEOUT || 5000;
const appTimeout = process.env.EGG_APP_CLOSE_TIMEOUT || legacyTimeout;
const agentTimeout = process.env.EGG_AGENT_CLOSE_TIMEOUT || legacyTimeout;
this.logger.info('[master] send kill SIGTERM to app workers, will exit with code:0 after %sms', appTimeout);
this.logger.info('[master] wait %sms', appTimeout);
try {
yield this.killAppWorkers(appTimeout);
} catch (e) /* istanbul ignore next */ {
this.logger.error('[master] app workers exit error: ', e);
}
this.logger.info('[master] send kill SIGTERM to agent worker, will exit with code:0 after %sms', agentTimeout);
this.logger.info('[master] wait %sms', agentTimeout);
try {
yield this.killAgentWorker(agentTimeout);
} catch (e) /* istanbul ignore next */ {
this.logger.error('[master] agent worker exit error: ', e);
}
}
}
module.exports = Master;
function isProduction() {
const serverEnv = process.env.EGG_SERVER_ENV;
if (serverEnv) {
return serverEnv !== 'local' && serverEnv !== 'unittest';
}
return process.env.NODE_ENV === 'production';
}
function getAddress({
addressType,
address,
port,
protocol,
}) {
// unix sock
// https://nodejs.org/api/cluster.html#cluster_event_listening_1
if (addressType === -1) return address;
let hostname = address;
if (!hostname && process.env.HOST && process.env.HOST !== '0.0.0.0') {
hostname = process.env.HOST;
}
if (!hostname) {
hostname = '127.0.0.1';
}
return `${protocol}://${hostname}:${port}`;
}
function isUnixSock(address) {
return address.addressType === -1;
}