-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathindex.ts
144 lines (122 loc) · 3.94 KB
/
index.ts
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
import {spawn} from 'child_process';
import os from 'os';
import {PassThrough} from 'stream';
import {Webhooks} from '@octokit/webhooks';
import concat from 'concat-stream';
import {FastifyInstance} from 'fastify';
import {get} from 'lodash';
import pm2 from 'pm2';
import logger from '../lib/logger';
import type {SlackInterface} from '../lib/slack';
// @ts-expect-error
import Blocker from './block.js';
const log = logger.child({bot: 'deploy'});
const webhooks = process.env.GITHUB_WEBHOOK_SECRET ? new Webhooks({
secret: process.env.GITHUB_WEBHOOK_SECRET,
}) : null;
if (process.env.NODE_ENV === 'production' && !webhooks) {
log.warn('[INSECURE] GitHub webhook endpoint is not protected');
}
const commands = [
['git', 'checkout', '--', 'package.json', 'package-lock.json', 'functions/package.json', 'functions/package-lock.json'],
['git', 'pull'],
['git', 'submodule', 'update', '--init', '--recursive'],
['npm', 'install', '--production', '--build-from-source'],
['/home/slackbot/.cargo/bin/cargo', 'build', '--release', '--all'],
];
const deployBlocker = new Blocker();
export const blockDeploy = (name: string) => deployBlocker.block(name);
// eslint-disable-next-line require-await
export const server = ({webClient: slack}: SlackInterface) => async (fastify: FastifyInstance) => {
let triggered = false;
let thread: string = null;
const postMessage = (text: string) => (
slack.chat.postMessage({
username: `tsgbot-deploy [${os.hostname()}]`,
channel: process.env.CHANNEL_SANDBOX,
text,
...(thread === null ? {} : {thread_ts: thread}),
})
);
// eslint-disable-next-line require-await
fastify.post('/hooks/github', async (req, res) => {
if (webhooks) {
if (await webhooks.verify(req.body as any, req.headers['x-hub-signature-256'] as string) !== true) {
res.code(400);
return 'invalid signature';
}
}
log.info(JSON.stringify({body: req.body, headers: req.headers}));
const name = req.headers['x-github-event'];
if (name === 'ping') {
return 'pong';
}
if (name === 'push') {
if (get(req.body, ['repository', 'id']) !== 105612722) {
res.code(400);
return 'repository id not match';
}
if (get(req.body, ['ref']) !== 'refs/heads/master') {
res.code(202);
return 'refs not match';
}
if (triggered) {
return 'already triggered';
}
triggered = true;
deployBlocker.wait(
async () => {
const message = await postMessage('デプロイを開始します');
thread = message.ts as string;
for (const [command, ...args] of commands) {
const proc = spawn(command, args, {cwd: process.cwd()});
const muxed = new PassThrough();
proc.stdout.on('data', (chunk) => muxed.write(chunk));
proc.stderr.on('data', (chunk) => muxed.write(chunk));
Promise.all([
new Promise<void>((resolve) => proc.stdout.on('end', () => resolve())),
new Promise<void>((resolve) => proc.stderr.on('end', () => resolve())),
]).then(() => {
muxed.end();
});
const output = await new Promise<Buffer>((resolve) => {
muxed.pipe(concat({encoding: 'buffer'}, (data: Buffer) => {
resolve(data);
}));
});
const text = `\`\`\`\n$ ${[command, ...args].join(' ')}\n${output.toString().slice(0, 3500)}\`\`\``;
await postMessage(text);
}
await new Promise<void>((resolve, reject) => {
pm2.connect((error) => {
if (error) {
reject(error);
} else {
resolve();
}
});
});
thread = null;
await postMessage('死にます:wave:');
await new Promise<void>((resolve, reject) => {
pm2.restart('app', (error) => {
if (error) {
reject(error);
} else {
resolve();
}
});
});
},
30 * 60 * 1000, // 30min
(blocks: any) => {
log.info(blocks);
postMessage('デプロイがブロック中だよ:confounded:');
},
);
return 'ok';
}
res.code(501);
return 'not implemented';
});
};