/
cp.ts
65 lines (56 loc) 路 1.69 KB
/
cp.ts
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
import { ChildProcessEventBus } from '@midwayjs/event-bus';
import { Worker } from 'cluster';
import { ClusterOptions } from '../interface';
import { AbstractForkManager } from './base';
const cluster = require('cluster');
import { debuglog } from 'util';
import { isTypeScriptEnvironment } from '@midwayjs/core';
const debug = debuglog('midway:bootstrap');
export class ClusterManager extends AbstractForkManager<
Worker,
ClusterOptions
> {
constructor(readonly options: ClusterOptions = {}) {
super(options);
options.args = options.args || [];
options.execArgv = options.execArgv || [];
if (isTypeScriptEnvironment()) {
options.execArgv.push(...['--require', 'ts-node/register']);
}
}
createWorker() {
if (cluster['setupPrimary']) {
cluster['setupPrimary'](this.options);
} else if (cluster['setupMaster']) {
cluster['setupMaster'](this.options);
}
return cluster.fork({
MIDWAY_FORK_MODE: 'cluster',
MIDWAY_STICKY_MODE: this.options.sticky ? 'true' : 'false',
...this.options.env,
});
}
bindWorkerDisconnect(listener: (worker: Worker) => void) {
debug('Bind cluster.disconnect event');
cluster.on('disconnect', listener);
}
bindWorkerExit(listener: (worker: Worker, code, signal) => void) {
debug('Bind cluster.exit event');
cluster.on('exit', listener);
}
getWorkerId(worker: Worker) {
return String(worker.process.pid);
}
isWorkerDead(worker: Worker) {
return worker.isDead();
}
closeWorker(worker: Worker) {
worker.kill('SIGTERM');
}
createEventBus(options) {
return new ChildProcessEventBus(options) as any;
}
isPrimary(): boolean {
return !cluster.isWorker;
}
}