-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathexec.ts
More file actions
293 lines (239 loc) · 7.46 KB
/
exec.ts
File metadata and controls
293 lines (239 loc) · 7.46 KB
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
import { SimpleStructuredLogger } from "@trigger.dev/core/v3/utils/structuredLogger";
import { randomUUID } from "crypto";
import { homedir } from "os";
import { type Result, x } from "tinyexec";
class TinyResult {
pid?: number;
exitCode?: number;
aborted: boolean;
killed: boolean;
constructor(result: Result) {
this.pid = result.pid;
this.exitCode = result.exitCode;
this.aborted = result.aborted;
this.killed = result.killed;
}
}
interface ExecOptions {
logger?: SimpleStructuredLogger;
abortSignal?: AbortSignal;
logOutput?: boolean;
trimArgs?: boolean;
neverThrow?: boolean;
}
export class Exec {
private logger: SimpleStructuredLogger;
private abortSignal: AbortSignal | undefined;
private logOutput: boolean;
private trimArgs: boolean;
private neverThrow: boolean;
constructor(opts: ExecOptions) {
this.logger = opts.logger ?? new SimpleStructuredLogger("exec");
this.abortSignal = opts.abortSignal;
this.logOutput = opts.logOutput ?? true;
this.trimArgs = opts.trimArgs ?? true;
this.neverThrow = opts.neverThrow ?? false;
}
async x(
command: string,
args?: string[],
opts?: { neverThrow?: boolean; ignoreAbort?: boolean }
) {
const argsTrimmed = this.trimArgs ? args?.map((arg) => arg.trim()) : args;
const commandWithFirstArg = `${command}${argsTrimmed?.length ? ` ${argsTrimmed[0]}` : ""}`;
this.logger.debug(`exec: ${commandWithFirstArg}`, { command, args, argsTrimmed });
const result = x(command, argsTrimmed, {
signal: opts?.ignoreAbort ? undefined : this.abortSignal,
// We don't use this as it doesn't cover killed and aborted processes
// throwOnError: true,
});
const output = await result;
const metadata = {
command,
argsRaw: args,
argsTrimmed,
globalOpts: {
trimArgs: this.trimArgs,
neverThrow: this.neverThrow,
hasAbortSignal: !!this.abortSignal,
},
localOpts: opts,
stdout: output.stdout,
stderr: output.stderr,
pid: result.pid,
exitCode: result.exitCode,
aborted: result.aborted,
killed: result.killed,
};
if (this.logOutput) {
this.logger.debug(`output: ${commandWithFirstArg}`, metadata);
}
if (this.neverThrow || opts?.neverThrow) {
return output;
}
if (result.aborted) {
this.logger.error(`aborted: ${commandWithFirstArg}`, metadata);
throw new TinyResult(result);
}
if (result.killed) {
this.logger.error(`killed: ${commandWithFirstArg}`, metadata);
throw new TinyResult(result);
}
if (result.exitCode !== 0) {
this.logger.error(`non-zero exit: ${commandWithFirstArg}`, metadata);
throw new TinyResult(result);
}
return output;
}
static Result = TinyResult;
}
interface BuildahOptions {
id?: string;
abortSignal?: AbortSignal;
}
export class Buildah {
private id: string;
private logger: SimpleStructuredLogger;
private exec: Exec;
private containers = new Set<string>();
private images = new Set<string>();
constructor(opts: BuildahOptions) {
this.id = opts.id ?? randomUUID();
this.logger = new SimpleStructuredLogger("buildah", undefined, { id: this.id });
this.exec = new Exec({
logger: this.logger,
abortSignal: opts.abortSignal,
});
this.logger.log("initiaized", { opts });
}
private get x() {
return this.exec.x.bind(this.exec);
}
async from(baseImage: string) {
const output = await this.x("buildah", ["from", baseImage]);
this.containers.add(output.stdout);
return output;
}
async add(container: string, src: string, dest: string) {
return await this.x("buildah", ["add", container, src, dest]);
}
async config(container: string, annotations: string[]) {
const args = ["config"];
for (const annotation of annotations) {
args.push(`--annotation=${annotation}`);
}
args.push(container);
return await this.x("buildah", args);
}
async commit(container: string, imageRef: string) {
const output = await this.x("buildah", ["commit", container, imageRef]);
this.images.add(output.stdout);
return output;
}
async push(imageRef: string, registryTlsVerify?: boolean) {
return await this.x("buildah", [
"push",
`--tls-verify=${String(!!registryTlsVerify)}`,
imageRef,
]);
}
async cleanup() {
if (this.containers.size > 0) {
try {
const output = await this.x("buildah", ["rm", ...this.containers], { ignoreAbort: true });
this.containers.clear();
if (output.stderr.length > 0) {
this.logger.error("failed to remove some containers", { output });
}
} catch (error) {
this.logger.error("failed to clean up containers", { error, containers: this.containers });
}
} else {
this.logger.debug("no containers to clean up");
}
if (this.images.size > 0) {
try {
const output = await this.x("buildah", ["rmi", ...this.images], { ignoreAbort: true });
this.images.clear();
if (output.stderr.length > 0) {
this.logger.error("failed to remove some images", { output });
}
} catch (error) {
this.logger.error("failed to clean up images", { error, images: this.images });
}
} else {
this.logger.debug("no images to clean up");
}
}
static async canLogin(registryHost: string) {
try {
await x("buildah", ["login", "--get-login", registryHost], { throwOnError: true });
return true;
} catch (error) {
return false;
}
}
static get tmpDir() {
return process.env.TMPDIR ?? "/var/tmp";
}
static get storageRootDir() {
return process.getuid?.() === 0
? "/var/lib/containers/storage"
: `${homedir()}/.local/share/containers/storage`;
}
}
interface CrictlOptions {
id?: string;
abortSignal?: AbortSignal;
}
export class Crictl {
private id: string;
private logger: SimpleStructuredLogger;
private exec: Exec;
private archives = new Set<string>();
constructor(opts: CrictlOptions) {
this.id = opts.id ?? randomUUID();
this.logger = new SimpleStructuredLogger("crictl", undefined, { id: this.id });
this.exec = new Exec({
logger: this.logger,
abortSignal: opts.abortSignal,
});
this.logger.log("initiaized", { opts });
}
private get x() {
return this.exec.x.bind(this.exec);
}
async ps(containerName: string, quiet?: boolean) {
return await this.x("crictl", ["ps", "--name", containerName, quiet ? "--quiet" : ""]);
}
async checkpoint(containerId: string, exportLocation: string) {
const output = await this.x("crictl", [
"checkpoint",
`--export=${exportLocation}`,
containerId,
]);
this.archives.add(exportLocation);
return output;
}
async cleanup() {
if (this.archives.size > 0) {
try {
const output = await this.x("rm", ["-v", ...this.archives], { ignoreAbort: true });
this.archives.clear();
if (output.stderr.length > 0) {
this.logger.error("failed to remove some archives", { output });
}
} catch (error) {
this.logger.error("failed to clean up archives", { error, archives: this.archives });
}
} else {
this.logger.debug("no archives to clean up");
}
}
static getExportLocation(identifier: string) {
return `${this.checkpointDir}/${identifier}.tar`;
}
static get checkpointDir() {
return process.env.CRI_CHECKPOINT_DIR ?? "/checkpoints";
}
}