forked from redhat-developer/vscode-openshift-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomponent.ts
More file actions
862 lines (753 loc) · 45.6 KB
/
component.ts
File metadata and controls
862 lines (753 loc) · 45.6 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
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
/*-----------------------------------------------------------------------------------------------
* Copyright (c) Red Hat, Inc. All rights reserved.
* Licensed under the MIT License. See LICENSE file in the project root for license information.
*-----------------------------------------------------------------------------------------------*/
/* eslint-disable @typescript-eslint/no-var-requires */
import { window, commands, QuickPickItem, Uri, workspace, ExtensionContext, debug, DebugConfiguration, extensions, ProgressLocation, DebugSession, Disposable } from 'vscode';
import { ChildProcess , exec } from 'child_process';
import { isURL } from 'validator';
import { EventEmitter } from 'events';
import OpenShiftItem, { selectTargetApplication, selectTargetComponent } from './openshiftItem';
import { OpenShiftObject, ContextType, OpenShiftObjectImpl } from '../odo';
import { Command } from "../odo/command";
import { Progress } from '../util/progress';
import { CliExitData } from '../cli';
import { Refs, Ref, Type } from '../util/refs';
import { Delayer } from '../util/async';
import { Platform } from '../util/platform';
import { selectWorkspaceFolder } from '../util/workspace';
import { ToolsConfig } from '../tools';
import { Catalog } from './catalog';
import LogViewLoader from '../view/log/LogViewLoader';
import DescribeViewLoader from '../view/describe/describeViewLoader';
import { vsCommand, VsCommandError } from '../vscommand';
import { SourceType } from '../odo/config';
import path = require('path');
import globby = require('globby');
import treeKill = require('tree-kill');
const waitPort = require('wait-port');
export class Component extends OpenShiftItem {
private static extensionContext: ExtensionContext;
private static debugSessions = new Map<string, DebugSession>();
private static watchSessions = new Map<string, ChildProcess>();
private static readonly watchEmitter = new EventEmitter();
public static onDidWatchStarted(listener: (event: OpenShiftObjectImpl) => void): void {
Component.watchEmitter.on('watchStarted', listener);
}
public static onDidWatchStopped(listener: (event: OpenShiftObjectImpl) => void): void {
Component.watchEmitter.on('watchStopped', listener);
}
public static init(context: ExtensionContext): Disposable[] {
Component.extensionContext = context;
return [
debug.onDidStartDebugSession((session) => {
if (session.configuration.contextPath) {
Component.debugSessions.set(session.configuration.contextPath.fsPath, session);
}
}),
debug.onDidTerminateDebugSession((session) => {
if (session.configuration.contextPath) {
Component.debugSessions.delete(session.configuration.contextPath.fsPath);
}
if (session.configuration.odoPid) {
treeKill(session.configuration.odoPid);
}
})
];
}
static stopDebugSession(component: OpenShiftObject): void {
const ds = Component.debugSessions.get(component.contextPath.fsPath);
if (ds) {
treeKill(ds.configuration.odoPid);
}
}
static stopWatchSession(component: OpenShiftObject): void {
const ws = Component.watchSessions.get(component.contextPath.fsPath);
if (ws) {
treeKill(ws.pid);
}
}
static async getOpenshiftData(context: OpenShiftObject): Promise<OpenShiftObject> {
return Component.getOpenShiftCmdData(context,
"In which Application you want to create a Component"
);
}
@vsCommand('openshift.component.create')
@selectTargetApplication(
"In which Application you want to create a Component"
)
static async create(application: OpenShiftObject): Promise<string> {
if (!application) return null;
const sourceTypes: QuickPickItem[] = [
{
label: 'Git Repository',
description: 'Use an existing git repository as a source for the Component'
},
{
label: 'Binary File',
description: 'Use binary file as a source for the Component'
},
{
label: 'Workspace Directory',
description: 'Use workspace directory as a source for the Component'
}
];
const componentSource = await window.showQuickPick(sourceTypes, {
placeHolder: "Select source type for Component",
ignoreFocusOut: true
});
if (!componentSource) return null;
let command: Promise<string>;
if (componentSource.label === 'Git Repository') {
command = Component.createFromGit(application);
} else if (componentSource.label === 'Binary File') {
command = Component.createFromBinary(application);
} else if (componentSource.label === 'Workspace Directory') {
command = Component.createFromLocal(application);
}
return command.catch((err) => Promise.reject(new VsCommandError(`Failed to create Component with error '${err}'`)));
}
@vsCommand('openshift.component.delete', true)
@selectTargetComponent(
"From which Application you want to delete Component",
"Select Component to delete"
)
static async del(component: OpenShiftObject): Promise<string> {
if (!component) return null;
const name: string = component.getName();
const value = await window.showWarningMessage(`Do you want to delete Component '${name}'?`, 'Yes', 'Cancel');
if (value === 'Yes') {
return Progress.execFunctionWithProgress(`Deleting the Component '${component.getName()} '`, async () => {
if (component.contextValue === ContextType.COMPONENT_NO_CONTEXT || component.contextValue === ContextType.COMPONENT_PUSHED) {
await Component.unlinkAllComponents(component);
}
Component.stopDebugSession(component);
Component.stopWatchSession(component);
await Component.odo.deleteComponent(component);
}).then(() => `Component '${name}' successfully deleted`)
.catch((err) => Promise.reject(new VsCommandError(`Failed to delete Component with error '${err}'`)));
}
}
@vsCommand('openshift.component.undeploy', true)
@selectTargetComponent(
"From which Application you want to undeploy Component",
"Select Component to undeploy",
(target) => target.contextValue === ContextType.COMPONENT_PUSHED
)
static async undeploy(component: OpenShiftObject): Promise<string> {
if (!component) return null;
const name: string = component.getName();
const value = await window.showWarningMessage(`Do you want to undeploy Component '${name}'?`, 'Yes', 'Cancel');
if (value === 'Yes') {
return Progress.execFunctionWithProgress(`Undeploying the Component '${component.getName()} '`, async () => {
Component.stopDebugSession(component);
Component.stopWatchSession(component);
await Component.odo.undeployComponent(component);
}).then(() => `Component '${name}' successfully undeployed`)
.catch((err) => Promise.reject(new VsCommandError(`Failed to undeploy Component with error '${err}'`)));
}
}
static async getLinkPort(component: OpenShiftObject, compName: string): Promise<any> {
const compData = await Component.odo.execute(Command.describeComponentNoContextJson(component.getParent().getParent().getName(), component.getParent().getName(), compName), component.contextPath ? component.contextPath.fsPath : Platform.getUserHomePath());
return JSON.parse(compData.stdout);
}
static async unlinkAllComponents(component: OpenShiftObject): Promise<void> {
const linkComponent = await Component.getLinkData(component);
const getLinkComponent = linkComponent.status.linkedComponents;
if (getLinkComponent) {
// eslint-disable-next-line no-restricted-syntax
for (const key of Object.keys(getLinkComponent)) {
// eslint-disable-next-line no-await-in-loop
const getLinkPort = await Component.getLinkPort(component, key);
const ports = getLinkPort.status.linkedComponents[component.getName()];
if (ports) {
// eslint-disable-next-line no-restricted-syntax
for (const port of ports) {
// eslint-disable-next-line no-await-in-loop
await Component.odo.execute(Command.unlinkComponents(component.getParent().getParent().getName(), component.getParent().getName(), key, component.getName(), port), component.contextPath.fsPath);
}
}
}
}
}
static isUsingWebviewEditor(): boolean {
return workspace
.getConfiguration('openshiftConnector')
.get<boolean>('useWebviewInsteadOfTerminalView');
}
@vsCommand('openshift.component.describe', true)
@selectTargetComponent(
"From which Application you want to describe Component",
"Select Component you want to describe"
)
static describe(component: OpenShiftObject): Promise<string> {
if (!component) return null;
const command = (component.contextValue === ContextType.COMPONENT_NO_CONTEXT) ? Command.describeComponentNoContext : Command.describeComponent;
if (Component.isUsingWebviewEditor()) {
DescribeViewLoader.loadView(`${component.path} Describe`, command, component);
} else {
Component.odo.executeInTerminal(
command(component.getParent().getParent().getName(),
component.getParent().getName(),
component.getName()),
component.contextPath.fsPath,
`OpenShift: Describe '${component.getName()}' Component`);
}
}
@vsCommand('openshift.component.log', true)
@selectTargetComponent(
"In which Application you want to see Log",
"For which Component you want to see Log",
(value: OpenShiftObject) => value.contextValue === ContextType.COMPONENT_PUSHED
)
static log(component: OpenShiftObject): Promise<string> {
if (!component) return null;
if (Component.isUsingWebviewEditor()) {
LogViewLoader.loadView(`${component.path} Log`, Command.showLog, component);
} else {
Component.odo.executeInTerminal(
Command.showLog(),
component.contextPath.fsPath,
`OpenShift: Show '${component.getName()}' Component Log`);
}
}
@vsCommand('openshift.component.followLog', true)
@selectTargetComponent(
"In which Application you want to follow Log",
"For which Component you want to follow Log",
(value: OpenShiftObject) => value.contextValue === ContextType.COMPONENT_PUSHED
)
static followLog(component: OpenShiftObject): Promise<string> {
if (!component) return null;
if (Component.isUsingWebviewEditor()) {
LogViewLoader.loadView(`${component.path} Follow Log`, Command.showLogAndFollow, component);
} else {
Component.odo.executeInTerminal(
Command.showLogAndFollow(),
component.contextPath.fsPath,
`OpenShift: Follow '${component.getName()}' Component Log`);
}
}
static async getLinkData(component: OpenShiftObject): Promise<any> {
const compData = await Component.odo.execute(Command.describeComponentNoContextJson(component.getParent().getParent().getName(), component.getParent().getName(), component.getName()), component.contextPath ? component.contextPath.fsPath : Platform.getUserHomePath());
return JSON.parse(compData.stdout);
}
@vsCommand('openshift.component.unlink')
static async unlink(context: OpenShiftObject): Promise<string | null> {
const unlinkActions = [
{
label: 'Component',
description: 'Unlink Component'
},
{
label: 'Service',
description: 'Unlink Service'
}
];
const unlinkActionSelected = await window.showQuickPick(unlinkActions, {placeHolder: 'Select an option', ignoreFocusOut: true});
if (!unlinkActionSelected) return null;
let result = null;
if (unlinkActionSelected.label === 'Component') {
result = Component.unlinkComponent(context);
} else {
result = Component.unlinkService(context);
}
return result;
}
@vsCommand('openshift.component.unlinkComponent.palette')
@selectTargetComponent(
'Select an Application',
'Select a Component',
(value: OpenShiftObject) => value.contextValue === ContextType.COMPONENT_PUSHED
)
static async unlinkComponent(component: OpenShiftObject): Promise<string | null> {
if (!component) return null;
const linkComponent = await Component.getLinkData(component);
const getLinkComponent = linkComponent.status.linkedComponents;
if (!getLinkComponent) throw new VsCommandError('No linked Components found');
const linkCompName: Array<string> = Object.keys(getLinkComponent);
const compName = await window.showQuickPick(linkCompName, {placeHolder: "Select a Component to unlink", ignoreFocusOut: true});
if (!compName) return null;
const getLinkPort = linkComponent.status.linkedComponents[compName];
const port = await window.showQuickPick(getLinkPort, {placeHolder: "Select a Port"});
if (!port) return null;
return Progress.execFunctionWithProgress(`Unlinking Component`,
() => Component.odo.execute(Command.unlinkComponents(component.getParent().getParent().getName(), component.getParent().getName(), component.getName(), compName, port), component.contextPath.fsPath)
.then(() => `Component '${compName}' has been successfully unlinked from the Component '${component.getName()}'`)
.catch((err) => Promise.reject(new VsCommandError(`Failed to unlink Component with error '${err}'`)))
);
}
@vsCommand('openshift.component.unlinkService.palette')
@selectTargetComponent(
'Select an Application',
'Select a Component',
(value: OpenShiftObject) => value.contextValue === ContextType.COMPONENT_PUSHED
)
static async unlinkService(component: OpenShiftObject): Promise<string | null> {
if (!component) return null;
const linkService = await Component.getLinkData(component);
const getLinkService = linkService.status.linkedServices;
if (!getLinkService) throw new VsCommandError('No linked Services found');
const serviceName = await window.showQuickPick(getLinkService, {placeHolder: "Select a Service to unlink", ignoreFocusOut: true});
if (!serviceName) return null;
return Progress.execFunctionWithProgress(`Unlinking Service`,
() => Component.odo.execute(Command.unlinkService(component.getParent().getParent().getName(), component.getParent().getName(), serviceName, component.getName()), component.contextPath.fsPath)
.then(() => `Service '${serviceName}' has been successfully unlinked from the Component '${component.getName()}'`)
.catch((err) => Promise.reject(new VsCommandError(`Failed to unlink Service with error '${err}'`)))
);
}
@vsCommand('openshift.component.linkComponent')
@selectTargetComponent(
'Select an Application',
'Select a Component',
(value: OpenShiftObject) => value.contextValue === ContextType.COMPONENT_PUSHED
)
static async linkComponent(component: OpenShiftObject): Promise<string | null> {
if (!component) return null;
const componentPresent = (await Component.odo.getComponents(component.getParent())).filter((target) => target.contextValue !== ContextType.COMPONENT);
if (componentPresent.length === 1) throw Error('You have no Components available to link, please create new OpenShift Component and try again.');
const componentToLink = await window.showQuickPick(componentPresent.filter((comp)=> comp.getName() !== component.getName()), {placeHolder: "Select a Component to link", ignoreFocusOut: true});
if (!componentToLink) return null;
const ports: string[] = await Component.getPorts(component, componentToLink);
let port: string;
if (ports.length === 1) {
[port] = ports;
} else if (ports.length > 1) {
port = await window.showQuickPick(ports, {placeHolder: "Select Port to link", ignoreFocusOut: true});
} else {
return Promise.reject(new VsCommandError(`Component '${component.getName()}' has no Ports declared.`));
}
return Progress.execFunctionWithProgress(`Link Component '${componentToLink.getName()}' with Component '${component.getName()}'`,
() => Component.odo.execute(Command.linkComponentTo(component.getParent().getParent().getName(), component.getParent().getName(), component.getName(), componentToLink.getName(), port), component.contextPath.fsPath)
.then(() => `Component '${componentToLink.getName()}' successfully linked with Component '${component.getName()}'`)
.catch((err) => Promise.reject(new VsCommandError(`Failed to link component with error '${err}'`)))
);
}
static async getPorts(component: OpenShiftObject, componentToLink: OpenShiftObject): Promise<string[]> {
const portsResult: CliExitData = await Component.odo.execute(Command.listComponentPorts(component.getParent().getParent().getName(), component.getParent().getName(), componentToLink.getName()));
let ports: string[] = portsResult.stdout.trim().split(',');
ports = ports.slice(0, ports.length - 1);
return ports;
}
@vsCommand('openshift.component.linkService')
@selectTargetComponent(
'Select an Application',
'Select a Component',
(value: OpenShiftObject) => value.contextValue === ContextType.COMPONENT_PUSHED
)
static async linkService(component: OpenShiftObject): Promise<string | null> {
if (!component) return null;
const serviceToLink: OpenShiftObject = await window.showQuickPick(Component.getServiceNames(component.getParent()), {placeHolder: "Select a service to link", ignoreFocusOut: true});
if (!serviceToLink) return null;
return Progress.execFunctionWithProgress(`Link Service '${serviceToLink.getName()}' with Component '${component.getName()}'`,
() => Component.odo.execute(Command.linkServiceTo(component.getParent().getParent().getName(), component.getParent().getName(), component.getName(), serviceToLink.getName()), component.contextPath.fsPath)
.then(() => `Service '${serviceToLink.getName()}' successfully linked with Component '${component.getName()}'`)
.catch((err) => Promise.reject(new VsCommandError(`Failed to link Service with error '${err}'`)))
);
}
static getPushCmd(): Thenable<{pushCmd: string; contextPath: string; name: string}> {
return this.extensionContext.globalState.get('PUSH');
}
static setPushCmd(fsPath: string, name: string): Thenable<void> {
return this.extensionContext.globalState.update('PUSH', { pushCmd: Command.pushComponent(),
contextPath: fsPath, name });
}
@vsCommand('openshift.component.push', true)
@selectTargetComponent(
'In which Application you want to push the changes',
'For which Component you want to push the changes',
(target) => target.contextValue === ContextType.COMPONENT_PUSHED || target.contextValue === ContextType.COMPONENT
)
static async push(component: OpenShiftObject, configOnly = false): Promise<string | null> {
if (!component) return null;
Component.setPushCmd(component.contextPath.fsPath, component.getName());
await Component.odo.executeInTerminal(Command.pushComponent(configOnly), component.contextPath.fsPath, `OpenShift: Push '${component.getName()}' Component`);
component.contextValue = ContextType.COMPONENT_PUSHED;
Component.explorer.refresh(component);
}
@vsCommand('openshift.component.lastPush')
static async lastPush(): Promise<void> {
const getPushCmd = await Component.getPushCmd();
if (getPushCmd.pushCmd && getPushCmd.contextPath) {
Component.odo.executeInTerminal(getPushCmd.pushCmd, getPushCmd.contextPath, `OpenShift: Push '${getPushCmd.name}' Component`);
} else {
throw Error('No existing push command found');
}
}
static addWatchSession(component: OpenShiftObject, process: ChildProcess): void {
Component.watchSessions.set(component.contextPath.fsPath, process);
Component.watchEmitter.emit('watchStarted', component);
}
static removeWatchSession(component: OpenShiftObject): void {
Component.watchSessions.delete(component.contextPath.fsPath);
Component.watchEmitter.emit('watchStopped', component);
}
@vsCommand('openshift.component.watch', true)
@selectTargetComponent(
'Select an Application',
'Select a Component you want to watch',
(target) => target.contextValue === ContextType.COMPONENT_PUSHED
)
static async watch(component: OpenShiftObject): Promise<void> {
if (!component) return null;
if (component.compType !== SourceType.LOCAL && component.compType !== SourceType.BINARY) {
window.showInformationMessage(`Watch is supported only for Components with local or binary source type.`)
return null;
}
if (Component.watchSessions.get(component.contextPath.fsPath)) {
const sel = await window.showInformationMessage(`Watch process is already running for '${component.getName()}'`, 'Show Log');
if (sel === 'Show Log') {
commands.executeCommand('openshift.component.watch.showLog', component.contextPath.fsPath);
}
} else {
const process: ChildProcess = await Component.odo.spawn(Command.watchComponent(), component.contextPath.fsPath);
Component.addWatchSession(component, process);
process.on('exit', () => {
Component.removeWatchSession(component);
});
}
}
@vsCommand('openshift.component.watch.terminate')
static terminateWatchSession(context: string): void {
treeKill(Component.watchSessions.get(context).pid, 'SIGKILL');
}
@vsCommand('openshift.component.watch.showLog')
static showWatchSessionLog(context: string): void {
LogViewLoader.loadView(`${context} Watch Log`, () => `odo watch --context ${context}`, Component.odo.getOpenShiftObjectByContext(context), Component.watchSessions.get(context));
}
@vsCommand('openshift.component.openUrl', true)
@selectTargetComponent(
'Select an Application',
'Select a Component to open in browser',
(target) => target.contextValue === ContextType.COMPONENT_PUSHED
)
static async openUrl(component: OpenShiftObject): Promise<ChildProcess | string> {
if (!component) return null;
const app: OpenShiftObject = component.getParent();
const urlItems = await Component.listUrl(component);
if (urlItems === null) {
const value = await window.showInformationMessage(`No URL for Component '${component.getName()}' in Application '${app.getName()}'. Do you want to create a URL and open it?`, 'Create', 'Cancel');
if (value === 'Create') {
await commands.executeCommand('openshift.url.create', component);
}
}
if (urlItems !== null) {
let selectRoute: QuickPickItem;
const unpushedUrl = urlItems.filter((value: { status: { state: string } }) => value.status.state === 'Not Pushed');
const pushedUrl = urlItems.filter((value: { status: { state: string } }) => value.status.state === 'Pushed');
if (pushedUrl.length > 0) {
const hostName: QuickPickItem[] = pushedUrl.map((value: { spec: { protocol: string; host: string; port: any } }) => ({ label: `${value.spec.protocol}://${value.spec.host}`, description: `Target Port is ${value.spec.port}`}));
if (hostName.length >1) {
selectRoute = await window.showQuickPick(hostName, {placeHolder: "This Component has multiple URLs. Select the desired URL to open in browser.", ignoreFocusOut: true});
if (!selectRoute) return null;
return commands.executeCommand('vscode.open', Uri.parse(`${selectRoute.label}`));
}
return commands.executeCommand('vscode.open', Uri.parse(`${hostName[0].label}`));
} if (unpushedUrl.length > 0) {
return `${unpushedUrl.length} unpushed URL in the local config. Use 'Push' command before opening URL in browser.`;
}
}
}
static async listUrl(component: OpenShiftObject): Promise<any> {
const UrlDetails = await Component.odo.execute(Command.getComponentUrl(), component.contextPath.fsPath);
return JSON.parse(UrlDetails.stdout).items;
}
@vsCommand('openshift.component.createFromLocal')
@selectTargetApplication(
"Select an Application where you want to create a Component"
)
static async createFromLocal(application: OpenShiftObject): Promise<string | null> {
if (!application) return null;
const workspacePath = await selectWorkspaceFolder();
if (!workspacePath) return null;
const componentList: Array<OpenShiftObject> = await Component.odo.getComponents(application);
const componentName = await Component.getName('Component name', componentList, application.getName());
if (!componentName) return null;
const catalog = new Catalog();
const componentTypeName = await window.showQuickPick(catalog.getComponentNames(), {placeHolder: "Component type", ignoreFocusOut: true});
if (!componentTypeName) return null;
const componentTypeVersion = await window.showQuickPick(catalog.getComponentVersions(componentTypeName), {placeHolder: "Component type version", ignoreFocusOut: true});
if (!componentTypeVersion) return null;
await Progress.execFunctionWithProgress(`Creating new Component '${componentName}'`, () => Component.odo.createComponentFromFolder(application, componentTypeName, componentTypeVersion, componentName, workspacePath));
return `Component '${componentName}' successfully created. To deploy it on cluster, perform 'Push' action.`;
}
static async createFromFolder(folder: Uri): Promise<string | null> {
const application = await Component.getOpenShiftCmdData(undefined,
"In which Application you want to create a Component"
);
if (!application) return null;
const componentList: Array<OpenShiftObject> = await Component.odo.getComponents(application);
const componentName = await Component.getName('Component name', componentList, application.getName());
if (!componentName) return null;
const catalog = new Catalog();
const componentTypeName = await window.showQuickPick(catalog.getComponentNames(), {placeHolder: "Component type", ignoreFocusOut: true});
if (!componentTypeName) return null;
const componentTypeVersion = await window.showQuickPick(catalog.getComponentVersions(componentTypeName), {placeHolder: "Component type version", ignoreFocusOut: true});
if (!componentTypeVersion) return null;
await Progress.execFunctionWithProgress(`Creating new Component '${componentName}'`, () => Component.odo.createComponentFromFolder(application, componentTypeName, componentTypeVersion, componentName, folder));
return `Component '${componentName}' successfully created. To deploy it on cluster, perform 'Push' action.`;
}
@vsCommand('openshift.component.createFromGit')
@selectTargetApplication(
"In which Application you want to create a Component"
)
static async createFromGit(application: OpenShiftObject): Promise<string | null> {
if (!application) return null;
const workspacePath = await selectWorkspaceFolder();
if (!workspacePath) return null;
const delayer = new Delayer<string>(500);
const repoURI = await window.showInputBox({
prompt: 'Git repository URI',
ignoreFocusOut: true,
validateInput: (value: string) => {
return delayer.trigger(async () => {
if (!value.trim()) return 'Empty Git repository URL';
if (!isURL(value)) return 'Invalid URL provided';
const references = await Refs.fetchTag(value);
if (!references.get('HEAD')) return 'There is no git repository at provided URL.';
});
}
});
if (!repoURI) return null;
const references: Map<string, Ref> = await Refs.fetchTag(repoURI);
const gitRef = await window.showQuickPick([...references.values()].map(value => ({label: value.name, description: value.type === Type.TAG? `Tag at ${value.hash}` : value.hash })) , {placeHolder: "Select git reference (branch/tag)", ignoreFocusOut: true});
if (!gitRef) return null;
const componentList: Array<OpenShiftObject> = await Component.odo.getComponents(application);
const componentName = await Component.getName('Component name', componentList, application.getName());
if (!componentName) return null;
const catalog = new Catalog();
const componentTypeName = await window.showQuickPick(catalog.getComponentNames(), {placeHolder: "Component type", ignoreFocusOut: true});
if (!componentTypeName) return null;
const componentTypeVersion = await window.showQuickPick(catalog.getComponentVersions(componentTypeName), {placeHolder: "Component type version", ignoreFocusOut: true});
if (!componentTypeVersion) return null;
await Component.odo.createComponentFromGit(application, componentTypeName, componentTypeVersion, componentName, repoURI, workspacePath, gitRef.label);
return `Component '${componentName}' successfully created. To deploy it on cluster, perform 'Push' action.`;
}
@vsCommand('openshift.component.createFromBinary')
@selectTargetApplication(
"In which Application you want to create a Component"
)
static async createFromBinary(application: OpenShiftObject): Promise<string | null> {
if (!application) return null;
const workspacePath = await selectWorkspaceFolder();
if (!workspacePath) return null;
const globPath = process.platform === 'win32' ? workspacePath.fsPath.replace(/\\/g, '/') : workspacePath.path;
const paths = globby.sync(`${globPath}`, { expandDirectories: { files: ['*'], extensions: ['jar', 'war']}, deep: 20 });
if (paths.length === 0) return "No binary file present in the context folder selected. We currently only support .jar and .war files. If you need support for any other file, please raise an issue.";
const binaryFileObj: QuickPickItem[] = paths.map((file) => ({ label: `$(file-zip) ${path.basename(file)}`, description: `${file}`}));
const binaryFile: QuickPickItem = await window.showQuickPick(binaryFileObj, {placeHolder: "Select binary file", ignoreFocusOut: true});
if (!binaryFile) return null;
const componentList: Array<OpenShiftObject> = await Component.odo.getComponents(application);
const componentName = await Component.getName('Component name', componentList, application.getName());
if (!componentName) return null;
const catalog = new Catalog();
const componentTypeName = await window.showQuickPick(catalog.getComponentNames(), {placeHolder: "Component type", ignoreFocusOut: true});
if (!componentTypeName) return null;
const componentTypeVersion = await window.showQuickPick(catalog.getComponentVersions(componentTypeName), {placeHolder: "Component type version", ignoreFocusOut: true});
if (!componentTypeVersion) return null;
await Component.odo.createComponentFromBinary(application, componentTypeName, componentTypeVersion, componentName, Uri.file(binaryFile.description), workspacePath);
return `Component '${componentName}' successfully created. To deploy it on cluster, perform 'Push' action.`;
}
@vsCommand('openshift.component.debug', true)
@selectTargetComponent(
'Select an Application',
'Select a Component you want to debug (showing only Components pushed to the cluster)',
(value: OpenShiftObject) => value.contextValue === ContextType.COMPONENT_PUSHED
)
static async debug(component: OpenShiftObject): Promise<string | null> {
if (!component) return null;
if (component.compType === SourceType.LOCAL) {
return Progress.execFunctionWithProgress(`Starting debugger session for the component '${component.getName()}'.`, () => Component.startDebugger(component));
}
if (component.compType !== SourceType.GIT || SourceType.BINARY) {
throw new VsCommandError(`You are trying to run Debug on a ${component.compType} component, which is NOT supported. Debug Command is only supported for Local components.`);
}
}
static async startDebugger(component: OpenShiftObject): Promise<string | undefined> {
if (Component.debugSessions.get(component.contextPath.fsPath)) {
const choice = await window.showWarningMessage(`Debugger session is already running for ${component.getName()}.`, 'Show \'Run and Debug\' view');
if (choice) {
commands.executeCommand('workbench.view.debug');
}
return null;
}
const components = await Component.odo.getComponentTypesJson();
const componentBuilder = components.find((builder) => builder.metadata.name === component.builderImage.name);
const imageStreamRef = await Component.odo.getImageStreamRef(componentBuilder.metadata.name, componentBuilder.metadata.namespace);
const tag = imageStreamRef.spec.tags.find((element: { name: string }) => element.name === component.builderImage.tag);
const isJava = tag.annotations.tags.includes('java');
const isNode = tag.annotations.tags.includes('nodejs');
const JAVA_EXT = 'redhat.java';
const JAVA_DEBUG_EXT = 'vscjava.vscode-java-debug';
let result: undefined | string | PromiseLike<string>;
if (isJava || isNode) {
const toolLocation = await ToolsConfig.detect(`odo`);
if (isJava) {
const jlsIsActive = extensions.getExtension(JAVA_EXT);
const jdIsActive = extensions.getExtension(JAVA_DEBUG_EXT);
if (!jlsIsActive || !jdIsActive) {
let warningMsg;
if (jlsIsActive && !jdIsActive) {
warningMsg = 'Debugger for Java is required to debug component';
} else if (!jlsIsActive && jdIsActive) {
warningMsg = 'Language Support for Java is required to debug component';
} else {
warningMsg = 'Language Support and Debugger for Java are required to debug component';
}
const response = await window.showWarningMessage(warningMsg, 'Install');
if (response === 'Install') {
await window.withProgress({ location: ProgressLocation.Notification }, async (progress) => {
progress.report({ message: 'Installing extensions required to debug Java Component ...'});
if (!jlsIsActive) await commands.executeCommand('workbench.extensions.installExtension', JAVA_EXT);
if (!jdIsActive) await commands.executeCommand('workbench.extensions.installExtension', JAVA_DEBUG_EXT);
});
await window.showInformationMessage("Please reload window to activate installed extensions.", 'Reload');
await commands.executeCommand("workbench.action.reloadWindow");
}
}
if (jlsIsActive && jdIsActive) {
result = Component.startOdoAndConnectDebugger(toolLocation, component, {
name: `Attach to '${component.getName()}' component.`,
type: 'java',
request: 'attach',
hostName: 'localhost',
projectName: path.basename(component.contextPath.fsPath)
});
}
} else {
result = Component.startOdoAndConnectDebugger(toolLocation, component, {
name: `Attach to '${component.getName()}' component.`,
type: 'node2',
request: 'attach',
address: 'localhost',
localRoot: component.contextPath.fsPath,
remoteRoot: '/opt/app-root/src'
});
}
} else {
window.showWarningMessage('Debug command supports only local Java and Node.Js components.');
}
return result;
}
static async startOdoAndConnectDebugger(toolLocation: string, component: OpenShiftObject, config: DebugConfiguration): Promise<string> {
const cp = exec(`"${toolLocation}" debug port-forward`, {cwd: component.contextPath.fsPath});
return new Promise<string>((resolve, reject) => {
// eslint-disable-next-line @typescript-eslint/no-misused-promises
cp.stdout.on('data', async (data: string) => {
const parsedPort = data.trim().match(/- (?<localPort>\d+):\d+$/);
if (parsedPort?.groups?.localPort) {
await waitPort({
host: 'localhost',
port: parseInt(parsedPort.groups.localPort, 10)
});
resolve(parsedPort.groups.localPort);
}
});
cp.stderr.on('data', (data: string) => {
if (!`${data}`.includes('the local debug port 5858 is not free')) {
reject(data);
}
});
}).then((result) => {
config.contextPath = component.contextPath;
config.port = result;
config.odoPid = cp.pid;
return debug.startDebugging(workspace.getWorkspaceFolder(component.contextPath), config);
}).then((result: boolean) =>
result ? 'Debugger session has successfully started.' : Promise.reject(new VsCommandError('Debugger session failed to start.'))
);
}
@vsCommand('openshift.component.import')
static async import(component: OpenShiftObject): Promise<string | null> {
const prjName = component.getParent().getParent().getName();
const appName = component.getParent().getName();
const compName = component.getName();
// get pvcs and urls based on label selector
const componentResult = await Component.odo.execute(`oc get dc -l app.kubernetes.io/instance=${compName} --namespace ${prjName} -o json`, Platform.getUserHomePath(), false);
const componentJson = JSON.parse(componentResult.stdout).items[0];
const componentType = componentJson.metadata.annotations['app.kubernetes.io/component-source-type'];
if (componentType === SourceType.BINARY) {
return 'Import for binary OpenShift Components is not supported.';
} if (componentType !== SourceType.GIT && componentType !== SourceType.LOCAL) {
throw new VsCommandError(`Cannot import unknown Component type '${componentType}'.`);
}
const workspaceFolder = await selectWorkspaceFolder();
if (!workspaceFolder) return null;
return Progress.execFunctionWithProgress(`Importing component '${compName}'`, async () => {
try {
// use annotations to understand what kind of component is imported
// metadata:
// annotations:
// app.kubernetes.io/component-source-type: binary
// app.openshift.io/vcs-uri: 'file:///helloworld.war'
// not supported yet
// metadata:
// annotations:
// app.kubernetes.io/component-source-type: local
// app.openshift.io/vcs-uri: 'file:///./'
// metadata:
// annotations:
// app.kubernetes.io/component-source-type: git
// app.kubernetes.io/url: 'https://github.com/dgolovin/nodejs-ex'
if (componentType === SourceType.GIT) {
const bcResult = await Component.odo.execute(`oc get bc/${componentJson.metadata.name} --namespace ${prjName} -o json`);
const bcJson = JSON.parse(bcResult.stdout);
const compTypeName = componentJson.metadata.labels['app.kubernetes.io/name'];
const compTypeVersion = componentJson.metadata.labels['app.openshift.io/runtime-version'];
const gitUrl = componentJson.metadata.annotations['app.openshift.io/vcs-uri'] || componentJson.metadata.annotations['app.kubernetes.io/url'];
const gitRef = bcJson.spec.source.git.ref || 'master';
await Component.odo.execute(Command.createGitComponent(prjName, appName, compTypeName, compTypeVersion, compName, gitUrl, gitRef), workspaceFolder.fsPath);
} else { // componentType === ComponentType.Local
await Component.odo.execute(Command.createLocalComponent(prjName, appName, componentJson.metadata.labels['app.kubernetes.io/name'], componentJson.metadata.labels['app.openshift.io/runtime-version'], compName, workspaceFolder.fsPath));
}
// import storage if present
if (componentJson.spec.template.spec.containers[0].volumeMounts) {
const volumeMounts: any[] = componentJson.spec.template.spec.containers[0].volumeMounts.filter((volume: { name: string }) => !volume.name.startsWith(compName));
const volumes: any[] = componentJson.spec.template.spec.volumes.filter((volume: { persistentVolumeClaim: any; name: string }) => volume.persistentVolumeClaim !== undefined && !volume.name.startsWith(compName));
const storageData: Partial<{mountPath: string; pvcName: string}>[] = volumes.map((volume) => {
const data: Partial<{mountPath: string; pvcName: string}> = {};
const mount = volumeMounts.find((item) => item.name === volume.name);
data.mountPath = mount.mountPath;
data.pvcName = volume.persistentVolumeClaim.claimName;
return data;
});
// eslint-disable-next-line no-restricted-syntax
for (const storage of storageData) {
try {
// eslint-disable-next-line no-await-in-loop
const pvcResult = await Component.odo.execute(`oc get pvc/${storage.pvcName} --namespace ${prjName} -o json`, Platform.getUserHomePath(), false);
const pvcJson = JSON.parse(pvcResult.stdout);
const storageName = pvcJson.metadata.labels['app.kubernetes.io/storage-name'];
const size = pvcJson.spec.resources.requests.storage;
// eslint-disable-next-line no-await-in-loop
await Component.odo.execute(Command.createStorage(storageName, storage.mountPath, size), workspaceFolder.fsPath);
} catch (ignore) {
// means there is no storage attached to component
}
}
}
// import routes if present
try {
const routeResult = await Component.odo.execute(`oc get route -l app.kubernetes.io/instance=${compName},app.kubernetes.io/part-of=${appName} --namespace ${prjName} -o json`, Platform.getUserHomePath(), false);
const routeJson = JSON.parse(routeResult.stdout);
const routeData: Partial<{name: string; port: string}>[] = routeJson.items.map((element: any) => ({name: element.metadata.labels['odo.openshift.io/url-name'], port: element.spec.port.targetPort}));
// eslint-disable-next-line no-restricted-syntax
for (const url of routeData) {
Component.odo.execute(Command.createComponentCustomUrl(url.name, url.port), workspaceFolder.fsPath);
}
} catch (ignore) {
// means there is no routes to the component
}
const wsFolder = workspace.getWorkspaceFolder(workspaceFolder);
if (wsFolder) {
Component.odo.addWorkspaceComponent(wsFolder, component);
} else {
workspace.updateWorkspaceFolders(workspace.workspaceFolders? workspace.workspaceFolders.length : 0 , null, { uri: workspaceFolder });
}
return `Component '${compName}' was successfully imported.`;
} catch (errGetCompJson) {
throw new VsCommandError(`Component import failed with error '${errGetCompJson.message}'.`);
}
}); // create component with the same name
}
}