-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathfinalizeDeploymentV2.server.ts
More file actions
318 lines (272 loc) · 8.9 KB
/
finalizeDeploymentV2.server.ts
File metadata and controls
318 lines (272 loc) · 8.9 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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
import { ExternalBuildData, FinalizeDeploymentRequestBody } from "@trigger.dev/core/v3/schemas";
import { AuthenticatedEnvironment } from "~/services/apiAuth.server";
import { logger } from "~/services/logger.server";
import { BaseService, ServiceValidationError } from "./baseService.server";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { mkdtemp, writeFile } from "node:fs/promises";
import { env } from "~/env.server";
import { depot as execDepot } from "@depot/cli";
import { FinalizeDeploymentService } from "./finalizeDeployment.server";
import { remoteBuildsEnabled } from "../remoteImageBuilder.server";
import { getEcrAuthToken, isEcrRegistry } from "../getDeploymentImageRef.server";
import { tryCatch } from "@trigger.dev/core";
export class FinalizeDeploymentV2Service extends BaseService {
public async call(
authenticatedEnv: AuthenticatedEnvironment,
id: string,
body: FinalizeDeploymentRequestBody,
writer?: WritableStreamDefaultWriter
) {
// If remote builds are not enabled, lets just use the v1 finalize deployment service
if (!remoteBuildsEnabled()) {
const finalizeService = new FinalizeDeploymentService();
return finalizeService.call(authenticatedEnv, id, body);
}
const deployment = await this._prisma.workerDeployment.findFirst({
where: {
friendlyId: id,
environmentId: authenticatedEnv.id,
},
select: {
status: true,
id: true,
version: true,
externalBuildData: true,
environment: true,
imageReference: true,
worker: {
select: {
project: true,
},
},
},
});
if (!deployment) {
logger.error("Worker deployment not found", { id });
return;
}
if (!deployment.worker) {
logger.error("Worker deployment does not have a worker", { id });
throw new ServiceValidationError("Worker deployment does not have a worker");
}
if (deployment.status === "DEPLOYED") {
logger.debug("Worker deployment is already deployed", { id });
return deployment;
}
if (deployment.status !== "DEPLOYING") {
logger.error("Worker deployment is not in DEPLOYING status", { id });
throw new ServiceValidationError("Worker deployment is not in DEPLOYING status");
}
const externalBuildData = deployment.externalBuildData
? ExternalBuildData.safeParse(deployment.externalBuildData)
: undefined;
if (!externalBuildData) {
throw new ServiceValidationError("External build data is missing");
}
if (!externalBuildData.success) {
throw new ServiceValidationError("External build data is invalid");
}
if (
!env.DEPLOY_REGISTRY_HOST ||
!env.DEPLOY_REGISTRY_USERNAME ||
!env.DEPLOY_REGISTRY_PASSWORD
) {
throw new ServiceValidationError("Missing deployment registry credentials");
}
if (!env.DEPOT_TOKEN) {
throw new ServiceValidationError("Missing depot token");
}
// All new deployments will set the image reference at creation time
if (!deployment.imageReference) {
throw new ServiceValidationError("Missing image reference");
}
logger.debug("Pushing image to registry", { id, deployment, body });
const pushResult = await executePushToRegistry(
{
depot: {
buildId: externalBuildData.data.buildId,
orgToken: env.DEPOT_TOKEN,
projectId: externalBuildData.data.projectId,
},
registry: {
host: env.DEPLOY_REGISTRY_HOST,
namespace: env.DEPLOY_REGISTRY_NAMESPACE,
username: env.DEPLOY_REGISTRY_USERNAME,
password: env.DEPLOY_REGISTRY_PASSWORD,
},
deployment: {
version: deployment.version,
environmentSlug: deployment.environment.slug,
projectExternalRef: deployment.worker.project.externalRef,
imageReference: deployment.imageReference,
},
},
writer
);
if (!pushResult.ok) {
throw new ServiceValidationError(pushResult.error);
}
logger.debug("Image pushed to registry", {
id,
deployment,
body,
pushedImage: pushResult.image,
});
const finalizeService = new FinalizeDeploymentService();
const finalizedDeployment = await finalizeService.call(authenticatedEnv, id, body);
return finalizedDeployment;
}
}
type ExecutePushToRegistryOptions = {
depot: {
buildId: string;
orgToken: string;
projectId: string;
};
registry: {
host: string;
namespace: string;
username: string;
password: string;
};
deployment: {
version: string;
environmentSlug: string;
projectExternalRef: string;
imageReference: string;
};
};
type ExecutePushResult =
| {
ok: true;
image: string;
logs: string;
}
| {
ok: false;
error: string;
logs: string;
};
async function executePushToRegistry(
{ depot, registry, deployment }: ExecutePushToRegistryOptions,
writer?: WritableStreamDefaultWriter
): Promise<ExecutePushResult> {
// Step 1: We need to "login" to the registry
const [loginError, configDir] = await tryCatch(
ensureLoggedIntoDockerRegistry(registry.host, {
username: registry.username,
password: registry.password,
})
);
if (loginError) {
logger.error("Failed to login to registry", {
deployment,
registryHost: registry.host,
error: loginError.message,
});
return {
ok: false as const,
error: "Failed to login to registry",
logs: "",
};
}
const imageTag = deployment.imageReference;
// Step 2: We need to run the depot push command
const childProcess = execDepot(["push", depot.buildId, "-t", imageTag, "--progress", "plain"], {
env: {
NODE_ENV: process.env.NODE_ENV,
DEPOT_TOKEN: depot.orgToken,
DEPOT_PROJECT_ID: depot.projectId,
DEPOT_NO_SUMMARY_LINK: "1",
DEPOT_NO_UPDATE_NOTIFIER: "1",
DOCKER_CONFIG: configDir,
},
});
const errors: string[] = [];
try {
const processCode = await new Promise<number | null>((res, rej) => {
// For some reason everything is output on stderr, not stdout
childProcess.stderr?.on("data", async (data: Buffer) => {
const text = data.toString();
// Emitted data chunks can contain multiple lines. Remove empty lines.
const lines = text.split("\n").filter(Boolean);
errors.push(...lines);
logger.debug(text, { deployment });
// Now we can write strings directly
if (writer) {
for (const line of lines) {
await writer.write(`event: log\ndata: ${JSON.stringify({ message: line })}\n\n`);
}
}
});
childProcess.on("error", (e) => rej(e));
childProcess.on("close", (code) => res(code));
});
const logs = extractLogs(errors);
if (processCode !== 0) {
return {
ok: false as const,
error: `Error pushing image`,
logs,
};
}
return {
ok: true as const,
image: imageTag,
logs,
};
} catch (e) {
return {
ok: false as const,
error: e instanceof Error ? e.message : JSON.stringify(e),
logs: extractLogs(errors),
};
}
}
async function ensureLoggedIntoDockerRegistry(
registryHost: string,
auth: { username: string; password: string } | undefined = undefined
) {
const tmpDir = await createTempDir();
const dockerConfigPath = join(tmpDir, "config.json");
// If this is an ECR registry, get fresh credentials
if (isEcrRegistry(registryHost)) {
auth = await getEcrAuthToken({
registryHost,
assumeRole: env.DEPLOY_REGISTRY_ECR_ASSUME_ROLE_ARN
? {
roleArn: env.DEPLOY_REGISTRY_ECR_ASSUME_ROLE_ARN,
externalId: env.DEPLOY_REGISTRY_ECR_ASSUME_ROLE_EXTERNAL_ID,
}
: undefined,
});
} else if (!auth) {
throw new Error("Authentication required for non-ECR registry");
}
await writeJSONFile(dockerConfigPath, {
auths: {
[registryHost]: {
auth: Buffer.from(`${auth.username}:${auth.password}`).toString("base64"),
},
},
});
logger.debug(`Writing docker config to ${dockerConfigPath}`);
return tmpDir;
}
// Create a temporary directory within the OS's temp directory
async function createTempDir(): Promise<string> {
// Generate a unique temp directory path
const tempDirPath: string = join(tmpdir(), "trigger-");
// Create the temp directory synchronously and return the path
const directory = await mkdtemp(tempDirPath);
return directory;
}
async function writeJSONFile(path: string, json: any, pretty = false) {
await writeFile(path, JSON.stringify(json, undefined, pretty ? 2 : undefined), "utf8");
}
function extractLogs(outputs: string[]) {
// Remove empty lines
const cleanedOutputs = outputs.map((line) => line.trim()).filter((line) => line !== "");
return cleanedOutputs.map((line) => line.trim()).join("\n");
}