/
run.ts
253 lines (218 loc) · 6.79 KB
/
run.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
import assert from 'assert';
import { ChildProcess } from 'child_process';
import path from 'path';
import * as readline from 'readline';
import { Args, Flags } from '@oclif/core';
import retryAsync from 'async-retry';
import chalk from 'chalk';
import crossSpawn from 'cross-spawn';
import dotenv from 'dotenv';
import { defaults, omit } from 'lodash';
import treeKill from 'tree-kill';
import { CliCommand } from '../command';
import { evalManifestEnv, loadManifestFile } from '../manifest';
const chalkColors = [chalk.green, chalk.yellow, chalk.blue, chalk.magenta, chalk.cyan];
const chalkColorGenerator = (() => {
let n = 0;
return () => chalkColors[n++ % chalkColors.length];
})();
type SquidProcessOptions = {
env?: Record<string, string>;
cwd?: string;
stdin: NodeJS.ReadableStream;
stdout: NodeJS.WritableStream;
stderr: NodeJS.WritableStream;
};
class SquidProcess {
private readonly prefix: string;
private child?: ChildProcess;
private options: SquidProcessOptions;
constructor(
readonly name: string,
private cmd: string[],
options: Partial<SquidProcessOptions>,
) {
this.prefix = chalkColorGenerator()(`[${name}]`);
this.options = defaults(options, {
stdin: process.stdin,
stdout: process.stdout,
stderr: process.stderr,
});
}
async run({ retries }: { retries: number }) {
await retryAsync(
async () => {
const result = await this.spawn();
if (result.code && result.code > 0) {
throw new Error(`Process ${this.prefix} failed with exit code: ${result.code}`);
} else {
return;
}
},
{
forever: retries < 0,
retries,
factor: 1,
onRetry: (e) => {
console.log(e.message);
console.log(`Process ${this.prefix} restarting...`);
},
},
);
}
kill(signal?: string | number) {
if (this.child?.pid) {
treeKill(this.child.pid, signal);
this.child = undefined;
}
}
private spawn() {
assert(!this.child, `process "${this.name}" has been already started`);
const [command, ...args] = this.cmd;
return new Promise<{ code: number | null; signal: string | null }>((resolve, reject) => {
const child = crossSpawn(command, args, {
cwd: this.options.cwd,
env: this.options.env,
});
this.child = child;
child.once('error', (error: Error) => {
this.child = undefined;
reject(error);
});
child.once('close', (code: number | null, signal: string | null) => {
this.child = undefined;
resolve({ code, signal });
});
if (this.child.stderr) {
this.pipe(this.child.stderr, this.options.stderr);
}
if (this.child.stdout) {
this.pipe(this.child.stdout, this.options.stdout);
}
});
}
private pipe(input: NodeJS.ReadableStream, output: NodeJS.WritableStream) {
readline.createInterface({ input }).on('line', (line) => {
output.write(`${this.prefix} ${line}\n`);
});
}
}
function isSkipped({ include, exclude }: { include?: string[]; exclude?: string[] }, haystack: string) {
if (exclude?.length && exclude.includes(haystack)) return true;
else if (include?.length && !include.includes(haystack)) return true;
return false;
}
export default class Run extends CliCommand {
static description = 'Run a squid project locally';
static flags = {
manifest: Flags.string({
char: 'm',
description: 'Relative path to a squid manifest file',
required: false,
default: 'squid.yaml',
}),
envFile: Flags.string({
char: 'f',
description: 'Relative path to an additional environment file',
required: false,
default: '.env',
}),
exclude: Flags.string({ char: 'e', description: 'Do not run specified services', required: false, multiple: true }),
include: Flags.string({
char: 'i',
description: 'Run only specified services',
required: false,
multiple: true,
exclusive: ['exclude'],
}),
retries: Flags.integer({
char: 'r',
description: 'Attempts to restart failed or stopped services',
required: false,
default: 5,
}),
};
static args = {
path: Args.string({
hidden: false,
required: true,
default: '.',
}),
};
async run(): Promise<void> {
try {
const {
flags: { manifest: manifestPath, envFile, exclude, include, retries },
args: { path: squidPath },
} = await this.parse(Run);
const { squidDir, manifest } = loadManifestFile(squidPath, manifestPath);
const children: SquidProcess[] = [];
if (envFile) {
const { error } = dotenv.config({
path: path.isAbsolute(envFile) ? envFile : path.join(squidDir, envFile),
});
if (error) {
return this.error(error);
}
}
const context = { secrets: process.env };
const processEnv = omit(process.env, ['PROCESSOR_PROMETHEUS_PORT']);
const env = {
FORCE_COLOR: 'true',
FORCE_PRETTY_LOGGER: 'true',
...processEnv,
...evalManifestEnv(manifest.deploy?.env ?? {}, context),
};
const init = manifest.deploy?.init;
if (init && init.cmd && !isSkipped({ include, exclude }, 'init')) {
const p = new SquidProcess('init', init.cmd, {
env: {
...env,
...evalManifestEnv(init.env ?? {}, context),
},
cwd: squidDir,
});
await p.run({ retries });
}
const api = manifest.deploy?.api;
if (api && api.cmd && !isSkipped({ include, exclude }, 'api')) {
children.push(
new SquidProcess('api', api.cmd, {
env: {
...env,
...evalManifestEnv(api.env ?? {}, context),
},
cwd: squidDir,
}),
);
}
if (manifest.deploy?.processor) {
const processors = Array.isArray(manifest.deploy.processor)
? manifest.deploy.processor
: [manifest.deploy.processor];
for (const processor of processors) {
if (!processor.cmd || isSkipped({ include, exclude }, processor.name)) continue;
children.push(
new SquidProcess(processor.name, processor.cmd, {
env: {
...env,
...evalManifestEnv(processor.env ?? {}, context),
},
cwd: squidDir,
}),
);
}
}
let error: Error | undefined;
const abort = (e: Error) => {
if (error) return;
error = e;
children.map((c) => c.kill());
};
await Promise.allSettled(children.map((c) => c.run({ retries }).catch(abort)));
if (error) this.error(error);
} catch (e: any) {
this.error(e instanceof Error ? e.message : e);
}
}
}