-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
index.js
498 lines (462 loc) · 17.8 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
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
const { Buffer } = require('buffer');
const yaml = require('js-yaml');
const bluebird = require('bluebird');
const { sub } = require("date-fns");
const getConfigFile = async (app, context, owner) => {
app.log.info('getConfigFile>');
const repoPaths = {
'.infraway': 'config.yaml',
'charts': '.infraway/config.yaml',
};
const content = await Object.keys(repoPaths)
.reduce(async (prev, repo) => {
try {
const prevContent = await prev;
if (prevContent) {
return prevContent;
}
const { data: { content } } = await context.octokit.repos.getContent({
owner,
repo,
path: repoPaths[repo],
});
return content;
} catch (e) {
return;
}
}, Promise.resolve());
return content ? yaml.load(Buffer.from(content, 'base64').toString('utf8')) : null;
}
const getTagByCommit = async (context, owner, repo, sha) => {
const tags = await context.octokit.repos.listTags({
owner,
repo,
per_page: 200,
});
if (!tags || !tags.data) {
return null;
}
return tags.data.find(t => t.commit.sha === sha);
}
const getLatestReleaseTag = async (context, owner, repo) => {
const releases = await context.octokit.repos.listReleases({
owner,
repo,
per_page: 1,
});
if (!releases || !releases.data) {
return null;
}
const [latest] = releases.data;
return latest ? latest.tag_name : null;
}
const findOpenPullRequestNumber = async (context, owner, repo, sha) => {
const pulls = await context.octokit.repos.listPullRequestsAssociatedWithCommit({
owner,
repo,
commit_sha: sha,
});
const pr = pulls.data.length > 0 && pulls.data.find(el => el.state === 'open');
return pr ? pr.number : null;
};
const getLatestCommitInPullRequest = async (context, owner, repo, pullNumber) => {
const pull = await context.octokit.pulls.get({
owner,
repo,
pull_number: pullNumber,
});
if (!pull || !pull.data) {
return null;
}
return pull.data.head.sha;
};
const getStalePulls = async (app, context, owner) => {
app.log.info('getStalePulls>');
const {
deploy,
stale_pull_cleanup: cleanupPolicy,
} = getConfig(owner);
if (!cleanupPolicy.enabled) {
return [];
}
const duration = (cleanupPolicy.duration || '7 days').split(' ');
const filterDate = sub(new Date(), { [duration[1]]: parseInt(duration[0], 10) });
const repos = deploy.map((d) => d.name);
app.log.info(`Checking repos for stale rule: X < ${filterDate.toISOString()}`);
app.log.info(repos);
return repos.reduce(async (acc, repo) => {
const previous = await acc;
const { data: foundPulls } = await context.octokit.pulls.list({
owner,
repo,
state: 'open',
sort: 'updated',
direction: 'asc',
});
app.log.info(`Found ${foundPulls.length} pulls for repo ${repo}`);
return [
...previous,
...foundPulls
.filter((p) => new Date(p.updated_at) < filterDate)
.map((p) => ({ pullNumber: p.number, owner, repo })),
];
}, Promise.resolve([]));
}
const updatePulls = async (app, context, owner) => {
const pulls = await getStalePulls(app, context, owner);
app.log.info(`Found ${pulls.length} stale pulls`);
app.log.info(pulls);
await pulls.reduce(async (_, { owner, repo, pullNumber }) => {
app.log.info(`Cleaning up resources for stale pull: ${owner}/${repo}/pull/${pullNumber}`);
const payloads = await getDeletePayloads(context, { owner, repo, pullNumber });
await deleteDeployments(app, context, owner, payloads);
}, Promise.resolve());
}
const stalePromise = {};
const syncStale = async (app, context, owner) => {
// await updatePulls(app, context, owner);
if (!stalePromise[owner]) {
stalePromise[owner] = new Promise((resolve, reject) => {
try {
setInterval(async () => {
await updatePulls(app, context, owner);
}, 20 * 60 * 1000);
} catch (e) {
reject(e);
}
});
}
}
const configMap = {};
const configMapPromise = {};
const getConfig = (owner) => configMap[owner];
const syncConfig = async (app, context, owner) => {
if (!configMap[owner]) {
configMap[owner] = await getConfigFile(app, context, owner);
}
if (!configMapPromise[owner]) {
configMapPromise[owner] = new Promise((resolve, reject) => {
try {
setInterval(async () => {
configMap[owner] = await getConfigFile(app, context, owner);
}, 20 * 60 * 1000);
} catch (e) {
reject(e);
}
});
}
}
const sync = async (app, context, owner) => {
await syncConfig(app, context, owner);
await syncStale(app, context, owner);
};
const getDeployPayloads = async (context, { owner, repo, pullNumber, sha = '' }, components = [], action = '', logger = null) => {
const config = getConfig(owner);
const componentsMap = new Map(components.map((c) => [c.component, c]));
const domain = config.domain;
// find deploy by repo
const deploy = config.deploy.find((d) => d.name === repo);
if (!deploy) {
logger.info(`getDeployPayloads> Deploy ${deploy} cannot be found in config`);
return [];
}
const charts = (deploy.components || [])
.filter((c) => {
// no components passed meaning - deploy all
if (!components.length) {
// deploy all components which are not marked as addon=true
return !c.addon;
}
return componentsMap.get(c.name);
})
.map(({ name, chart, version, needs, addon, values }) => {
if (!chart) {
const found = deploy.components.find(({ needs = [] }) => needs.includes(name));
if (found && found.chart) {
chart = found.chart;
}
}
const versionOverwrite = componentsMap.get(name);
if (versionOverwrite && versionOverwrite.version) {
version = versionOverwrite.version;
}
return {
name, chart, version, addon, values,
};
})
.filter(({ chart }) => !!chart);
const deployPayloads = charts.reduce(async (acc, { name, version, chart, addon, values }) => {
const val = await acc;
let gitVersion;
if (!version || version === 'commit') {
version = sha || await getLatestCommitInPullRequest(context, owner, repo, pullNumber);
gitVersion = version;
version = version.substr(0, 7);
}
if (version === 'release') {
version = await getLatestReleaseTag(context, owner, name || repo);
gitVersion = version;
}
const description = `Deploy ${chart} for ${repo}/pull/${pullNumber}`;
const environment = `${repo.replace('.', '-')}-pull-${pullNumber}`;
const component = name.replace('.', '-');
return [...val, {
repo,
component,
addon,
gitVersion,
version,
chart,
description,
environment,
values: values || component,
domain: `${environment}.${domain}`,
action: 'deploy',
}];
}, Promise.resolve([]));
logger.info('getDeployPayloads> found payloads');
logger.info(JSON.stringify(deployPayloads));
return deployPayloads;
}
const getDeletePayloads = async (context, { owner, repo, pullNumber, sha }) => {
const config = getConfig(owner);
const domain = config.domain;
// find deploy by repo
const deploy = config.deploy.find((d) => d.name === repo);
if (!deploy) {
return [];
}
const description = `Delete ${repo}/pull/${pullNumber}`;
const environment = `${repo.replace('.', '-')}-pull-${pullNumber}`;
return [{
repo,
description,
environment,
domain: `${environment}.${domain}`,
action: 'delete',
}];
}
const getLockPayloads = async (context, { owner, repo, pullNumber, sha }) => {
const config = getConfig(owner);
const domain = config.domain;
// find deploy by repo
const deploy = config.deploy.find((d) => d.name === repo);
if (!deploy) {
return [];
}
const description = `Lock ${repo}/pull/${pullNumber}`;
const environment = `${repo.replace('.', '-')}-pull-${pullNumber}`;
return [{
repo,
description,
environment,
domain: `${environment}.${domain}`,
action: 'lock',
}];
}
const createDeployments = async (app, context, owner, payloads) => {
await bluebird.mapSeries(payloads, async ({ repo, component, chart, version, gitVersion, environment, description, domain, action, values, addon = false }) => {
app.log.info({ repo, component, chart, version, gitVersion, environment, description, domain, action, values });
const res = await context.octokit.repos.createDeployment({
owner: owner,
repo: 'charts',
ref: 'master', // The ref to deploy. This can be a branch, tag, or SHA.
task: 'deploy', // Specifies a task to execute (e.g., deploy or deploy:migrations).
auto_merge: false, // Attempts to automatically merge the default branch into the requested ref, if it is behind the default branch.
required_contexts: [], // The status contexts to verify against commit status checks. If this parameter is omitted, then all unique contexts will be verified before a deployment is created. To bypass checking entirely pass an empty array. Defaults to all unique contexts.
payload: {
repo, chart, version, gitVersion, component, action, domain, environment, addon, values,
}, // JSON payload with extra information about the deployment. Default: ""
environment, // Name for the target deployment environment (e.g., production, staging, qa)
description, // Short description of the deployment
transient_environment: true, // Specifies if the given environment is specific to the deployment and will no longer exist at some point in the future.
production_environment: false, // Specifies if the given environment is one that end-users directly interact with.
});
app.log.info(`Created deployment #${res.data.id} for pull request ${environment}`);
});
};
const deleteDeployments = async (app, context, owner, payloads) => {
await bluebird.mapSeries(payloads, async ({ repo, environment, description, domain, action }) => {
app.log.info({ repo, environment, description, domain, action });
const res = await context.octokit.repos.createDeployment({
owner: owner,
repo: 'charts',
ref: 'master', // The ref to deploy. This can be a branch, tag, or SHA.
task: 'delete', // Specifies a task to execute (e.g., deploy or deploy:migrations).
auto_merge: false, // Attempts to automatically merge the default branch into the requested ref, if it is behind the default branch.
required_contexts: [], // The status contexts to verify against commit status checks. If this parameter is omitted, then all unique contexts will be verified before a deployment is created. To bypass checking entirely pass an empty array. Defaults to all unique contexts.
payload: {
repo, domain, action, environment,
}, // JSON payload with extra information about the deployment. Default: ""
environment, // Name for the target deployment environment (e.g., production, staging, qa)
description, // Short description of the deployment
transient_environment: true, // Specifies if the given environment is specific to the deployment and will no longer exist at some point in the future.
production_environment: false, // Specifies if the given environment is one that end-users directly interact with.
});
app.log.info(`Created delete deployment #${res.data.id} for pull request ${environment}`);
});
// if (payloads.length === 0) {
// return;
// }
// const environment = payloads[0].environment;
// // find all deployments related to environment
// app.log.info('context.octokit.repos.listDeployments');
// app.log.info({ owner: owner, repo: 'charts', ref: 'master', environment });
// const deploymentsList = await context.octokit.repos.listDeployments({
// owner: owner,
// repo: 'charts',
// ref: 'master',
// environment,
// });
// app.log.info('deploymentsList');
// app.log.info(deploymentsList);
// const deployments = (deploymentsList && deploymentsList.data) || [];
// await bluebird.mapSeries(deployments || [], ({ id }) => context.octokit.repos.deleteDeployment({
// owner: owner,
// repo: 'charts',
// deployment_id: id,
// }),
// );
};
const lockDeployments = async (app, context, owner, payloads) => {
await bluebird.mapSeries(payloads, async ({ repo, environment, description, domain, action }) => {
app.log.info({ repo, environment, description, domain, action });
const res = await context.octokit.repos.createDeployment({
owner: owner,
repo: 'charts',
ref: 'master', // The ref to deploy. This can be a branch, tag, or SHA.
task: 'lock', // Specifies a task to execute (e.g., deploy or deploy:migrations).
auto_merge: false, // Attempts to automatically merge the default branch into the requested ref, if it is behind the default branch.
required_contexts: [], // The status contexts to verify against commit status checks. If this parameter is omitted, then all unique contexts will be verified before a deployment is created. To bypass checking entirely pass an empty array. Defaults to all unique contexts.
payload: {
repo, domain, action, environment,
}, // JSON payload with extra information about the deployment. Default: ""
environment, // Name for the target deployment environment (e.g., production, staging, qa)
description, // Short description of the deployment
transient_environment: true, // Specifies if the given environment is specific to the deployment and will no longer exist at some point in the future.
production_environment: false, // Specifies if the given environment is one that end-users directly interact with.
});
app.log.info(`Created lock deployment #${res.data.id} for pull request ${environment}`);
});
};
/**
* This is the main entrypoint to your Probot app
* @param {import('probot').Probot} app
*/
module.exports = (app) => {
app.log.info("Bot started!");
app.on(
"issue_comment.created",
async (context) => {
const {
comment: { body: comment },
repository: { owner: { login: owner }, name: repo },
} = context.payload;
if (!comment) {
app.log.info(`Missing comment body`);
return;
}
app.log.info('issue_comment.created');
app.log.info(context.payload);
const pullNumber = context.payload.issue.html_url.indexOf('/pull/')
? context.payload.issue.number : null;
if (!pullNumber) {
app.log.info('Cannot find pull request. Command dismissed.');
return;
}
// lock flow
const commandLockRegex = /^[\\\|\/\#]lock([^$]*)$/;
if ((comment.toLowerCase().match(commandLockRegex))) {
await sync(app, context, owner);
const payloads = await getLockPayloads(
context, { owner, repo, pullNumber }
);
await lockDeployments(app, context, owner, payloads);
return;
}
// deploy flow
let matched;
const commandDeployRegex = /^[\\\|\/\#]deploy([^$]*)$/;
if ((matched = comment.toLowerCase().match(commandDeployRegex))) {
await sync(app, context, owner);
const components = matched[1]
.split(/\s|\n/)
.filter(Boolean)
.map((component) => {
const parts = component.split(':');
return {
component: parts[0],
version: parts[1],
};
});
app.log.info('extracted comment components');
app.log.info(JSON.stringify(components));
const payloads = await getDeployPayloads(
context, { owner, repo, pullNumber }, components, 'comment', app.log,
);
await createDeployments(app, context, owner, payloads);
}
},
);
app.on(
"push",
async (context) => {
const {
context: ctx,
head_commit: { id: sha },
repository: { owner: { login: owner }, name: repo },
} = context.payload;
app.log.info('push');
app.log.info({ owner, repo, sha, ctx });
await sync(app, context, owner);
const config = getConfig(owner);
const { commit: commitEvent } = config.events || { commit: 'deploy' };
if (commitEvent === 'ignore') {
return;
}
const pullNumber = await findOpenPullRequestNumber(context, owner, repo, sha);
if (!pullNumber) {
app.log.debug(`Open pull request for sha ${sha} cannot be find. Deploy dismissed.`);
return;
}
const payloads = await getDeployPayloads(
context, { owner, repo, pullNumber, sha }, [],'push', app.log,
);
await createDeployments(app, context, owner, payloads);
},
);
app.on(
"pull_request",
async (context) => {
const {
context: ctx,
pull_request: { number: pullNumber },
repository: { owner: { login: owner }, name: repo },
action,
} = context.payload;
if (!pullNumber) {
app.log.info(`Close pull request cannot be found. Delete dismissed.`);
return;
}
app.log.info(`pull_request.${action}`);
app.log.info({ owner, repo, ctx, pullNumber });
await sync(app, context, owner);
const config = getConfig(owner);
const { [`pull_request_${action}`]: prEvent } = config.events || { [`pull_request_${action}`]: 'deploy' };
if (prEvent === 'ignore') {
return;
}
if (['opened', 'reopened'].includes(action)) {
const payloads = await getDeployPayloads(
context, { owner, repo, pullNumber }, [],'pull_request', app.log,
);
await createDeployments(app, context, owner, payloads);
}
if (['closed', 'merged'].includes(action)) {
app.log.info(`Action on pull request. But action ${action} is not appropriate. Skipping...`);
const payloads = await getDeletePayloads(context, { owner, repo, pullNumber });
await deleteDeployments(app, context, owner, payloads);
}
},
);
};