-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathindex.ts
More file actions
190 lines (160 loc) · 5.44 KB
/
Copy pathindex.ts
File metadata and controls
190 lines (160 loc) · 5.44 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
import {spawn, spawnSync} 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';
import Blocker from './block';
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 alwaysCommands = [
['git', 'checkout', '--', 'package.json', 'package-lock.json', 'functions/package.json', 'functions/package-lock.json'],
['git', 'pull'],
['git', 'submodule', 'update', '--init', '--recursive'],
];
const getChangedFiles = (): string[] => {
const result = spawnSync('git', ['diff', 'ORIG_HEAD', 'HEAD', '--name-only'], {
cwd: process.cwd(),
encoding: 'utf-8',
});
return result.status === 0 ? result.stdout.split('\n').filter(Boolean) : [];
};
const buildConditionalCommands = (changedFiles: string[]): string[][] => {
const commands: string[][] = [];
if (changedFiles.includes('package-lock.json')) {
// NODE_ENV=production (loaded from .env by this app) is inherited by
// spawned npm processes, which makes npm ci skip devDependencies
// such as tsgo. Force-include them since the build step needs them.
commands.push(['npm', 'ci', '--include=dev']);
}
if (changedFiles.some((f) => f.endsWith('.rs'))) {
commands.push(['/home/slackbot/.cargo/bin/cargo', 'build', '--release', '--all']);
}
commands.push(['npm', 'run', 'build']);
return commands;
};
const collectStream = (stream: PassThrough): Promise<Buffer> => new Promise<Buffer>((resolve) => {
stream.pipe(concat({encoding: 'buffer'}, (data: Buffer) => {
resolve(data);
}));
});
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) => {
// GitHub webhook signature verification requires the raw request body string,
// so we receive JSON as a string and parse it manually in the route handler.
fastify.addContentTypeParser('application/json', {parseAs: 'string'}, (_req, body: string, done) => {
done(null, body);
});
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}),
})
);
const runCommand = async (command: string, args: string[]): Promise<void> => {
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 collectStream(muxed);
const text = `\`\`\`\n$ ${[command, ...args].join(' ')}\n${output.toString().slice(0, 3500)}\`\`\``;
await postMessage(text);
};
// eslint-disable-next-line require-await
fastify.post('/hooks/github', async (req, res) => {
const rawBody = String(req.body);
if (webhooks) {
if (await webhooks.verify(rawBody, req.headers['x-hub-signature-256'] as string) !== true) {
res.code(400);
return 'invalid signature';
}
}
const body = JSON.parse(rawBody) as Record<string, unknown>;
log.info(JSON.stringify({body, headers: req.headers}));
const name = req.headers['x-github-event'];
if (name === 'ping') {
return 'pong';
}
if (name === 'push') {
if (get(body, ['repository', 'id']) !== 105612722) {
res.code(400);
return 'repository id not match';
}
if (get(body, ['ref']) !== 'refs/heads/master') {
res.code(202);
return 'refs not match';
}
if (triggered) {
return 'already triggered';
}
triggered = true;
deployBlocker.wait(
async () => {
try {
const message = await postMessage('デプロイを開始します');
thread = message.ts as string;
for (const [command, ...args] of alwaysCommands) {
await runCommand(command, args);
}
const changedFiles = getChangedFiles();
for (const [command, ...args] of buildConditionalCommands(changedFiles)) {
await runCommand(command, args);
}
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();
}
});
});
} catch (error) {
triggered = false;
throw error;
}
},
30 * 60 * 1000, // 30min
(blocks) => {
log.info(blocks);
postMessage('デプロイがブロック中だよ:confounded:');
},
);
return 'ok';
}
res.code(501);
return 'not implemented';
});
};