-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
374 lines (348 loc) · 11.6 KB
/
index.js
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
const core = require("@actions/core");
const io = require("@actions/io");
const { spawn } = require("child_process");
const fs = require("fs");
const path = require("path");
const choreoApp = process.env.CHOREO_GITOPS_REPO;
const type = core.getInput('type');
const organizationUuid = core.getInput('organizationUuid');
const ACR = "ACR";
const ECR = "ECR";
const DOCKER_HUB = "DOCKER_HUB";
const GCP = "GCP";
async function run() {
switch (type) {
case "login_and_push":
login_and_push();
break;
case "login":
login();
break;
default:
login_and_push();
}
}
async function login_and_push() {
try {
const fileContents = fs.readFileSync(
`/home/runner/workspace/${choreoApp}/${process.env.REG_CRED_FILE_NAME}`,
"utf8"
);
let data = JSON.parse(fileContents);
for (const cred of data) {
if (cred.type == ACR) {
await acrLogin(cred);
await dockerPush(cred , ACR);
}
if (cred.type == ECR) {
await ecrLoginPrivate(cred);
await dockerPush(cred, ECR);
}
if (cred.type == GCP) {
await setupGcpArtifactRegistry(cred);
}
if (cred.type == DOCKER_HUB) {
await dockerHubLogin(cred);
await dockerPush(cred, DOCKER_HUB);
}
}
} catch (error) {
core.setFailed(error.message);
}
}
async function login() {
try {
const fileContents = fs.readFileSync(
`/home/runner/workspace/${choreoApp}/${process.env.REG_CRED_FILE_NAME}`,
"utf8"
);
let data = JSON.parse(fileContents);
for (const cred of data) {
if ((cred?.is_cdp === undefined || cred?.is_cdp) && cred.registry_id != "choreo-docker-hub") {
continue;
}
if (cred.type == ACR) {
await acrLogin(cred);
}
if (cred.type == ECR) {
await ecrLoginPrivate(cred);
}
if (cred.type == GCP) {
await gcpArtifactRegistryLogin(cred);
}
if (cred.type == DOCKER_HUB) {
await dockerHubLogin(cred);
}
}
} catch (error) {
core.setFailed(error.message);
}
}
async function ecrLoginPrivate(cred) {
const username = cred.credentials.registryUser;
const password = cred.credentials.registryPassword;
const region = cred.credentials.region;
const registry = cred.credentials.registry;
console.log(`Logging into ${registry}`);
console.log(`Creating repository ${region}`);
var child = spawn(
`aws configure set aws_access_key_id ${username} && aws configure set aws_secret_access_key ${password} && aws configure set default.region ${region} && aws ecr get-login-password --region ${region} | docker login --username AWS --password-stdin ${registry} && aws ecr describe-repositories --repository-names ${organizationUuid} || aws ecr create-repository --image-scanning-configuration scanOnPush=true --repository-name ${organizationUuid} --image-tag-mutability IMMUTABLE`,
{
shell: true,
}
);
var data = "";
for await (const chunk of child.stdout) {
console.log("stdout chunk: " + chunk);
data += chunk;
}
var error = "";
for await (const chunk of child.stderr) {
console.error("stderr chunk: " + chunk);
error += chunk;
}
const exitCode = await new Promise((resolve, reject) => {
child.on("close", resolve);
});
if (exitCode) {
throw new Error(`subprocess error exit ${exitCode}, ${error}`);
}
return data;
}
// Deprecated: Please implment this feature
async function ecrLoginPublic(cred) {
const username = cred.credentials.registryUser;
const password = cred.credentials.registryPassword;
const region = cred.credentials.region;
var child = spawn(
`aws configure set aws_access_key_id ${username} && aws configure set aws_secret_access_key ${password} && aws configure set default.region ${region} && aws ecr-public get-login-password --region ${region} | docker login --username AWS --password-stdin public.ecr.aws && aws ecr-public describe-repositories --repository-names ${choreoApp} || aws ecr-public create-repository --repository-name ${choreoApp}`,
{
shell: true,
}
);
var data = "";
for await (const chunk of child.stdout) {
console.log("stdout chunk: " + chunk);
data += chunk;
}
var error = "";
for await (const chunk of child.stderr) {
console.error("stderr chunk: " + chunk);
error += chunk;
}
const exitCode = await new Promise((resolve, reject) => {
child.on("close", resolve);
});
if (exitCode) {
throw new Error(`subprocess error exit ${exitCode}, ${error}`);
}
return data;
}
async function dockerHubLogin(cred) {
try {
const username = cred.credentials.registryUser;
const password = cred.credentials.registryPassword;
let loginServer = "https://index.docker.io/v1/";
if (!cred.credentials.registry.includes("docker.io")) {
loginServer = cred.credentials.registry;
}
const authenticationToken = Buffer.from(`${username}:${password}`).toString(
"base64"
);
let config;
const runnerTempDirectory = process.env["RUNNER_TEMP"]; // Using process.env until the core libs are updated
const dirPath =
process.env["DOCKER_CONFIG"] ||
path.join(runnerTempDirectory, `docker_login_${Date.now()}`);
await io.mkdirP(dirPath);
const dockerConfigPath = path.join(dirPath, `config.json`);
if (fs.existsSync(dockerConfigPath)) {
try {
config = JSON.parse(fs.readFileSync(dockerConfigPath, "utf8"));
if (!config.auths) {
config.auths = {};
}
config.auths[loginServer] = { auth: authenticationToken };
} catch (err) {
// if the file is invalid, just overwrite it
config = undefined;
}
}
if (!config) {
config = {
auths: {
[loginServer]: {
auth: authenticationToken,
},
},
};
}
core.debug(`Writing docker config contents to ${dockerConfigPath}`);
fs.writeFileSync(dockerConfigPath, JSON.stringify(config));
core.exportVariable("DOCKER_CONFIG", dirPath);
console.log("DOCKER_CONFIG environment variable is set");
} catch (error) {
core.setFailed(error);
}
}
async function gcpArtifactRegistryLogin(cred) {
const registryPassword = cred.credentials.registryPassword;
const keyContex = Buffer.from(registryPassword, 'base64').toString();
const region = cred.credentials.region;
const registry = cred.credentials.registry;
const repository = cred.credentials.repository;
const projectId = JSON.parse(keyContex)['project_id'];
const newImageTag = `${region}-docker.pkg.dev/${projectId}/${repository}/${choreoApp}:${process.env.NEW_SHA}`;
const keyPath = 'gcp-key.json';
fs.writeFileSync(keyPath, keyContex, 'utf-8');
var child = spawn(`
cat ${keyPath} | docker login -u _json_key --password-stdin ${registry} && \
rm -rf gcp-key.json`,
{
shell: true
});
var data = "";
for await (const chunk of child.stdout) {
console.log(chunk.toString());
data += chunk;
}
var error = "";
for await (const chunk of child.stderr) {
console.error(chunk.toString());
error += chunk;
}
const exitCode = await new Promise((resolve, reject) => {
child.on("close", resolve);
});
if (exitCode) {
throw new Error(`subprocess error exit ${exitCode}, ${error}`);
}
return data;
}
async function acrLogin(cred) {
try {
const username = cred.credentials.registryUser;
const password = cred.credentials.registryPassword;
const loginServer = cred.credentials.registry;
const authenticationToken = Buffer.from(`${username}:${password}`).toString(
"base64"
);
let config;
const runnerTempDirectory = process.env["RUNNER_TEMP"]; // Using process.env until the core libs are updated
const dirPath =
process.env["DOCKER_CONFIG"] ||
path.join(runnerTempDirectory, `docker_login_${Date.now()}`);
await io.mkdirP(dirPath);
const dockerConfigPath = path.join(dirPath, `config.json`);
if (fs.existsSync(dockerConfigPath)) {
try {
config = JSON.parse(fs.readFileSync(dockerConfigPath, "utf8"));
if (!config.auths) {
config.auths = {};
}
config.auths[loginServer] = { auth: authenticationToken };
} catch (err) {
// if the file is invalid, just overwrite it
config = undefined;
}
}
if (!config) {
config = {
auths: {
[loginServer]: {
auth: authenticationToken,
},
},
};
}
core.debug(`Writing docker config contents to ${dockerConfigPath}`);
fs.writeFileSync(dockerConfigPath, JSON.stringify(config));
core.exportVariable("DOCKER_CONFIG", dirPath);
console.log("DOCKER_CONFIG environment variable is set");
} catch (error) {
core.setFailed(error);
}
}
function constructRegistryUrl(cred, registryType) {
const registryUrl = cred.credentials.registry;
if (registryType == ECR) {
return`${registryUrl}/${organizationUuid}:${choreoApp}-${process.env.NEW_SHA}`;
}
return `${registryUrl}/${choreoApp}:${process.env.NEW_SHA}`;
}
async function dockerPush(cred, registryType) {
// We do a docker login to increase the image pull rate limit and this registry id is added as a choreo-docker-hub
// so we skip the docker push for this registry
if (cred.registry_id == "choreo-docker-hub") {
return;
}
const tempImage = process.env.DOCKER_TEMP_IMAGE;
const registryUrl = cred.credentials.registry;
console.log(`Logging into ${registryUrl}`);
const newImageTag = constructRegistryUrl(cred, registryType);
console.log(`Pushing image to ${newImageTag}`);
// Pushing images to Registory
var child = spawn(
`docker image tag ${tempImage} ${newImageTag} && docker push ${newImageTag} && docker logout ${registryUrl}`,
{
shell: true,
}
);
var data = "";
for await (const chunk of child.stdout) {
console.log("stdout chunk: " + chunk);
data += chunk;
}
var error = "";
for await (const chunk of child.stderr) {
console.error("stderr chunk: " + chunk);
error += chunk;
}
const exitCode = await new Promise((resolve, reject) => {
child.on("close", resolve);
});
if (exitCode) {
throw new Error(`subprocess error exit ${exitCode}, ${error}`);
}
return data;
}
async function setupGcpArtifactRegistry(cred) {
const registryPassword = cred.credentials.registryPassword;
const keyContex = Buffer.from(registryPassword, 'base64').toString();
const region = cred.credentials.region;
const registry = cred.credentials.registry;
const repository = cred.credentials.repository;
const projectId = JSON.parse(keyContex)['project_id'];
const newImageTag = `${region}-docker.pkg.dev/${projectId}/${repository}/${choreoApp}:${process.env.NEW_SHA}`;
const keyPath = 'gcp-key.json';
// const shellScriptPath = './scripts/gcp-artifact-registry-push.sh';
// fs.chmodSync(shellScriptPath, "755");
fs.writeFileSync(keyPath, keyContex, 'utf-8');
var child = spawn(`
cat ${keyPath} | docker login -u _json_key --password-stdin ${registry} && \
docker image tag ${process.env.DOCKER_TEMP_IMAGE} ${newImageTag} && \
docker push ${newImageTag} && \
docker logout ${registry} && \
rm -rf gcp-key.json`,
{
shell: true
});
var data = "";
for await (const chunk of child.stdout) {
console.log(chunk.toString());
data += chunk;
}
var error = "";
for await (const chunk of child.stderr) {
console.error(chunk.toString());
error += chunk;
}
const exitCode = await new Promise((resolve, reject) => {
child.on("close", resolve);
});
if (exitCode) {
throw new Error(`subprocess error exit ${exitCode}, ${error}`);
}
return data;
}
run().catch(core.setFailed);