-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathdeploy.ts
359 lines (333 loc) · 9.32 KB
/
deploy.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
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
import * as parser from 'docker-file-parser';
import * as path from 'path';
import { logError, readFile, run } from './utils';
interface INowJSON {
name?: string;
files?: string[];
alias?: string[];
}
interface IDeployment {
metadata: {
generation: number;
};
spec: {
template: {
spec: {
containers: [{
image: string;
}];
};
};
};
}
function verifyNowJSON({alias, name}: INowJSON): Promise<void> {
if (!name) {
const msg = 'Specify a "name" (string) property in now.json';
logError(msg);
return Promise.reject();
}
if (!alias) {
const msg = 'Specify an "alias" (string[]) property in now.json';
logError(msg);
return Promise.reject();
}
return Promise.resolve();
}
function getDockerfilePort(commands: parser.CommandEntry[]): Promise<string> {
let dockerFilePort: string | undefined;
commands.forEach(({args, name}) => {
if (name !== 'EXPOSE') {
return;
}
console.log('args is', args);
if (typeof args === 'string') {
const port = args.match(/\d/g);
if (port) {
dockerFilePort = port.join('');
}
} else if (Array.isArray(args)) {
const argsAsString = args.join(' ');
const port = argsAsString.match(/\d/g);
if (port) {
dockerFilePort = port.join('');
}
}
});
if (!dockerFilePort) {
return Promise.reject();
}
return Promise.resolve(dockerFilePort);
}
export default async () => {
// Verify we have a Dockerfile
let dockerFile: parser.CommandEntry[];
const dockerFilePath = path.resolve(process.cwd(), 'Dockerfile');
try {
const content = await readFile(dockerFilePath);
dockerFile = parser.parse(content.toString());
} catch (error) {
const msg = `Error finding Dockerfile.\n${error.message}`;
logError(msg);
return;
}
// Verify we have a well-formatted now.json file
const nowFilePath = path.resolve(process.cwd(), 'now.json');
let nowConfig;
try {
const nowFile = await readFile(nowFilePath);
nowConfig = JSON.parse(nowFile.toString());
} catch (error) {
const msg = `Error reading now.json.\n${error.message}`;
logError(msg);
return;
}
verifyNowJSON(nowConfig);
const {name, files} = nowConfig;
// Get revision number.
let deployment: IDeployment | undefined;
let revision: number;
try {
// See if we have a deployment.
const {stdout: deploymentStr} = await run(`kubectl get deployments/${name} -o json`);
// Deployment exists. Update it.
deployment = JSON.parse(deploymentStr);
const {metadata: {generation}} : IDeployment = JSON.parse(deploymentStr);
revision = generation + 1;
} catch (e) {
// No deployment exists.
revision = 1;
}
// Create a volume for persisting the build context
const pvcName = `${name}-buildctx`;
await run(`
cat <<EOF | kubectl create -f -
{
"kind": "PersistentVolumeClaim",
"apiVersion": "v1",
"metadata": {
"name": "${pvcName}"
},
"spec": {
"accessModes": [
"ReadWriteOnce"
],
"volumeMode": "Filesystem",
"resources": {
"requests": {
"storage": "1Gi"
}
}
}
}
\nEOF`);
// Create a pod for uploading the build context
const uploadPodPrefix = `${name}-bctx`;
const podName = `${uploadPodPrefix}-pod`;
const contName = `${uploadPodPrefix}-cont`;
await run(`
cat <<EOF | kubectl create -f -
{
"kind": "Pod",
"apiVersion": "v1",
"metadata": {
"name": "${podName}"
},
"spec": {
"volumes": [
{
"name": "storage",
"persistentVolumeClaim": {
"claimName": "${pvcName}"
}
}
],
"containers": [
{
"name": "${contName}",
"image": "alpine",
"args": [
"sh",
"-c",
"while true; do sleep 1; if [ -f /tmp/complete ]; then break; fi done"
],
"volumeMounts": [
{
"mountPath": "/kaniko/build-context",
"name": "storage"
}
]
}
]
}
}
\nEOF`);
// Create build context tarball.
await run(`tar cvfz buildcontext.tar.gz Dockerfile ${files.join(' ')}`);
// Wait for pod to be ready.
await run(`kubectl wait pods/${podName} --timeout=${2 * 60}s --for condition=Ready`);
// Copy build context to container
await run(`kubectl cp -c ${contName} buildcontext.tar.gz ${podName}:/tmp/buildcontext.tar.gz`);
// Untar the build context
await run(`kubectl exec ${podName} -c ${contName} -- tar -zxf /tmp/buildcontext.tar.gz -C /kaniko/build-context`);
// Mark the upload process as complete
await run(`kubectl exec ${podName} -c ${contName} -- touch /tmp/complete`);
// Delete the pod so we can attach the PVC to a new pod
await run(`kubectl delete pod/${podName}`);
// Get Docker Registry IP Address
const {stdout: dockerIP} = await run('kubectl get service/docker-registry -o jsonpath={.spec.clusterIP}');
// Create an image and push it to the registry.
const kanikoJobName = `${podName}-kaniko`;
const imageName = `${dockerIP}:5000/${name}:${revision}`;
await run(`
cat <<EOF | kubectl create -f -
{
"apiVersion": "batch/v1",
"kind": "Job",
"metadata": {
"name": "${kanikoJobName}"
},
"spec": {
"template": {
"spec": {
"restartPolicy": "Never",
"volumes": [
{
"name": "docker-config",
"secret": {
"secretName": "regcred",
"items": [
{
"key": ".dockerconfigjson",
"path": "config.json"
}
]
}
},
{
"name": "storage",
"persistentVolumeClaim": {
"claimName": "${pvcName}"
}
}
],
"containers": [
{
"name": "kaniko",
"image": "gcr.io/kaniko-project/executor:v0.7.0",
"args": [
"--context=dir:///kaniko/build-context",
"--destination=${imageName}",
"--skip-tls-verify"
],
"volumeMounts": [
{
"name": "storage",
"mountPath": "/kaniko/build-context"
},
{
"name": "docker-config",
"mountPath": "/kaniko/.docker"
}
]
}
]
}
}
}
}
\nEOF`);
// Wait for Kaniko to complete / push to Docker registry.
await run(`kubectl wait jobs/${kanikoJobName} --timeout=${15 * 60}s --for=condition=complete`);
// Cleanup
// Delete kaniko pod and PVC.
await run(`kubectl delete jobs/${kanikoJobName}`);
await run(`kubectl delete pvc/${pvcName}`);
// Create or update the deployment API object.
// Inspect dockerfile to find port.
let dockerFilePort : string;
try {
dockerFilePort = await getDockerfilePort(dockerFile);
} catch (e) {
logError('Could not find port in Dockerfile. Did you define an EXPOSE command?');
return;
}
if (!deployment) {
// No deployment exists. Create one.
await run(`
cat <<EOF | kubectl create -f -
{
"apiVersion": "extensions/v1beta1",
"kind": "Deployment",
"metadata": {
"name": "${name}"
},
"spec": {
"template": {
"metadata": {
"labels": {
"app": "${name}"
}
},
"spec": {
"containers": [
{
"name": "${name}",
"image": "${imageName}",
"ports": [
{
"name": "app-port",
"containerPort": ${dockerFilePort}
}
]
}
],
"imagePullSecrets": [
{
"name": "regcred"
}
]
}
}
}
}
\nEOF`);
} else {
// Deployment exists. Patch it.
const {spec: deploymentSpec} = deployment;
deploymentSpec.template.spec.containers[0].image = imageName;
const deploymentPatchString = JSON.stringify({spec: deploymentSpec});
await run(`kubectl patch deployment/${name} --patch '${deploymentPatchString}'`);
}
// See if service object exists.
try {
await run(`kubectl get services/${name} -o json`);
// Service object exists-- it does not need to be patched. Continue.
} catch (e) {
// No service object exists. Create one.
await run(`
cat <<EOF | kubectl create -f -
{
"apiVersion": "v1",
"kind": "Service",
"metadata": {
"name": "${name}",
"labels": {
"app": "${name}"
}
},
"spec": {
"type": "NodePort",
"selector": {
"app": "${name}"
},
"ports": [
{
"port": 8080,
"targetPort": "app-port"
}
]
}
}
\nEOF`);
}
};