-
Notifications
You must be signed in to change notification settings - Fork 450
Expand file tree
/
Copy pathinit-action-post-helper.ts
More file actions
386 lines (356 loc) · 12 KB
/
init-action-post-helper.ts
File metadata and controls
386 lines (356 loc) · 12 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
import * as fs from "fs";
import * as github from "@actions/github";
import * as actionsUtil from "./actions-util";
import { CodeScanning } from "./analyses";
import { getApiClient } from "./api-client";
import { CodeQL, getCodeQL } from "./codeql";
import { Config, isCodeScanningEnabled } from "./config-utils";
import * as dependencyCaching from "./dependency-caching";
import { EnvVar } from "./environment";
import { Feature, FeatureEnablement } from "./feature-flags";
import { Logger } from "./logging";
import { OverlayDatabaseMode } from "./overlay";
import { OverlayStatus, saveOverlayStatus } from "./overlay/status";
import { RepositoryNwo, getRepositoryNwo } from "./repository";
import { JobStatus } from "./status-report";
import * as uploadLib from "./upload-lib";
import {
checkDiskUsage,
delay,
getErrorMessage,
getRequiredEnvParam,
parseMatrixInput,
shouldSkipSarifUpload,
wrapError,
} from "./util";
import {
getCategoryInputOrThrow,
getCheckoutPathInputOrThrow,
getUploadInputOrThrow,
getWorkflow,
} from "./workflow";
export interface UploadFailedSarifResult extends uploadLib.UploadStatusReport {
/** If there was an error while uploading a failed run, this is its message. */
upload_failed_run_error?: string;
/** If there was an error while uploading a failed run, this is its stack trace. */
upload_failed_run_stack_trace?: string;
/** Reason why we did not upload a SARIF payload with `executionSuccessful: false`. */
upload_failed_run_skipped_because?: string;
/** The internal ID of SARIF analysis. */
sarifID?: string;
}
export interface JobStatusReport {
job_status: JobStatus;
}
export interface DependencyCachingUsageReport {
dependency_caching_usage?: dependencyCaching.DependencyCachingUsageReport;
}
function createFailedUploadFailedSarifResult(
error: unknown,
): UploadFailedSarifResult {
const wrappedError = wrapError(error);
return {
upload_failed_run_error: wrappedError.message,
upload_failed_run_stack_trace: wrappedError.stack,
};
}
/**
* Upload a failed SARIF file if we can verify that SARIF upload is enabled and determine the SARIF
* category for the workflow.
*/
async function maybeUploadFailedSarif(
config: Config,
repositoryNwo: RepositoryNwo,
features: FeatureEnablement,
logger: Logger,
): Promise<UploadFailedSarifResult> {
if (!config.codeQLCmd) {
return { upload_failed_run_skipped_because: "CodeQL command not found" };
}
const workflow = await getWorkflow(logger);
const jobName = getRequiredEnvParam("GITHUB_JOB");
const matrix = parseMatrixInput(actionsUtil.getRequiredInput("matrix"));
const shouldUpload = getUploadInputOrThrow(workflow, jobName, matrix);
if (
!["always", "failure-only"].includes(
actionsUtil.getUploadValue(shouldUpload),
) ||
shouldSkipSarifUpload()
) {
return { upload_failed_run_skipped_because: "SARIF upload is disabled" };
}
const category = getCategoryInputOrThrow(workflow, jobName, matrix);
const checkoutPath = getCheckoutPathInputOrThrow(workflow, jobName, matrix);
const databasePath = config.dbLocation;
const codeql = await getCodeQL(config.codeQLCmd);
const sarifFile = "../codeql-failed-run.sarif";
// If there is no database or the feature flag is off, we run 'export diagnostics'
if (
databasePath === undefined ||
!(await features.getValue(Feature.ExportDiagnosticsEnabled, codeql))
) {
await codeql.diagnosticsExport(sarifFile, category, config);
} else {
// We call 'database export-diagnostics' to find any per-database diagnostics.
await codeql.databaseExportDiagnostics(databasePath, sarifFile, category);
}
logger.info(`Uploading failed SARIF file ${sarifFile}`);
const uploadResult = await uploadLib.uploadFiles(
sarifFile,
checkoutPath,
category,
features,
logger,
CodeScanning,
);
await uploadLib.waitForProcessing(
repositoryNwo,
uploadResult.sarifID,
logger,
{ isUnsuccessfulExecution: true },
);
return uploadResult
? { ...uploadResult.statusReport, sarifID: uploadResult.sarifID }
: {};
}
export async function tryUploadSarifIfRunFailed(
config: Config,
repositoryNwo: RepositoryNwo,
features: FeatureEnablement,
logger: Logger,
): Promise<UploadFailedSarifResult> {
// Only upload the failed SARIF to Code scanning if Code scanning is enabled.
if (!isCodeScanningEnabled(config)) {
return {
upload_failed_run_skipped_because: "Code Scanning is not enabled.",
};
}
if (process.env[EnvVar.ANALYZE_DID_COMPLETE_SUCCESSFULLY] === "true") {
return {
upload_failed_run_skipped_because:
"Analyze Action completed successfully",
};
}
try {
return await maybeUploadFailedSarif(
config,
repositoryNwo,
features,
logger,
);
} catch (e) {
logger.debug(
`Failed to upload a SARIF file for this failed CodeQL code scanning run. ${e}`,
);
return createFailedUploadFailedSarifResult(e);
}
}
export async function run(
uploadAllAvailableDebugArtifacts: (
codeql: CodeQL,
config: Config,
logger: Logger,
codeQlVersion: string,
) => Promise<void>,
printDebugLogs: (config: Config) => Promise<void>,
codeql: CodeQL,
config: Config,
repositoryNwo: RepositoryNwo,
features: FeatureEnablement,
logger: Logger,
) {
await recordOverlayStatus(codeql, config, features, logger);
const uploadFailedSarifResult = await tryUploadSarifIfRunFailed(
config,
repositoryNwo,
features,
logger,
);
if (uploadFailedSarifResult.upload_failed_run_skipped_because) {
logger.debug(
"Won't upload a failed SARIF file for this CodeQL code scanning run because: " +
`${uploadFailedSarifResult.upload_failed_run_skipped_because}.`,
);
}
// Throw an error if in integration tests, we expected to upload a SARIF file for a failed run
// but we didn't upload anything.
if (
process.env["CODEQL_ACTION_EXPECT_UPLOAD_FAILED_SARIF"] === "true" &&
!uploadFailedSarifResult.raw_upload_size_bytes
) {
const error = JSON.stringify(uploadFailedSarifResult);
throw new Error(
"Expected to upload a failed SARIF file for this CodeQL code scanning run, " +
`but the result was instead ${error}.`,
);
}
if (process.env["CODEQL_ACTION_EXPECT_UPLOAD_FAILED_SARIF"] === "true") {
if (!github.context.payload.pull_request?.head.repo.fork) {
await removeUploadedSarif(uploadFailedSarifResult, logger);
} else {
logger.info(
"Skipping deletion of failed SARIF because the workflow was triggered from a fork of " +
"codeql-action and doesn't have the appropriate permissions for deletion.",
);
}
}
// Upload appropriate Actions artifacts for debugging
if (config.debugMode) {
logger.info(
"Debug mode is on. Uploading available database bundles and logs as Actions debugging artifacts...",
);
const version = await codeql.getVersion();
await uploadAllAvailableDebugArtifacts(
codeql,
config,
logger,
version.version,
);
await printDebugLogs(config);
}
if (actionsUtil.isSelfHostedRunner()) {
try {
fs.rmSync(config.dbLocation, {
recursive: true,
force: true,
maxRetries: 3,
});
logger.info(
`Cleaned up database cluster directory ${config.dbLocation}.`,
);
} catch (e) {
logger.warning(
`Failed to clean up database cluster directory ${config.dbLocation}. Details: ${e}`,
);
}
} else {
logger.debug(
"Skipping cleanup of database cluster directory since we are running on a GitHub-hosted " +
"runner which will be automatically cleaned up.",
);
}
return uploadFailedSarifResult;
}
/**
* If overlay base database creation was attempted but the analysis did not complete
* successfully, save the failure status to the Actions cache so that subsequent runs
* can skip overlay analysis until something changes (e.g. a new CodeQL version).
*/
async function recordOverlayStatus(
codeql: CodeQL,
config: Config,
features: FeatureEnablement,
logger: Logger,
) {
if (
config.overlayDatabaseMode !== OverlayDatabaseMode.OverlayBase ||
process.env[EnvVar.ANALYZE_DID_COMPLETE_SUCCESSFULLY] === "true" ||
!(await features.getValue(Feature.OverlayAnalysisStatusSave))
) {
return;
}
const overlayStatus: OverlayStatus = {
attemptedToBuildOverlayBaseDatabase: true,
builtOverlayBaseDatabase: false,
};
const diskUsage = await checkDiskUsage(logger);
if (diskUsage === undefined) {
logger.warning(
"Unable to save overlay status to the Actions cache because the available disk space could not be determined.",
);
return;
}
const saved = await saveOverlayStatus(
codeql,
config.languages,
diskUsage,
overlayStatus,
logger,
);
const blurb =
"This job attempted to run with improved incremental analysis but it did not complete successfully. " +
"This may have been due to disk space constraints: using improved incremental analysis can " +
"require a significant amount of disk space for some repositories.";
if (saved) {
logger.error(
`${blurb} ` +
"This failure has been recorded in the Actions cache, so the next CodeQL analysis will run " +
"without improved incremental analysis. If you want to enable improved incremental analysis, " +
"increase the disk space available to the runner. " +
"If that doesn't help, contact GitHub Support for further assistance.",
);
} else {
logger.error(
`${blurb} ` +
"The attempt to save this failure status to the Actions cache failed. The Action will attempt to " +
"run with improved incremental analysis again.",
);
}
}
async function removeUploadedSarif(
uploadFailedSarifResult: UploadFailedSarifResult,
logger: Logger,
) {
const sarifID = uploadFailedSarifResult.sarifID;
if (sarifID) {
logger.startGroup("Deleting failed SARIF upload");
logger.info(
`In test mode, therefore deleting the failed analysis to avoid impacting tool status for the Action repository. SARIF ID to delete: ${sarifID}.`,
);
const client = getApiClient();
try {
const repositoryNwo = getRepositoryNwo();
// Wait to make sure the analysis is ready for download before requesting it.
await delay(5000);
// Get the analysis associated with the uploaded sarif
const analysisInfo = await client.request(
"GET /repos/:owner/:repo/code-scanning/analyses?sarif_id=:sarif_id",
{
owner: repositoryNwo.owner,
repo: repositoryNwo.repo,
sarif_id: sarifID,
},
);
// Delete the analysis.
if (analysisInfo.data.length === 1) {
const analysis = analysisInfo.data[0];
logger.info(`Analysis ID to delete: ${analysis.id}.`);
try {
await client.request(
"DELETE /repos/:owner/:repo/code-scanning/analyses/:analysis_id?confirm_delete",
{
owner: repositoryNwo.owner,
repo: repositoryNwo.repo,
analysis_id: analysis.id,
},
);
logger.info(`Analysis deleted.`);
} catch (e) {
const origMessage = getErrorMessage(e);
const newMessage = origMessage.includes(
"No analysis found for analysis ID",
)
? `Analysis ${analysis.id} does not exist. It was likely already deleted.`
: origMessage;
throw new Error(newMessage);
}
} else {
throw new Error(
`Expected to find exactly one analysis with sarif_id ${sarifID}. Found ${analysisInfo.data.length}.`,
);
}
} catch (e) {
throw new Error(
`Failed to delete uploaded SARIF analysis. Reason: ${getErrorMessage(
e,
)}`,
);
} finally {
logger.endGroup();
}
} else {
logger.warning(
"Could not delete the uploaded SARIF analysis because a SARIF ID wasn't provided by the API when uploading the SARIF file.",
);
}
}