This repository was archived by the owner on Apr 13, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathget.ts
More file actions
601 lines (563 loc) · 16.6 KB
/
get.ts
File metadata and controls
601 lines (563 loc) · 16.6 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
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
import Table from "cli-table";
import commander from "commander";
import {
duration,
getDeploymentsBasedOnFilters,
IDeployment,
status as getDeploymentStatus,
fetchPR,
getRepositoryFromURL,
} from "spektate/lib/IDeployment";
import AzureDevOpsPipeline from "spektate/lib/pipeline/AzureDevOpsPipeline";
import {
getManifestSyncState as getAzureManifestSyncState,
IAzureDevOpsRepo,
} from "spektate/lib/repository/IAzureDevOpsRepo";
import {
getManifestSyncState as getGithubManifestSyncState,
IGitHub,
} from "spektate/lib/repository/IGitHub";
import { ITag } from "spektate/lib/repository/Tag";
import { Config } from "../../config";
import { build as buildCmd, exit as exitCmd } from "../../lib/commandBuilder";
import { build as buildError, log as logError } from "../../lib/errorBuilder";
import { errorStatusCode } from "../../lib/errorStatusCode";
import { isIntegerString } from "../../lib/validator";
import { logger } from "../../logger";
import decorator from "./get.decorator.json";
import { IPullRequest } from "spektate/lib/repository/IPullRequest";
const promises: Promise<void>[] = [];
const pullRequests: { [id: string]: IPullRequest } = {};
/**
* Output formats to display service details
*/
export enum OUTPUT_FORMAT {
NORMAL = 0, // normal format
WIDE = 1, // Wide table format
JSON = 2,
}
/**
* Interface for capturing all the
* objects and key during the initialization
* process
*/
export interface InitObject {
accountName: string;
tableName: string;
partitionKey: string;
clusterPipeline: AzureDevOpsPipeline;
hldPipeline: AzureDevOpsPipeline;
key: string;
srcPipeline: AzureDevOpsPipeline;
manifestRepo?: string;
accessToken?: string;
}
/**
* Command Line values from the commander
*/
export interface CommandOptions {
watch: boolean;
output: string;
env: string;
imageTag: string;
buildId: string;
commitId: string;
service: string;
deploymentId: string;
top: string;
}
/**
* Validated commandline values. After verify top value and
* the output format.
*/
export interface ValidatedOptions extends CommandOptions {
nTop: number;
outputFormat: OUTPUT_FORMAT;
}
/**
* Processes the output format based on defaults
* @param outputFormat Output format specified by the user
*/
export const processOutputFormat = (outputFormat: string): OUTPUT_FORMAT => {
if (outputFormat && outputFormat.toLowerCase() === "wide") {
return OUTPUT_FORMAT.WIDE;
}
if (outputFormat && outputFormat.toLowerCase() === "json") {
return OUTPUT_FORMAT.JSON;
}
return OUTPUT_FORMAT.NORMAL;
};
/**
* Validating the options values from commander.
*
* @param opts options values from commander
* @return validated values
* @throws Error if opts.top is not a positive integer
*/
export const validateValues = (opts: CommandOptions): ValidatedOptions => {
let top = 0; // no limits
if (opts.top) {
if (isIntegerString(opts.top)) {
top = parseInt(opts.top, 10);
} else {
throw buildError(errorStatusCode.VALIDATION_ERR, {
errorKey: "introspect-get-cmd-err-validation-top-num",
values: [opts.top],
});
}
}
return {
buildId: opts.buildId,
commitId: opts.commitId,
deploymentId: opts.deploymentId,
env: opts.env,
imageTag: opts.imageTag,
nTop: top,
output: opts.output,
outputFormat: processOutputFormat(opts.output),
service: opts.service,
top: opts.top,
watch: opts.watch,
};
};
/**
* Initializes the pipelines assuming that the configuration has been loaded
*/
export const initialize = async (): Promise<InitObject> => {
const config = Config();
if (
!config.introspection ||
!config.azure_devops ||
!config.introspection.azure ||
!config.azure_devops.org ||
!config.azure_devops.project ||
!config.introspection.azure.account_name ||
!config.introspection.azure.table_name ||
!config.introspection.azure.key ||
!config.introspection.azure.partition_key ||
!config.introspection.azure.key
) {
throw buildError(
errorStatusCode.VALIDATION_ERR,
"introspect-get-cmd-missing-vals"
);
}
return {
clusterPipeline: new AzureDevOpsPipeline(
config.azure_devops.org,
config.azure_devops.project,
false,
config.azure_devops.access_token
),
hldPipeline: new AzureDevOpsPipeline(
config.azure_devops.org,
config.azure_devops.project,
true,
config.azure_devops.access_token
),
key: config.introspection.azure.key,
srcPipeline: new AzureDevOpsPipeline(
config.azure_devops.org,
config.azure_devops.project,
false,
config.azure_devops.access_token
),
accountName: config.introspection.azure.account_name,
tableName: config.introspection.azure.table_name,
partitionKey: config.introspection.azure.partition_key,
manifestRepo: config.azure_devops.manifest_repository,
accessToken: config.azure_devops.access_token,
};
};
/**
* Gets cluster sync statuses
* @param initObj captures keys and objects during the initialization process
*/
export const getClusterSyncStatuses = async (
initObj: InitObject
): Promise<ITag[] | undefined> => {
try {
if (initObj.manifestRepo && initObj.manifestRepo.includes("azure.com")) {
const manifestUrlSplit = initObj.manifestRepo.split("/");
const manifestRepo: IAzureDevOpsRepo = {
org: manifestUrlSplit[3],
project: manifestUrlSplit[4],
repo: manifestUrlSplit[6],
};
return await getAzureManifestSyncState(manifestRepo, initObj.accessToken);
} else if (
initObj.manifestRepo &&
initObj.manifestRepo.includes("github.com")
) {
const manifestUrlSplit = initObj.manifestRepo.split("/");
const manifestRepo: IGitHub = {
reponame: manifestUrlSplit[4],
username: manifestUrlSplit[3],
};
return await getGithubManifestSyncState(
manifestRepo,
initObj.accessToken
);
} else {
return undefined;
}
} catch (err) {
throw buildError(
errorStatusCode.GIT_OPS_ERR,
"introspect-get-cmd-cluster-sync-stat-err",
err
);
}
};
/**
* Fetches pull request data for deployments that complete merge into HLD
* by merging a PR
*
* @param deployment deployment for which PR has to be fetched
* @param initObj initialization object
*/
export const fetchPRInformation = async (
deployment: IDeployment,
initObj: InitObject
): Promise<void> => {
if (deployment.hldRepo && deployment.pr) {
const repo = getRepositoryFromURL(deployment.hldRepo);
const strPr = deployment.pr.toString();
if (repo) {
try {
const pr = await fetchPR(repo, strPr, initObj.accessToken);
if (pr) {
pullRequests[strPr] = pr;
}
} catch (err) {
logger.warn(`Could not get PR ${strPr} information: ` + err);
}
}
}
};
/**
* Gets PR information for all the deployments.
*
* @param deployments all deployments to be displayed
* @param initObj initialization object
*/
export const getPRs = (
deployments: IDeployment[] | undefined,
initObj: InitObject
): void => {
(deployments || []).forEach((d) => {
promises.push(fetchPRInformation(d, initObj));
});
};
/**
* Returns a status indicator icon
*
* @param status Status
* @return a status indicator icon
*/
export const getStatus = (status: string): string => {
if (status === "succeeded") {
return "\u2713";
} else if (!status) {
return "...";
}
return "\u0445";
};
/**
* Returns a matching sync status for a deployment
* @param deployment Deployment object
* @param syncStatuses list of sync statuses for manifest
*/
export const getClusterSyncStatusForDeployment = (
deployment: IDeployment,
syncStatuses: ITag[]
): ITag | undefined => {
return syncStatuses.find((tag) => tag.commit === deployment.manifestCommitId);
};
/**
* Prints deployments in a terminal table
* @param deployments list of deployments to print in terminal
* @param outputFormat output format: normal | wide | json
*/
export const printDeployments = (
deployments: IDeployment[] | undefined,
outputFormat: OUTPUT_FORMAT,
limit?: number,
syncStatuses?: ITag[] | undefined
): Table | undefined => {
if (deployments && deployments.length > 0) {
let header = [
"Start Time",
"Service",
"Deployment",
"Commit",
"Src to ACR",
"Image Tag",
"Result",
"ACR to HLD",
"Env",
"Hld Commit",
"Result",
];
let prsExist = false;
if (
Object.keys(pullRequests).length > 0 &&
outputFormat === OUTPUT_FORMAT.WIDE
) {
header = header.concat(["Approval PR", "Merged By"]);
prsExist = true;
}
header = header.concat(["HLD to Manifest", "Result"]);
if (outputFormat === OUTPUT_FORMAT.WIDE) {
header = header.concat([
"Duration",
"Status",
"Manifest Commit",
"End Time",
]);
}
if (syncStatuses && syncStatuses.length > 0) {
header = header.concat(["Cluster Sync"]);
}
const table = new Table({
head: header,
chars: {
top: "",
"top-mid": "",
"top-left": "",
"top-right": "",
bottom: "",
"bottom-mid": "",
"bottom-left": "",
"bottom-right": "",
left: "",
"left-mid": "",
mid: "",
"mid-mid": "",
right: "",
"right-mid": "",
middle: " ",
},
style: { "padding-left": 0, "padding-right": 0 },
});
const toDisplay = limit ? deployments.slice(0, limit) : deployments;
toDisplay.forEach((deployment) => {
const row = [];
let deploymentStatus = getDeploymentStatus(deployment);
row.push(
deployment.srcToDockerBuild
? deployment.srcToDockerBuild.startTime.toLocaleString()
: deployment.hldToManifestBuild
? deployment.hldToManifestBuild.startTime.toLocaleString()
: "-"
);
row.push(deployment.service !== "" ? deployment.service : "-");
row.push(deployment.deploymentId);
row.push(deployment.commitId !== "" ? deployment.commitId : "-");
row.push(
deployment.srcToDockerBuild ? deployment.srcToDockerBuild.id : "-"
);
row.push(deployment.imageTag !== "" ? deployment.imageTag : "-");
row.push(
deployment.srcToDockerBuild
? getStatus(deployment.srcToDockerBuild.result)
: ""
);
let dockerToHldId = "-";
let dockerToHldStatus = "";
if (deployment.dockerToHldRelease) {
dockerToHldId = deployment.dockerToHldRelease.id;
dockerToHldStatus = getStatus(deployment.dockerToHldRelease.status);
} else if (
deployment.dockerToHldReleaseStage &&
deployment.srcToDockerBuild
) {
dockerToHldId = deployment.dockerToHldReleaseStage.id;
dockerToHldStatus = getStatus(deployment.srcToDockerBuild.result);
}
row.push(dockerToHldId);
row.push(
deployment.environment !== ""
? deployment.environment.toUpperCase()
: "-"
);
row.push(deployment.hldCommitId || "-");
row.push(dockerToHldStatus);
// Print PR if available
if (
prsExist &&
deployment.pr &&
deployment.pr.toString() in pullRequests
) {
row.push(deployment.pr);
if (pullRequests[deployment.pr.toString()].mergedBy) {
row.push(pullRequests[deployment.pr.toString()].mergedBy?.name);
} else {
deploymentStatus = "Waiting";
row.push("-");
}
} else if (prsExist) {
row.push("-");
row.push("-");
}
row.push(
deployment.hldToManifestBuild ? deployment.hldToManifestBuild.id : "-"
);
row.push(
deployment.hldToManifestBuild
? getStatus(deployment.hldToManifestBuild.result)
: ""
);
if (outputFormat === OUTPUT_FORMAT.WIDE) {
row.push(duration(deployment) + " mins");
row.push(deploymentStatus);
row.push(deployment.manifestCommitId || "-");
row.push(
deployment.hldToManifestBuild &&
deployment.hldToManifestBuild.finishTime &&
!isNaN(new Date(deployment.hldToManifestBuild.finishTime).getTime())
? deployment.hldToManifestBuild.finishTime.toLocaleString()
: deployment.srcToDockerBuild &&
deployment.srcToDockerBuild.finishTime &&
!isNaN(new Date(deployment.srcToDockerBuild.finishTime).getTime())
? deployment.srcToDockerBuild.finishTime.toLocaleString()
: "-"
);
}
if (syncStatuses && syncStatuses.length > 0) {
const tag = getClusterSyncStatusForDeployment(deployment, syncStatuses);
if (tag) {
row.push(tag.name);
} else {
row.push("-");
}
}
table.push(row);
});
console.log(table.toString());
return table;
} else {
logger.info("No deployments found for specified filters.");
return undefined;
}
};
/**
* Displays the deployments based on output format requested and top n
* @param values validated command line values
* @param deployments list of deployments to display
* @param syncStatuses cluster sync statuses,
* @param initObj initialization object
*/
export const displayDeployments = async (
values: ValidatedOptions,
deployments: IDeployment[] | undefined,
syncStatuses: ITag[] | undefined,
initObj: InitObject
): Promise<IDeployment[]> => {
if (values.outputFormat === OUTPUT_FORMAT.WIDE) {
getPRs(deployments, initObj);
}
if (values.outputFormat === OUTPUT_FORMAT.JSON) {
console.log(JSON.stringify(deployments, null, 2));
return deployments || [];
}
await Promise.all(promises);
printDeployments(deployments, values.outputFormat, values.nTop, syncStatuses);
return deployments || [];
};
/**
* Gets a list of deployments for the specified filters
* @param initObj captures keys and objects during the initialization process
* @param values validated command line values
*/
export const getDeployments = async (
initObj: InitObject,
values: ValidatedOptions
): Promise<IDeployment[]> => {
try {
const syncStatusesPromise = getClusterSyncStatuses(initObj);
const deploymentsPromise = getDeploymentsBasedOnFilters(
initObj.accountName,
initObj.key,
initObj.tableName,
initObj.partitionKey,
initObj.srcPipeline,
initObj.hldPipeline,
initObj.clusterPipeline,
values.env,
values.imageTag,
values.buildId,
values.commitId,
values.service,
values.deploymentId
);
const tuple: [
IDeployment[] | undefined,
ITag[] | undefined
] = await Promise.all([deploymentsPromise, syncStatusesPromise]);
const deployments: IDeployment[] | undefined = tuple[0];
const syncStatuses: ITag[] | undefined = tuple[1];
return await displayDeployments(values, deployments, syncStatuses, initObj);
} catch (err) {
throw buildError(
errorStatusCode.EXE_FLOW_ERR,
"introspect-get-cmd-get-deployments-err",
err
);
}
};
/**
* Returns a list of deployments for the specified filters every 5 seconds
*
* @param initObject Initialization Object
* @param values Validated values from commander
*/
export const watchGetDeployments = async (
initObjects: InitObject,
values: ValidatedOptions
): Promise<void> => {
const timeInterval = 5000;
// Call get deployments once, and then set the timer.
await getDeployments(initObjects, values);
setInterval(async () => {
await getDeployments(initObjects, values);
}, timeInterval);
};
/**
* Executes the command, can all exit function with 0 or 1
* when command completed successfully or failed respectively.
*
* @param opts validated option values
* @param exitFn exit function
*/
export const execute = async (
opts: CommandOptions,
exitFn: (status: number) => Promise<void>
): Promise<void> => {
try {
const values = validateValues(opts);
const initObjects = await initialize();
if (opts.watch) {
await watchGetDeployments(initObjects, values);
} else {
await getDeployments(initObjects, values);
await exitFn(0);
}
} catch (err) {
logError(
buildError(errorStatusCode.CMD_EXE_ERR, "introspect-get-cmd-failed", err)
);
await exitFn(1);
}
};
/**
* Adds the get command to the commander command object
* @param command Commander command object to decorate
*/
export const commandDecorator = (command: commander.Command): void => {
buildCmd(command, decorator).action(async (opts: CommandOptions) => {
await execute(opts, async (status: number) => {
await exitCmd(logger, process.exit, status);
});
});
};