forked from redhat-developer/vscode-openshift-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild-run-deploy.ts
More file actions
390 lines (368 loc) · 19.1 KB
/
build-run-deploy.ts
File metadata and controls
390 lines (368 loc) · 19.1 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
/*-----------------------------------------------------------------------------------------------
* Copyright (c) Red Hat, Inc. All rights reserved.
* Licensed under the MIT License. See LICENSE file in the project root for license information.
*-----------------------------------------------------------------------------------------------*/
import { EventEmitter, Terminal, Uri, commands, window } from 'vscode';
import { ClusterVersion, FunctionContent, FunctionObject, RunResponse } from './types';
import validator from 'validator';
import { ServerlessCommand, Utils } from './commands';
import { Platform } from '../util/platform';
import { OdoImpl } from '../odo';
import { CliChannel } from '../cli';
import { ChildProcess, SpawnOptions } from 'child_process';
import { ServerlessFunctionView } from './view';
import { multiStep } from './multiStepInput';
import { Progress } from '../util/progress';
export class BuildAndDeploy {
private static instance: BuildAndDeploy;
protected static readonly cli = CliChannel.getInstance();
private buildTerminalMap: Map<string, Terminal> = new Map<string, Terminal>();
public runTerminalMap: Map<string, Terminal> = new Map<string, Terminal>();
private buildEmiterMap: Map<string, EventEmitter<string>> = new Map<string, EventEmitter<string>>();
private buildPrcessMap: Map<Terminal, ChildProcess> = new Map<Terminal, ChildProcess>();
public static imageRegex = RegExp('[^/]+\\.[^/.]+\\/([^/.]+)(?:\\/[\\w\\s._-]*([\\w\\s._-]))*(?::[a-z0-9\\.-]+)?$');
static getInstance(): BuildAndDeploy {
if (!BuildAndDeploy.instance) {
BuildAndDeploy.instance = new BuildAndDeploy();
}
return BuildAndDeploy.instance;
}
checkRunning(fsPath: string): boolean {
return this.runTerminalMap.has(`run-${fsPath}`);
}
public async checkOpenShiftCluster(): Promise<ClusterVersion> {
try {
const result = await OdoImpl.Instance.execute(ServerlessCommand.getClusterVersion());
if (result?.stdout?.trim()) {
return JSON.parse(result?.stdout) as ClusterVersion;
}
return null;
} catch (err) {
return null;
}
}
public async buildFunction(context: FunctionObject): Promise<void> {
const exisitingTerminal = this.buildTerminalMap.get(`build-${context.folderURI.fsPath}`);
const outputEmitter = this.buildEmiterMap.get(`build-${context.folderURI.fsPath}`);
if (exisitingTerminal) {
let exisitingProcess = this.buildPrcessMap.get(exisitingTerminal);
void window.showWarningMessage(`Do you want to restart ${context.name} build ?`, 'Yes', 'No').then(async (value: string) => {
if (value === 'Yes') {
exisitingTerminal.show(true);
await commands.executeCommand('workbench.action.terminal.clear')
outputEmitter.fire(`Start Building ${context.name} \r\n`);
exisitingProcess.kill('SIGINT')
this.buildPrcessMap.delete(exisitingTerminal);
const clusterVersion: ClusterVersion | null = await this.checkOpenShiftCluster();
const buildImage = await this.getImage(context.folderURI);
const opt: SpawnOptions = { cwd: context.folderURI.fsPath };
void CliChannel.getInstance().spawnTool(ServerlessCommand.buildFunction(context.folderURI.fsPath, buildImage, clusterVersion), opt).then((cp) => {
exisitingProcess = cp;
this.buildPrcessMap.set(exisitingTerminal, cp);
exisitingProcess.on('error', (err) => {
void window.showErrorMessage(err.message);
});
exisitingProcess.stdout.on('data', (chunk) => {
outputEmitter.fire(`${chunk as string}`.replaceAll('\n', '\r\n'));
});
exisitingProcess.stderr.on('data', (errChunk) => {
outputEmitter.fire(`\x1b[31m${errChunk as string}\x1b[0m`.replaceAll('\n', '\r\n'));
void window.showErrorMessage(`${errChunk as string}`);
});
exisitingProcess.on('exit', () => {
context.hadBuilt = true;
ServerlessFunctionView.getInstance().refresh(context);
outputEmitter.fire('\r\nPress any key to close this terminal\r\n');
});
});
}
});
} else {
await this.buildProcess(context);
}
}
private async buildProcess(context: FunctionObject) {
const clusterVersion: ClusterVersion | null = await this.checkOpenShiftCluster();
const buildImage = await this.getImage(context.folderURI);
const outputEmitter = new EventEmitter<string>();
let devProcess: ChildProcess;
let terminal = window.createTerminal({
name: `Build ${context.name}`,
pty: {
onDidWrite: outputEmitter.event,
open: () => {
outputEmitter.fire(`Start Building ${context.name} \r\n`);
const opt: SpawnOptions = { cwd: context.folderURI.fsPath };
void CliChannel.getInstance().spawnTool(ServerlessCommand.buildFunction(context.folderURI.fsPath, buildImage, clusterVersion), opt).then((cp) => {
this.buildPrcessMap.set(terminal, cp);
devProcess = cp;
devProcess.on('spawn', () => {
terminal.show();
});
devProcess.on('error', (err) => {
void window.showErrorMessage(err.message);
});
devProcess.stdout.on('data', (chunk) => {
outputEmitter.fire(`${chunk as string}`.replaceAll('\n', '\r\n'));
});
devProcess.stderr.on('data', (errChunk) => {
outputEmitter.fire(`\x1b[31m${errChunk as string}\x1b[0m`.replaceAll('\n', '\r\n'));
});
devProcess.on('exit', () => {
context.hadBuilt = true;
ServerlessFunctionView.getInstance().refresh(context);
outputEmitter.fire('\r\nPress any key to close this terminal\r\n');
});
});
},
close: () => {
if (devProcess && devProcess.exitCode === null) { // if process is still running and user closed terminal
devProcess.kill('SIGINT');
}
this.buildTerminalMap.delete(`build-${context.folderURI.fsPath}`);
this.buildEmiterMap.delete(`build-${context.folderURI.fsPath}`);
this.buildPrcessMap.delete(terminal);
terminal = undefined;
},
handleInput: ((data: string) => {
if (!devProcess) { // if any key pressed after process ends
terminal.dispose();
} else { // ctrl+C processed only once when there is no cleaning process
outputEmitter.fire('^C\r\n');
devProcess.kill('SIGINT');
terminal.dispose();
}
})
},
});
this.buildTerminalMap.set(`build-${context.folderURI.fsPath}`, terminal);
this.buildEmiterMap.set(`build-${context.folderURI.fsPath}`, outputEmitter);
}
public runFunction(context: FunctionObject, runBuild = false) {
const outputEmitter = new EventEmitter<string>();
let runProcess: ChildProcess;
let terminal = window.createTerminal({
name: `Run ${context.name}`,
pty: {
onDidWrite: outputEmitter.event,
open: () => {
outputEmitter.fire(`Running ${context.name} \r\n`);
const opt: SpawnOptions = { cwd: context.folderURI.fsPath };
void CliChannel.getInstance().spawnTool(ServerlessCommand.runFunction(context.folderURI.fsPath, runBuild), opt).then((cp) => {
runProcess = cp;
runProcess.on('spawn', () => {
terminal.show();
});
runProcess.on('error', (err) => {
void window.showErrorMessage(err.message);
});
runProcess.stdout.on('data', (chunk) => {
outputEmitter.fire(`${chunk as string}`.replaceAll('\n', '\r\n'));
try {
const json = JSON.parse(`${chunk as string}`) as RunResponse;
if (json.msg?.indexOf('Server listening at') !== -1) {
outputEmitter.fire(`\n\n Press ctrl+C for stop running ${context.name}`);
}
} catch (err) {
// no action
}
void commands.executeCommand('openshift.Serverless.refresh');
});
runProcess.stderr.on('data', (errChunk) => {
outputEmitter.fire(`\x1b[31m${errChunk as string}\x1b[0m`.replaceAll('\n', '\r\n'));
});
runProcess.on('exit', () => {
outputEmitter.fire('\r\nPress any key to close this terminal\r\n');
});
});
},
close: () => {
if (runProcess && runProcess.exitCode === null) { // if process is still running and user closed terminal
runProcess.kill('SIGINT');
}
this.runTerminalMap.delete(`run-${context.folderURI.fsPath}`);
terminal = undefined;
void commands.executeCommand('openshift.Serverless.refresh');
},
handleInput: ((data: string) => {
if (data.charCodeAt(0) === 3 || data.charCodeAt(0) === 94) {
if (!runProcess) {
terminal.dispose();
} else {
outputEmitter.fire('^C\r\n');
runProcess.kill('SIGINT');
terminal.dispose()
}
}
})
},
});
this.runTerminalMap.set(`run-${context.folderURI.fsPath}`, terminal);
}
public stopFunction(context: FunctionObject) {
const terminal = this.runTerminalMap.get(`run-${context.folderURI.fsPath}`);
if (terminal) {
terminal.sendText('^C\r\n');
}
}
public undeployFunction(context: FunctionObject) {
void Progress.execFunctionWithProgress(`Undeploying the function ${context.name}`, async () => {
const result = await OdoImpl.Instance.execute(ServerlessCommand.undeployFunction(context.name));
if (result.error) {
void window.showErrorMessage(result.error.message);
} else {
void commands.executeCommand('openshift.Serverless.refresh');
}
});
}
public async deployFunction(context: FunctionObject) {
const currentNamespace: string = ServerlessFunctionView.getInstance().getCurrentNameSpace();
const yamlContent = await Utils.getFuncYamlContent(context.folderURI.fsPath);
if (yamlContent) {
const deployedNamespace = yamlContent.deploy?.namespace || undefined;
if (!deployedNamespace) {
await this.deployProcess(context, deployedNamespace, yamlContent);
} else if (deployedNamespace !== currentNamespace) {
const response = await window.showInformationMessage(`Function namespace (declared in func.yaml) is different from the current active namespace. Deploy function ${context.name} to namespace ${deployedNamespace}?`,
'Ok',
'Cancel');
if (response === 'Ok') {
await this.deployProcess(context, deployedNamespace, yamlContent);
}
} else {
await this.deployProcess(context, deployedNamespace, yamlContent);
}
}
}
private async deployProcess(context: FunctionObject, deployedNamespace: string, yamlContent: FunctionContent) {
if (!yamlContent.image || !BuildAndDeploy.imageRegex.test(yamlContent.image)) {
void window.showErrorMessage(`Function ${context.name} has invalid imaage`)
return;
}
const clusterVersion: ClusterVersion | null = await this.checkOpenShiftCluster();
const buildImage = await this.getImage(context.folderURI);
const outputEmitter = new EventEmitter<string>();
let deployProcess: ChildProcess;
let terminal = window.createTerminal({
name: `Deploying the function ${context.name}`,
pty: {
onDidWrite: outputEmitter.event,
open: () => {
outputEmitter.fire(`Deploying ${context.name} \r\n`);
const opt: SpawnOptions = { cwd: context.folderURI.fsPath };
void CliChannel.getInstance().spawnTool(ServerlessCommand.deployFunction(context.folderURI.fsPath, buildImage, deployedNamespace, clusterVersion), opt).then((cp) => {
deployProcess = cp;
deployProcess.on('spawn', () => {
terminal.show();
});
deployProcess.on('error', (err) => {
void window.showErrorMessage(err.message);
});
// eslint-disable-next-line @typescript-eslint/no-misused-promises
deployProcess.stdout.on('data', async (chunk) => {
const response = `${chunk as string}`.replaceAll('\n', '\r\n');
if (response.includes('Please provide credentials for image registry')) {
response.replace(/Please provide credentials for image registry/gm, '');
await this.provideUserNameAndPassword(deployProcess, 'Please provide credentials for image registry.');
}
if (response.includes('Incorrect credentials, please try again')) {
response.replace(/Incorrect credentials, please try again/gm, '');
await this.provideUserNameAndPassword(deployProcess, 'Please provide credentials for image registry.', true);
}
outputEmitter.fire(response);
});
deployProcess.stderr.on('data', (errChunk) => {
outputEmitter.fire(`\x1b[31m${errChunk as string}\x1b[0m`.replaceAll('\n', '\r\n'));
});
deployProcess.on('exit', () => {
void commands.executeCommand('openshift.Serverless.refresh');
outputEmitter.fire('\r\nPress any key to close this terminal\r\n');
});
});
},
close: () => {
if (deployProcess && deployProcess.exitCode === null) { // if process is still running and user closed terminal
deployProcess.kill('SIGINT');
}
terminal = undefined;
void commands.executeCommand('openshift.Serverless.refresh');
},
handleInput: ((_data: string) => {
if (!deployProcess) {
terminal.dispose();
} else {
outputEmitter.fire('^C\r\n');
deployProcess.kill('SIGINT');
terminal.dispose()
}
})
},
});
}
public async config(title: string, context: FunctionObject, mode: string, isAdd = true) {
await BuildAndDeploy.cli.executeInTerminal(ServerlessCommand.config(context.folderURI.fsPath, mode, isAdd),
context.folderURI.fsPath, title, process.env, true);
}
private async provideUserNameAndPassword(
process: ChildProcess,
message: string,
reattemptForLogin?: boolean,
): Promise<void> {
const userInfo = 'Provide username for image registry.';
const userName = await this.getUsernameOrPassword(
message,
userInfo,
false,
'Provide an username for image registry.',
reattemptForLogin,
);
if (!userName) {
process.stdin.end();
return null;
}
const passMessage = 'Provide password for image registry.';
const userPassword = await this.getUsernameOrPassword(message, passMessage, true, 'Provide a password for image registry.');
if (!userPassword) {
process.stdin.end();
return null;
}
process.stdin.write(`${userName}\n${userPassword}\n`);
}
private async getUsernameOrPassword(
message: string,
infoMessage: string,
passwordType?: boolean,
errorMessage?: string,
reattemptForLogin?: boolean,
): Promise<string | null> {
return multiStep.showInputBox({
title: message,
prompt: infoMessage,
placeholder: infoMessage,
reattemptForLogin,
validate: (value: string) => {
if (validator.isEmpty(value)) {
return errorMessage;
}
return null;
},
password: passwordType,
});
}
public getDefaultImages(name: string): string[] {
const imageList: string[] = [];
const defaultUsername = Platform.getEnv();
const defaultQuayImage = `quay.io/${Platform.getOS() === 'win32' ? defaultUsername.USERNAME : defaultUsername.USER}/${name}:latest`;
const defaultDockerImage = `docker.io/${Platform.getOS() === 'win32' ? defaultUsername.USERNAME : defaultUsername.USER}/${name}:latest`;
imageList.push(defaultQuayImage);
imageList.push(defaultDockerImage);
return imageList;
}
public async getImage(folderURI: Uri): Promise<string> {
const yamlContent = await Utils.getFuncYamlContent(folderURI.fsPath);
if (yamlContent?.image && BuildAndDeploy.imageRegex.test(yamlContent.image)) {
return yamlContent.image
}
return null;
}
}