forked from elastic/elastic-charts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuildkite.ts
More file actions
400 lines (349 loc) · 9.92 KB
/
buildkite.ts
File metadata and controls
400 lines (349 loc) · 9.92 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
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import axios from 'axios';
import { getBuildkiteEnv, getMetadata, setMetadata, metadataExists } from 'buildkite-agent-node';
import { ECH_CHECK_ID } from './constants';
import { exec } from './exec';
export const uploadPipeline = async (pipelineContent: any) => {
const str = typeof pipelineContent === 'string' ? pipelineContent : JSON.stringify(pipelineContent);
if (process.env.TEST_BK_PIPELINE) {
console.log(JSON.stringify(JSON.parse(str), null, 2));
return;
}
if (process.env.DEBUG_PIPELINE) {
console.log(JSON.stringify(JSON.parse(str), null, 2));
}
await exec('buildkite-agent pipeline upload', {
input: str,
});
};
/**
* Buildkite environment variables
*
* TODO clean this up with new custom API env build variables
*/
export const bkEnv = (() => {
const { pullRequest: _, branch: bkBranch, ...env } = getBuildkiteEnv();
const branch = bkBranch && bkBranch.split(':').reverse()[0];
const pullRequestNumber = getEnvNumber('BUILDKITE_PULL_REQUEST');
const checkId = getEnvString(ECH_CHECK_ID);
const isPullRequest = false && Boolean(pullRequestNumber);
let username: string | undefined;
if (isPullRequest) {
const userRE = /^\b(?:git|https)\b:\/\/github\.com\/([^#./]+)\/[^#./]+\.git$/;
const [, repoOwner] = userRE.exec(env.pullRequestRepo ?? '') ?? [];
if (repoOwner !== 'elastic') {
username = repoOwner;
}
}
return {
...env,
/**
* Step context for commit status
*/
branch,
checkId,
username,
isPullRequest,
isMainBranch: branch === 'main',
pullRequestNumber,
buildUrl: env.buildUrl,
canModifyPR: process.env.GITHUB_PR_MAINTAINER_CAN_MODIFY === 'true',
jobUrl: env.jobId ? `${env.buildUrl}#${env.jobId}` : undefined,
steps: {
playwright: {
updateScreenshots: isPullRequest ? process.env.ECH_STEP_PLAYWRIGHT_UPDATE_SCREENSHOTS === 'true' : false,
},
},
};
})();
/**
* Creates start of group in job logs
* https://buildkite.com/docs/pipelines/managing-log-output
*/
export const startGroup = (msg: string) => console.log(`--- ${msg}`);
export const downloadArtifacts = async (query: string, step?: string, destination = '.', build?: string) => {
startGroup(`Downloading artifacts${step ? ` from step: ${step}` : ''}`);
const dest = destination.endsWith('/') || destination === '.' ? destination : `${destination}/`;
const stepArg = step ? ` --step ${step}` : '';
const q = query.includes('*') ? `"${query}"` : query;
const buildId = build ?? bkEnv.buildId;
await exec(`buildkite-agent artifact download ${q} ${dest}${stepArg} --build ${buildId}`);
};
export const searchArtifacts = async (query: string, step?: string, destination = '.', build?: string) => {
startGroup(`Searching artifacts${step ? ` from step: ${step}` : ''}`);
const dest = destination.endsWith('/') || destination === '.' ? destination : `${destination}/`;
const stepArg = step ? ` --step ${step}` : '';
const q = query.includes('*') ? `"${query}"` : query;
const buildId = build ?? bkEnv.buildId;
await exec(`buildkite-agent artifact search ${q} ${dest}${stepArg} --build ${buildId}`);
};
export const uploadArtifacts = async (query: string) => {
const q = query.includes('*') ? `"${query}"` : query;
startGroup(`Uploading artifacts matching "${q}"`);
await exec(`buildkite-agent artifact upload ${q}`);
};
function getEnvNumber(key: string) {
const stringValue = getEnvString(key);
if (stringValue === undefined) {
return undefined;
}
const value = parseInt(stringValue);
return Number.isNaN(value) ? undefined : value;
}
function getEnvString(key: string) {
const value = process.env[key];
return value && value !== '' ? value : undefined;
}
/**
* Makes request to buildkite graphQL api
*/
export async function buildkiteGQLQuery<Response = any>(query: string) {
const { data } = await axios.post<Response>(
'https://graphql.buildkite.com/v1',
{ query },
{
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${process.env.BUILDKITE_TOKEN}`,
},
},
);
return data;
}
export const getJobMetadata = async (prop: string, required: boolean = false) => {
const key = `${bkEnv.jobId}__${prop}`;
if (required && !(await metadataExists(key))) {
throw new Error(`Failed to find metaData key for "${key}"`);
}
const value = await getMetadata(key);
console.log(`Found metaData value [${key}] -> ${value}`);
return value;
};
export const setJobMetadata = async (prop: string, value: string) => {
const key = `${bkEnv.jobId}__${prop}`;
await setMetadata(key, value);
console.log(`Set metaData value [${key}] -> ${value}`);
};
interface JobStep {
passed: boolean;
url: string | null;
state: JobState;
key: string;
}
interface PreviousDeployCommitShaResponse {
data: {
pipeline: {
builds: {
edges: [
{
node: {
commit: string;
jobs: {
edges: [
{
node: {
passed: boolean;
};
},
];
};
};
},
];
};
};
};
}
/**
* Returns previously successful firebase deploy commit sha for the current branch
*/
export async function getPreviousDeployCommitSha(): Promise<string | null> {
const { data } = await buildkiteGQLQuery<PreviousDeployCommitShaResponse>(`query getPreviousDeployCommitSha {
pipeline(slug: "${bkEnv.organizationSlug}/${bkEnv.pipelineSlug}") {
builds(first: 1, branch: "${bkEnv.branch}", state: PASSED) {
edges {
node {
commit
jobs(first: 1, step: { key: "deploy_fb" }, state: FINISHED) {
edges {
node {
... on JobTypeCommand {
passed
}
}
}
}
}
}
}
}
}`);
const { commit, jobs } = data?.pipeline?.builds?.edges?.[0]?.node ?? {};
return jobs?.edges?.[0]?.node?.passed ? commit : null;
}
export async function getBuildJobs(stepKey?: string): Promise<JobStep[]> {
const buildId = bkEnv.buildId;
if (!buildId) throw new Error(`Error: no job id found [${buildId}]`);
const jobQuery = stepKey ? `first: 100, step: { key: "${stepKey}" }` : 'first: 100';
const { data } = await buildkiteGQLQuery<BuildJobsResponse>(`query getBuildJobs {
build(uuid: "${buildId}") {
jobs(${jobQuery}) {
edges {
node {
... on JobTypeCommand {
passed
state
url
step {
key
}
}
}
}
}
}
}`);
return (
data?.build?.jobs?.edges.map(
({
node: {
step: { key },
...rest
},
}) => ({ ...rest, key }),
) ?? []
);
}
interface BuildJobsResponse {
data: {
build: {
jobs: {
edges: {
node: {
passed: boolean;
url: string | null;
state: JobState;
step: {
key: string;
};
};
}[];
};
};
};
}
export const enum JobState {
/**
* The job has just been created and doesn't have a state yet
*/
Pending = 'PENDING',
/**
* The job is waiting on a wait step to finish
*/
Waiting = 'WAITING',
/**
* The job was in a WAITING state when the build failed
*/
WaitingFailed = 'WAITING_FAILED',
/**
* The job is waiting on a block step to finish
*/
Blocked = 'BLOCKED',
/**
* The job was in a BLOCKED state when the build failed
*/
BlockedFailed = 'BLOCKED_FAILED',
/**
* This block job has been manually unblocked
*/
Unblocked = 'UNBLOCKED',
/**
* This block job was in an UNBLOCKED state when the build failed
*/
UnblockedFailed = 'UNBLOCKED_FAILED',
/**
* The job is waiting on a concurrency group check before becoming either LIMITED or SCHEDULED
*/
Limiting = 'LIMITING',
/**
* The job is waiting for jobs with the same concurrency group to finish
*/
Limited = 'LIMITED',
/**
* The job is scheduled and waiting for an agent
*/
Scheduled = 'SCHEDULED',
/**
* The job has been assigned to an agent, and it's waiting for it to accept
*/
Assigned = 'ASSIGNED',
/**
* The job was accepted by the agent, and now it's waiting to start running
*/
Accepted = 'ACCEPTED',
/**
* The job is runing
*/
Running = 'RUNNING',
/**
* The job has finished
*/
Finished = 'FINISHED',
/**
* The job is currently canceling
*/
Canceling = 'CANCELING',
/**
* The job was canceled
*/
Canceled = 'CANCELED',
/**
* The job is timing out for taking too long
*/
TimingOut = 'TIMING_OUT',
/**
* The job timed out
*/
TimedOut = 'TIMED_OUT',
/**
* The job was skipped
*/
Skipped = 'SKIPPED',
/**
* The jobs configuration means that it can't be run
*/
Broken = 'BROKEN',
/**
* The job expired before it was started on an agent
*/
Expired = 'EXPIRED',
}
export const jobStateMapping: Record<JobState, string> = {
PENDING: 'Pending',
WAITING: 'Waiting',
WAITING_FAILED: 'Waiting Failed',
BLOCKED: 'Blocked',
BLOCKED_FAILED: 'Blocked Failed',
UNBLOCKED: 'Unblocked',
UNBLOCKED_FAILED: 'Unblocked Failed',
LIMITING: 'Limiting',
LIMITED: 'Limited',
SCHEDULED: 'Scheduled',
ASSIGNED: 'Assigned',
ACCEPTED: 'Accepted',
RUNNING: 'Running',
FINISHED: 'Finished',
CANCELING: 'Canceling',
CANCELED: 'Canceled',
TIMING_OUT: 'TimingOut',
TIMED_OUT: 'TimedOut',
SKIPPED: 'Skipped',
BROKEN: 'Broken',
EXPIRED: 'Expired',
};