@eggjs/cluster 3.0.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +92 -0
- package/dist/commonjs/agent_worker.d.ts +1 -0
- package/dist/commonjs/agent_worker.js +65 -0
- package/dist/commonjs/app_worker.d.ts +1 -0
- package/dist/commonjs/app_worker.js +151 -0
- package/dist/commonjs/dirname.d.ts +1 -0
- package/dist/commonjs/dirname.js +17 -0
- package/dist/commonjs/error/ClusterAgentWorkerError.d.ts +10 -0
- package/dist/commonjs/error/ClusterAgentWorkerError.js +23 -0
- package/dist/commonjs/error/ClusterWorkerExceptionError.d.ts +7 -0
- package/dist/commonjs/error/ClusterWorkerExceptionError.js +18 -0
- package/dist/commonjs/error/index.d.ts +2 -0
- package/dist/commonjs/error/index.js +19 -0
- package/dist/commonjs/index.d.ts +17 -0
- package/dist/commonjs/index.js +37 -0
- package/dist/commonjs/master.d.ts +90 -0
- package/dist/commonjs/master.js +544 -0
- package/dist/commonjs/package.json +3 -0
- package/dist/commonjs/utils/messenger.d.ts +87 -0
- package/dist/commonjs/utils/messenger.js +183 -0
- package/dist/commonjs/utils/mode/base/agent.d.ts +38 -0
- package/dist/commonjs/utils/mode/base/agent.js +68 -0
- package/dist/commonjs/utils/mode/base/app.d.ts +48 -0
- package/dist/commonjs/utils/mode/base/app.js +81 -0
- package/dist/commonjs/utils/mode/impl/process/agent.d.ts +18 -0
- package/dist/commonjs/utils/mode/impl/process/agent.js +107 -0
- package/dist/commonjs/utils/mode/impl/process/app.d.ts +20 -0
- package/dist/commonjs/utils/mode/impl/process/app.js +134 -0
- package/dist/commonjs/utils/mode/impl/worker_threads/agent.d.ts +18 -0
- package/dist/commonjs/utils/mode/impl/worker_threads/agent.js +90 -0
- package/dist/commonjs/utils/mode/impl/worker_threads/app.d.ts +25 -0
- package/dist/commonjs/utils/mode/impl/worker_threads/app.js +156 -0
- package/dist/commonjs/utils/options.d.ts +80 -0
- package/dist/commonjs/utils/options.js +81 -0
- package/dist/commonjs/utils/terminate.d.ts +6 -0
- package/dist/commonjs/utils/terminate.js +89 -0
- package/dist/commonjs/utils/worker_manager.d.ts +25 -0
- package/dist/commonjs/utils/worker_manager.js +76 -0
- package/dist/esm/agent_worker.d.ts +1 -0
- package/dist/esm/agent_worker.js +63 -0
- package/dist/esm/app_worker.d.ts +1 -0
- package/dist/esm/app_worker.js +146 -0
- package/dist/esm/dirname.d.ts +1 -0
- package/dist/esm/dirname.js +11 -0
- package/dist/esm/error/ClusterAgentWorkerError.d.ts +10 -0
- package/dist/esm/error/ClusterAgentWorkerError.js +19 -0
- package/dist/esm/error/ClusterWorkerExceptionError.d.ts +7 -0
- package/dist/esm/error/ClusterWorkerExceptionError.js +14 -0
- package/dist/esm/error/index.d.ts +2 -0
- package/dist/esm/error/index.js +3 -0
- package/dist/esm/index.d.ts +17 -0
- package/dist/esm/index.js +19 -0
- package/dist/esm/master.d.ts +90 -0
- package/dist/esm/master.js +537 -0
- package/dist/esm/package.json +3 -0
- package/dist/esm/utils/messenger.d.ts +87 -0
- package/dist/esm/utils/messenger.js +176 -0
- package/dist/esm/utils/mode/base/agent.d.ts +38 -0
- package/dist/esm/utils/mode/base/agent.js +60 -0
- package/dist/esm/utils/mode/base/app.d.ts +48 -0
- package/dist/esm/utils/mode/base/app.js +73 -0
- package/dist/esm/utils/mode/impl/process/agent.d.ts +18 -0
- package/dist/esm/utils/mode/impl/process/agent.js +102 -0
- package/dist/esm/utils/mode/impl/process/app.d.ts +20 -0
- package/dist/esm/utils/mode/impl/process/app.js +126 -0
- package/dist/esm/utils/mode/impl/worker_threads/agent.d.ts +18 -0
- package/dist/esm/utils/mode/impl/worker_threads/agent.js +82 -0
- package/dist/esm/utils/mode/impl/worker_threads/app.d.ts +25 -0
- package/dist/esm/utils/mode/impl/worker_threads/app.js +151 -0
- package/dist/esm/utils/options.d.ts +80 -0
- package/dist/esm/utils/options.js +75 -0
- package/dist/esm/utils/terminate.d.ts +6 -0
- package/dist/esm/utils/terminate.js +86 -0
- package/dist/esm/utils/worker_manager.d.ts +25 -0
- package/dist/esm/utils/worker_manager.js +72 -0
- package/dist/package.json +4 -0
- package/package.json +94 -0
- package/src/agent_worker.ts +75 -0
- package/src/app_worker.ts +170 -0
- package/src/dirname.ts +11 -0
- package/src/error/ClusterAgentWorkerError.ts +19 -0
- package/src/error/ClusterWorkerExceptionError.ts +17 -0
- package/src/error/index.ts +2 -0
- package/src/index.ts +26 -0
- package/src/master.ts +641 -0
- package/src/utils/messenger.ts +199 -0
- package/src/utils/mode/base/agent.ts +90 -0
- package/src/utils/mode/base/app.ts +115 -0
- package/src/utils/mode/impl/process/agent.ts +118 -0
- package/src/utils/mode/impl/process/app.ts +146 -0
- package/src/utils/mode/impl/worker_threads/agent.ts +98 -0
- package/src/utils/mode/impl/worker_threads/app.ts +180 -0
- package/src/utils/options.ts +169 -0
- package/src/utils/terminate.ts +97 -0
- package/src/utils/worker_manager.ts +87 -0
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import workerThreads, { type Worker } from 'node:worker_threads';
|
|
2
|
+
import { type Options as gracefulExitOptions } from 'graceful-process';
|
|
3
|
+
import { BaseAgentUtils, BaseAgentWorker } from '../../base/agent.js';
|
|
4
|
+
import type { MessageBody } from '../../../messenger.js';
|
|
5
|
+
import { ClusterAgentWorkerError } from '../../../../error/ClusterAgentWorkerError.js';
|
|
6
|
+
|
|
7
|
+
export class AgentThreadWorker extends BaseAgentWorker<Worker> {
|
|
8
|
+
get workerId() {
|
|
9
|
+
return this.instance.threadId;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
send(message: MessageBody) {
|
|
13
|
+
this.instance.postMessage(message);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
static send(message: MessageBody) {
|
|
17
|
+
workerThreads.parentPort!.postMessage(message);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
static kill() {
|
|
21
|
+
// in worker_threads, process.exit
|
|
22
|
+
// does not stop the whole program, just the single thread
|
|
23
|
+
process.exit(1);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
static gracefulExit(options: gracefulExitOptions) {
|
|
27
|
+
const { beforeExit } = options;
|
|
28
|
+
process.on('exit', async code => {
|
|
29
|
+
if (typeof beforeExit === 'function') {
|
|
30
|
+
await beforeExit();
|
|
31
|
+
}
|
|
32
|
+
process.exit(code);
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export class AgentThreadUtils extends BaseAgentUtils {
|
|
38
|
+
#worker: Worker;
|
|
39
|
+
#id = 0;
|
|
40
|
+
instance: AgentThreadWorker;
|
|
41
|
+
|
|
42
|
+
fork() {
|
|
43
|
+
this.startTime = Date.now();
|
|
44
|
+
|
|
45
|
+
// start agent worker
|
|
46
|
+
const argv = [ JSON.stringify(this.options) ];
|
|
47
|
+
const agentPath = this.getAgentWorkerFile();
|
|
48
|
+
const worker = this.#worker = new workerThreads.Worker(agentPath, { argv });
|
|
49
|
+
|
|
50
|
+
// wrap agent worker
|
|
51
|
+
const agentWorker = this.instance = new AgentThreadWorker(worker);
|
|
52
|
+
this.emit('agent_forked', agentWorker);
|
|
53
|
+
agentWorker.status = 'starting';
|
|
54
|
+
agentWorker.id = ++this.#id;
|
|
55
|
+
this.log('[master] agent_worker#%s:%s start with worker_threads',
|
|
56
|
+
agentWorker.id, agentWorker.workerId);
|
|
57
|
+
|
|
58
|
+
worker.on('message', msg => {
|
|
59
|
+
if (typeof msg === 'string') {
|
|
60
|
+
msg = {
|
|
61
|
+
action: msg,
|
|
62
|
+
data: msg,
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
msg.from = 'agent';
|
|
66
|
+
this.messenger.send(msg);
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
worker.on('error', err => {
|
|
70
|
+
this.logger.error(new ClusterAgentWorkerError(agentWorker.id, agentWorker.workerId, agentWorker.status, err));
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
// agent exit message
|
|
74
|
+
worker.once('exit', (code: number, signal: string) => {
|
|
75
|
+
this.messenger.send({
|
|
76
|
+
action: 'agent-exit',
|
|
77
|
+
data: {
|
|
78
|
+
code,
|
|
79
|
+
signal,
|
|
80
|
+
},
|
|
81
|
+
to: 'master',
|
|
82
|
+
from: 'agent',
|
|
83
|
+
});
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
clean() {
|
|
88
|
+
this.#worker.removeAllListeners();
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async kill() {
|
|
92
|
+
if (this.#worker) {
|
|
93
|
+
this.log(`[master] kill agent worker#${this.#id} (worker_threads) by worker.terminate()`);
|
|
94
|
+
this.clean();
|
|
95
|
+
await this.#worker.terminate();
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import { setTimeout as sleep } from 'node:timers/promises';
|
|
2
|
+
import { Worker as ThreadWorker, parentPort, type WorkerOptions } from 'node:worker_threads';
|
|
3
|
+
import type { Options as gracefulExitOptions } from 'graceful-process';
|
|
4
|
+
import { BaseAppWorker, BaseAppUtils } from '../../base/app.js';
|
|
5
|
+
import type { MessageBody } from '../../../messenger.js';
|
|
6
|
+
|
|
7
|
+
export class AppThreadWorker extends BaseAppWorker<ThreadWorker> {
|
|
8
|
+
#state = 'none';
|
|
9
|
+
#id: number;
|
|
10
|
+
|
|
11
|
+
constructor(instance: ThreadWorker, id: number) {
|
|
12
|
+
super(instance);
|
|
13
|
+
this.#id = id;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
get id() {
|
|
17
|
+
return this.#id;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
get workerId() {
|
|
21
|
+
return this.instance.threadId;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
get state() {
|
|
25
|
+
return this.#state;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
set state(val) {
|
|
29
|
+
this.#state = val;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
get exitedAfterDisconnect() {
|
|
33
|
+
return true;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
get exitCode() {
|
|
37
|
+
return 0;
|
|
38
|
+
// return this.instance.exitCode;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
send(message: MessageBody) {
|
|
42
|
+
this.instance.postMessage(message);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
clean() {
|
|
46
|
+
this.instance.removeAllListeners();
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
static on(event: string, listener: (...args: any[]) => void) {
|
|
50
|
+
parentPort!.on(event, listener);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
static send(message: MessageBody) {
|
|
54
|
+
parentPort!.postMessage(message);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
static kill() {
|
|
58
|
+
process.exit(1);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
static gracefulExit(options: gracefulExitOptions) {
|
|
62
|
+
process.on('exit', async code => {
|
|
63
|
+
if (typeof options.beforeExit === 'function') {
|
|
64
|
+
await options.beforeExit();
|
|
65
|
+
}
|
|
66
|
+
process.exit(code);
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export class AppThreadUtils extends BaseAppUtils {
|
|
72
|
+
#workers: ThreadWorker[] = [];
|
|
73
|
+
|
|
74
|
+
#forkSingle(appPath: string, options: WorkerOptions, id: number) {
|
|
75
|
+
// start app worker
|
|
76
|
+
const worker = new ThreadWorker(appPath, options);
|
|
77
|
+
this.#workers.push(worker);
|
|
78
|
+
|
|
79
|
+
// wrap app worker
|
|
80
|
+
const appWorker = new AppThreadWorker(worker, id);
|
|
81
|
+
this.emit('worker_forked', appWorker);
|
|
82
|
+
appWorker.disableRefork = true;
|
|
83
|
+
worker.on('message', (msg: MessageBody) => {
|
|
84
|
+
if (typeof msg === 'string') {
|
|
85
|
+
msg = {
|
|
86
|
+
action: msg,
|
|
87
|
+
data: msg,
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
msg.from = 'app';
|
|
91
|
+
this.messenger.send(msg);
|
|
92
|
+
});
|
|
93
|
+
this.log('[master] app_worker#%s (tid:%s) start', appWorker.id, appWorker.workerId);
|
|
94
|
+
|
|
95
|
+
// send debug message, due to `brk` scene, send here instead of app_worker.js
|
|
96
|
+
let debugPort = process.debugPort;
|
|
97
|
+
if (this.options.isDebug) {
|
|
98
|
+
debugPort++;
|
|
99
|
+
this.messenger.send({
|
|
100
|
+
to: 'parent',
|
|
101
|
+
from: 'app',
|
|
102
|
+
action: 'debug',
|
|
103
|
+
data: {
|
|
104
|
+
debugPort,
|
|
105
|
+
pid: appWorker.workerId,
|
|
106
|
+
workerId: appWorker.workerId,
|
|
107
|
+
},
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// handle worker listening
|
|
112
|
+
worker.on('message', ({ action, data: address }) => {
|
|
113
|
+
if (action !== 'listening') {
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
if (!address) {
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
appWorker.state = 'listening';
|
|
122
|
+
this.messenger.send({
|
|
123
|
+
action: 'app-start',
|
|
124
|
+
data: {
|
|
125
|
+
workerId: appWorker.workerId,
|
|
126
|
+
address,
|
|
127
|
+
},
|
|
128
|
+
to: 'master',
|
|
129
|
+
from: 'app',
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
// handle worker exit
|
|
135
|
+
worker.on('exit', async code => {
|
|
136
|
+
appWorker.state = 'dead';
|
|
137
|
+
this.messenger.send({
|
|
138
|
+
action: 'app-exit',
|
|
139
|
+
data: {
|
|
140
|
+
workerId: appWorker.workerId,
|
|
141
|
+
code,
|
|
142
|
+
},
|
|
143
|
+
to: 'master',
|
|
144
|
+
from: 'app',
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
// refork app worker
|
|
148
|
+
await sleep(1000);
|
|
149
|
+
this.#forkSingle(appPath, options, id);
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
fork() {
|
|
154
|
+
this.startTime = Date.now();
|
|
155
|
+
this.startSuccessCount = 0;
|
|
156
|
+
|
|
157
|
+
const ports = this.options.ports ?? [];
|
|
158
|
+
if (!ports.length) {
|
|
159
|
+
ports.push(this.options.port!);
|
|
160
|
+
}
|
|
161
|
+
this.options.workers = ports.length;
|
|
162
|
+
let i = 0;
|
|
163
|
+
do {
|
|
164
|
+
const options = Object.assign({}, this.options, { port: ports[i] });
|
|
165
|
+
const argv = [ JSON.stringify(options) ];
|
|
166
|
+
this.#forkSingle(this.getAppWorkerFile(), { argv }, ++i);
|
|
167
|
+
} while (i < ports.length);
|
|
168
|
+
|
|
169
|
+
return this;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
async kill() {
|
|
173
|
+
for (const worker of this.#workers) {
|
|
174
|
+
const id = Reflect.get(worker, 'id');
|
|
175
|
+
this.log(`[master] kill app worker#${id} (worker_threads) by worker.terminate()`);
|
|
176
|
+
worker.removeAllListeners();
|
|
177
|
+
worker.terminate();
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
}
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import os from 'node:os';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import assert from 'node:assert';
|
|
5
|
+
import { SecureContextOptions } from 'node:tls';
|
|
6
|
+
import { getFrameworkPath, importModule } from '@eggjs/utils';
|
|
7
|
+
|
|
8
|
+
export interface ClusterHTTPSSecureOptions {
|
|
9
|
+
key: SecureContextOptions['key'];
|
|
10
|
+
cert: SecureContextOptions['cert'];
|
|
11
|
+
ca?: SecureContextOptions['ca'];
|
|
12
|
+
passphrase?: SecureContextOptions['passphrase'];
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export type ClusterStartMode = 'process' | 'worker_threads';
|
|
16
|
+
|
|
17
|
+
/** Cluster start options */
|
|
18
|
+
export interface ClusterOptions {
|
|
19
|
+
/**
|
|
20
|
+
* specify framework that can be absolute path or npm package
|
|
21
|
+
*/
|
|
22
|
+
framework?: string;
|
|
23
|
+
/**
|
|
24
|
+
* @deprecated please use framework instead
|
|
25
|
+
*/
|
|
26
|
+
customEgg?: string;
|
|
27
|
+
/** directory of application, default to `process.cwd()` */
|
|
28
|
+
baseDir?: string;
|
|
29
|
+
/**
|
|
30
|
+
* numbers of app workers, default to `os.cpus().length`
|
|
31
|
+
*/
|
|
32
|
+
workers?: number | string;
|
|
33
|
+
/**
|
|
34
|
+
* listening port, default to `7001`(http) or `8443`(https)
|
|
35
|
+
*/
|
|
36
|
+
port?: number | string | null;
|
|
37
|
+
/**
|
|
38
|
+
* listening a debug port on http protocol
|
|
39
|
+
*/
|
|
40
|
+
debugPort?: number;
|
|
41
|
+
/**
|
|
42
|
+
* https options, { key, cert, ca }, full path
|
|
43
|
+
*/
|
|
44
|
+
https?: ClusterHTTPSSecureOptions | boolean;
|
|
45
|
+
/**
|
|
46
|
+
* @deprecated please use `options.https.key` instead
|
|
47
|
+
*/
|
|
48
|
+
key?: ClusterHTTPSSecureOptions['key'];
|
|
49
|
+
/**
|
|
50
|
+
* @deprecated please use `options.https.cert` instead
|
|
51
|
+
*/
|
|
52
|
+
cert?: ClusterHTTPSSecureOptions['cert'];
|
|
53
|
+
/**
|
|
54
|
+
* will inject into worker/agent process
|
|
55
|
+
*/
|
|
56
|
+
require?: string | string[];
|
|
57
|
+
/**
|
|
58
|
+
* will save master pid to this file
|
|
59
|
+
*/
|
|
60
|
+
pidFile?: string;
|
|
61
|
+
/**
|
|
62
|
+
* custom env, default is `process.env.EGG_SERVER_ENV`
|
|
63
|
+
*/
|
|
64
|
+
env?: string;
|
|
65
|
+
/**
|
|
66
|
+
* default is `'process'`, use `'worker_threads'` to start the app & agent worker by worker_threads
|
|
67
|
+
*/
|
|
68
|
+
startMode?: ClusterStartMode;
|
|
69
|
+
/**
|
|
70
|
+
* startup port of each app worker, such as: `[7001, 7002, 7003]`, only effects when the startMode is `'worker_threads'`
|
|
71
|
+
*/
|
|
72
|
+
ports?: number[];
|
|
73
|
+
/**
|
|
74
|
+
* sticky mode server
|
|
75
|
+
*/
|
|
76
|
+
sticky?: boolean;
|
|
77
|
+
/** customized plugins, for unittest */
|
|
78
|
+
plugins?: object;
|
|
79
|
+
isDebug?: boolean;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export interface ParsedClusterOptions extends ClusterOptions {
|
|
83
|
+
port?: number;
|
|
84
|
+
baseDir: string;
|
|
85
|
+
workers: number;
|
|
86
|
+
framework: string;
|
|
87
|
+
startMode: ClusterStartMode;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export async function parseOptions(options?: ClusterOptions) {
|
|
91
|
+
options = {
|
|
92
|
+
baseDir: process.cwd(),
|
|
93
|
+
port: options?.https ? 8443 : undefined,
|
|
94
|
+
startMode: 'process',
|
|
95
|
+
// ports: [],
|
|
96
|
+
env: process.env.EGG_SERVER_ENV,
|
|
97
|
+
...options,
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
const pkgPath = path.join(options.baseDir!, 'package.json');
|
|
101
|
+
assert(fs.existsSync(pkgPath), `${pkgPath} should exist`);
|
|
102
|
+
|
|
103
|
+
options.framework = getFrameworkPath({
|
|
104
|
+
baseDir: options.baseDir!,
|
|
105
|
+
// compatible customEgg only when call startCluster directly without framework
|
|
106
|
+
framework: options.framework ?? options.customEgg,
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
const egg = await importModule(options.framework);
|
|
110
|
+
assert(egg.Application, `should define Application in ${options.framework}`);
|
|
111
|
+
assert(egg.Agent, `should define Agent in ${options.framework}`);
|
|
112
|
+
|
|
113
|
+
if (options.https === true) {
|
|
114
|
+
// Keep compatible options.key, options.cert
|
|
115
|
+
console.warn('[@eggjs/cluster:deprecated] [master] Please use `https: { key, cert, ca }` instead of `https: true`');
|
|
116
|
+
options.https = {
|
|
117
|
+
key: options.key,
|
|
118
|
+
cert: options.cert,
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// https
|
|
123
|
+
if (options.https) {
|
|
124
|
+
assert(options.https.key, 'options.https.key should exists');
|
|
125
|
+
if (typeof options.https.key === 'string') {
|
|
126
|
+
assert(fs.existsSync(options.https.key), 'options.https.key file should exists');
|
|
127
|
+
}
|
|
128
|
+
assert(options.https.cert, 'options.https.cert should exists');
|
|
129
|
+
if (typeof options.https.cert === 'string') {
|
|
130
|
+
assert(fs.existsSync(options.https.cert), 'options.https.cert file should exists');
|
|
131
|
+
}
|
|
132
|
+
if (typeof options.https.ca === 'string') {
|
|
133
|
+
assert(fs.existsSync(options.https.ca), 'options.https.ca file should exists');
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
if (options.port && typeof options.port === 'string') {
|
|
138
|
+
options.port = parseInt(options.port);
|
|
139
|
+
}
|
|
140
|
+
if (options.port === null) {
|
|
141
|
+
options.port = undefined;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
if (options.workers && typeof options.workers === 'string') {
|
|
145
|
+
options.workers = parseInt(options.workers);
|
|
146
|
+
}
|
|
147
|
+
if (!options.workers) {
|
|
148
|
+
options.workers = os.cpus().length;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
if (options.require) {
|
|
152
|
+
if (typeof options.require === 'string') {
|
|
153
|
+
options.require = [ options.require ];
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// don't print deprecated message in production env.
|
|
158
|
+
// it will print to stderr.
|
|
159
|
+
if (process.env.NODE_ENV === 'production') {
|
|
160
|
+
process.env.NO_DEPRECATION = '*';
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const isDebug = process.execArgv.some(argv => argv.includes('--debug') || argv.includes('--inspect'));
|
|
164
|
+
if (isDebug) {
|
|
165
|
+
options.isDebug = isDebug;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
return options as ParsedClusterOptions;
|
|
169
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { debuglog } from 'node:util';
|
|
2
|
+
import { setTimeout as sleep } from 'node:timers/promises';
|
|
3
|
+
import { once } from 'node:events';
|
|
4
|
+
import { ChildProcess } from 'node:child_process';
|
|
5
|
+
import { pstree } from '@fengmk2/ps-tree';
|
|
6
|
+
|
|
7
|
+
const debug = debuglog('@eggjs/cluster/utils/terminate');
|
|
8
|
+
|
|
9
|
+
interface SubProcess extends ChildProcess {
|
|
10
|
+
process?: ChildProcess;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export async function terminate(subProcess: SubProcess, timeout: number) {
|
|
14
|
+
const pid = subProcess.process?.pid ?? subProcess.pid;
|
|
15
|
+
const childPids = await getChildPids(pid!);
|
|
16
|
+
await Promise.all([
|
|
17
|
+
killProcess(subProcess, timeout),
|
|
18
|
+
killChildren(childPids, timeout),
|
|
19
|
+
]);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// kill process, if SIGTERM not work, try SIGKILL
|
|
23
|
+
async function killProcess(subProcess: SubProcess, timeout: number) {
|
|
24
|
+
// https://github.com/nodejs/node/pull/34312
|
|
25
|
+
(subProcess.process ?? subProcess).kill('SIGTERM');
|
|
26
|
+
await Promise.race([
|
|
27
|
+
once(subProcess, 'exit'),
|
|
28
|
+
sleep(timeout),
|
|
29
|
+
]);
|
|
30
|
+
if (subProcess.killed) {
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
// SIGKILL: http://man7.org/linux/man-pages/man7/signal.7.html
|
|
34
|
+
// worker: https://github.com/nodejs/node/blob/master/lib/internal/cluster/worker.js#L22
|
|
35
|
+
// subProcess.kill is wrapped to subProcess.destroy, it will wait to disconnected.
|
|
36
|
+
(subProcess.process ?? subProcess).kill('SIGKILL');
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// kill all children processes, if SIGTERM not work, try SIGKILL
|
|
40
|
+
async function killChildren(childrenPids: number[], timeout: number) {
|
|
41
|
+
if (childrenPids.length === 0) {
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
kill(childrenPids, 'SIGTERM');
|
|
45
|
+
|
|
46
|
+
const start = Date.now();
|
|
47
|
+
// if timeout is 1000, it will check twice.
|
|
48
|
+
const checkInterval = 400;
|
|
49
|
+
let unterminated: number[] = [];
|
|
50
|
+
|
|
51
|
+
while (Date.now() - start < timeout - checkInterval) {
|
|
52
|
+
await sleep(checkInterval);
|
|
53
|
+
unterminated = getUnterminatedProcesses(childrenPids);
|
|
54
|
+
if (unterminated.length === 0) {
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
kill(unterminated, 'SIGKILL');
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async function getChildPids(pid: number) {
|
|
62
|
+
let childrenPids: number[] = [];
|
|
63
|
+
try {
|
|
64
|
+
const children = await pstree(pid);
|
|
65
|
+
childrenPids = children!.map(c => parseInt(c.PID));
|
|
66
|
+
} catch (err) {
|
|
67
|
+
// if get children error, just ignore it
|
|
68
|
+
debug('pstree %s error: %s, ignore it', pid, err);
|
|
69
|
+
}
|
|
70
|
+
return childrenPids;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function kill(pids: number[], signal: string) {
|
|
74
|
+
for (const pid of pids) {
|
|
75
|
+
try {
|
|
76
|
+
process.kill(pid, signal);
|
|
77
|
+
} catch (err) {
|
|
78
|
+
// ignore
|
|
79
|
+
debug('kill %s error: %s, signal: %s, ignore it', pid, err, signal);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function getUnterminatedProcesses(pids: number[]) {
|
|
85
|
+
return pids.filter(pid => {
|
|
86
|
+
try {
|
|
87
|
+
// success means it's still alive
|
|
88
|
+
process.kill(pid, 0);
|
|
89
|
+
return true;
|
|
90
|
+
} catch (err) {
|
|
91
|
+
// error means it's dead
|
|
92
|
+
debug('kill %s error: %s, it still alive', pid, err);
|
|
93
|
+
return false;
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { EventEmitter } from 'node:events';
|
|
2
|
+
import { BaseAgentWorker } from './mode/base/agent.js';
|
|
3
|
+
import { BaseAppWorker } from './mode/base/app.js';
|
|
4
|
+
|
|
5
|
+
// worker manager to record agent and worker forked by egg-cluster
|
|
6
|
+
// can do some check stuff here to monitor the healthy
|
|
7
|
+
export class WorkerManager extends EventEmitter {
|
|
8
|
+
agent: BaseAgentWorker | null;
|
|
9
|
+
workers = new Map<number, BaseAppWorker>();
|
|
10
|
+
exception = 0;
|
|
11
|
+
timer: NodeJS.Timeout;
|
|
12
|
+
|
|
13
|
+
constructor() {
|
|
14
|
+
super();
|
|
15
|
+
this.agent = null;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
getWorkers() {
|
|
19
|
+
return Array.from(this.workers.keys());
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
setAgent(agent: BaseAgentWorker) {
|
|
23
|
+
this.agent = agent;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
getAgent() {
|
|
27
|
+
return this.agent;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
deleteAgent() {
|
|
31
|
+
this.agent = null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
setWorker(worker: BaseAppWorker) {
|
|
35
|
+
this.workers.set(worker.workerId, worker);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
getWorker(workerId: number) {
|
|
39
|
+
return this.workers.get(workerId);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
deleteWorker(workerId: number) {
|
|
43
|
+
this.workers.delete(workerId);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
listWorkerIds() {
|
|
47
|
+
return Array.from(this.workers.keys());
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
listWorkers() {
|
|
51
|
+
return Array.from(this.workers.values());
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
getListeningWorkerIds() {
|
|
55
|
+
const keys = [];
|
|
56
|
+
for (const [ id, worker ] of this.workers.entries()) {
|
|
57
|
+
if (worker.state === 'listening') {
|
|
58
|
+
keys.push(id);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return keys;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
count() {
|
|
65
|
+
return {
|
|
66
|
+
agent: this.agent?.status === 'started' ? 1 : 0,
|
|
67
|
+
worker: this.listWorkerIds().length,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// check agent and worker must both alive
|
|
72
|
+
// if exception appear 3 times, emit an exception event
|
|
73
|
+
startCheck() {
|
|
74
|
+
this.timer = setInterval(() => {
|
|
75
|
+
const count = this.count();
|
|
76
|
+
if (count.agent > 0 && count.worker > 0) {
|
|
77
|
+
this.exception = 0;
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
this.exception++;
|
|
81
|
+
if (this.exception >= 3) {
|
|
82
|
+
this.emit('exception', count);
|
|
83
|
+
clearInterval(this.timer);
|
|
84
|
+
}
|
|
85
|
+
}, 10000);
|
|
86
|
+
}
|
|
87
|
+
}
|