-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathworker-manager.ts
264 lines (244 loc) · 7.11 KB
/
worker-manager.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
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
import './instrument';
import './setup-logger'; // This should be first
import {
logger,
userInitiatedPriority,
systemInitiatedPriority,
} from '@cardstack/runtime-common';
import yargs from 'yargs';
import * as Sentry from '@sentry/node';
import flattenDeep from 'lodash/flattenDeep';
import { spawn } from 'child_process';
import pluralize from 'pluralize';
import Koa from 'koa';
import Router from '@koa/router';
import { ecsMetadata, fullRequestURL, livenessCheck } from './middleware';
import { Server } from 'http';
/* About the Worker Manager
*
* This process runs on each queue worker container and is responsible starting and monitoring the worker processes. It does this via IPC (inter-process communication).
* In test and development environments, the worker manager is also responsible for providing a readiness check HTTP endpoint so that tests can wait until the worker
* manager is ready before proceeding.
*/
let log = logger('worker-manager');
const REALM_SECRET_SEED = process.env.REALM_SECRET_SEED;
if (!REALM_SECRET_SEED) {
log.error(
`The REALM_SECRET_SEED environment variable is not set. Please make sure this env var has a value`,
);
process.exit(-1);
}
let {
port,
matrixURL,
allPriorityCount = 1,
highPriorityCount = 0,
distURL = process.env.HOST_URL ?? 'http://localhost:4200',
fromUrl: fromUrls,
toUrl: toUrls,
} = yargs(process.argv.slice(2))
.usage('Start worker manager')
.options({
port: {
description:
'HTTP port for worker manager to communicate readiness and status',
type: 'number',
},
highPriorityCount: {
description:
'The number of workers that service high priority jobs (user initiated) to start (default 0)',
type: 'number',
},
allPriorityCount: {
description:
'The number of workers that service all jobs regardless of priority to start (default 1)',
type: 'number',
},
fromUrl: {
description: 'the source of the realm URL proxy',
demandOption: true,
type: 'array',
},
toUrl: {
description: 'the target of the realm URL proxy',
demandOption: true,
type: 'array',
},
distURL: {
description:
'the URL of a deployed host app. (This can be provided instead of the --distPath)',
type: 'string',
},
matrixURL: {
description: 'The matrix homeserver for the realm server',
demandOption: true,
type: 'string',
},
})
.parseSync();
let isReady = false;
let isExiting = false;
process.on('SIGINT', () => (isExiting = true));
process.on('SIGTERM', () => (isExiting = true));
let webServerInstance: Server | undefined;
if (port) {
let webServer = new Koa<Koa.DefaultState, Koa.Context>();
let router = new Router();
router.head('/', livenessCheck);
router.get('/', async (ctxt: Koa.Context, _next: Koa.Next) => {
let result = {
ready: isReady,
} as Record<string, boolean | number>;
if (isReady) {
result = {
...result,
highPriorityWorkers: highPriorityCount,
allPriorityWorkers: allPriorityCount,
};
}
ctxt.set('Content-Type', 'application/json');
ctxt.body = JSON.stringify(result);
ctxt.status = isReady ? 200 : 503;
});
webServer
.use(router.routes())
.use((ctxt: Koa.Context, next: Koa.Next) => {
log.info(
`<-- ${ctxt.method} ${ctxt.req.headers.accept} ${
fullRequestURL(ctxt).href
}`,
);
ctxt.res.on('finish', () => {
log.info(
`--> ${ctxt.method} ${ctxt.req.headers.accept} ${
fullRequestURL(ctxt).href
}: ${ctxt.status}`,
);
log.debug(JSON.stringify(ctxt.req.headers));
});
return next();
})
.use(ecsMetadata);
webServer.on('error', (err: any) => {
log.error(`worker manager HTTP server error: ${err.message}`);
});
webServerInstance = webServer.listen(port);
log.info(`worker manager HTTP listening on port ${port}`);
}
const shutdown = (onShutdown?: () => void) => {
log.info(`Shutting down server for worker manager...`);
webServerInstance?.closeAllConnections();
webServerInstance?.close((err?: Error) => {
if (err) {
log.error(`Error while closing the server for worker manager HTTP:`, err);
process.exit(1);
}
log.info(`worker manager HTTP on port ${port} has stopped.`);
onShutdown?.();
process.exit(0);
});
};
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
process.on('uncaughtException', (err) => {
log.error(`Uncaught exception in worker manager:`, err);
shutdown();
});
process.on('message', (message) => {
if (message === 'stop') {
shutdown(() => {
process.send?.('stopped');
});
} else if (message === 'kill') {
log.info(`Ending worker manager process for ${port}...`);
process.exit(0);
}
});
(async () => {
log.info(
`starting ${highPriorityCount} high-priority ${pluralize(
'worker',
highPriorityCount,
)} and ${allPriorityCount} all-priority ${pluralize(
'worker',
allPriorityCount,
)}`,
);
let urlMappings = fromUrls.map((fromUrl, i) => [
new URL(String(fromUrl)),
new URL(String(toUrls[i])),
]);
for (let i = 0; i < highPriorityCount; i++) {
await startWorker(userInitiatedPriority, urlMappings);
}
for (let i = 0; i < allPriorityCount; i++) {
await startWorker(systemInitiatedPriority, urlMappings);
}
isReady = true;
log.info('All workers have been started');
})().catch((e: any) => {
Sentry.captureException(e);
log.error(
`worker: Unexpected error encountered starting worker manager, stopping worker manager`,
e,
);
process.exit(1);
});
async function startWorker(priority: number, urlMappings: URL[][]) {
let worker = spawn(
'ts-node',
[
'--transpileOnly',
'worker',
`--matrixURL='${matrixURL}'`,
`--distURL='${distURL}'`,
`--priority=${priority}`,
...flattenDeep(
urlMappings.map(([from, to]) => [
`--fromUrl='${from.href}'`,
`--toUrl='${to.href}'`,
]),
),
],
{
stdio: ['pipe', 'pipe', 'pipe', 'ipc'],
},
);
worker.on('exit', () => {
if (!isExiting) {
log.info(`worker ${worker.pid} exited. spawning replacement worker`);
startWorker(priority, urlMappings);
}
});
if (worker.stdout) {
worker.stdout.on('data', (data: Buffer) =>
log.info(
`[worker ${worker.pid} priority ${priority}]: ${data.toString()}`,
),
);
}
if (worker.stderr) {
worker.stderr.on('data', (data: Buffer) =>
log.error(
`[worker ${worker.pid} priority ${priority}]: ${data.toString()}`,
),
);
}
let timeout = await Promise.race([
new Promise<void>((r) => {
worker.on('message', (message) => {
if (message === 'ready') {
log.info(`[worker ${worker.pid} priority ${priority}]: worker ready`);
r();
}
});
}),
new Promise<true>((r) => setTimeout(() => r(true), 30_000)),
]);
if (timeout) {
console.error(
`timed-out waiting for worker pid ${worker.pid} to start. Stopping worker manager`,
);
process.exit(-2);
}
}