forked from redhat-developer/vscode-openshift-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathodo.ts
More file actions
1267 lines (1094 loc) · 58.6 KB
/
odo.ts
File metadata and controls
1267 lines (1094 loc) · 58.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
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*-----------------------------------------------------------------------------------------------
* Copyright (c) Red Hat, Inc. All rights reserved.
* Licensed under the MIT License. See LICENSE file in the project root for license information.
*-----------------------------------------------------------------------------------------------*/
import { ProviderResult, TreeItemCollapsibleState, window, Terminal, Uri, commands, QuickPickItem, workspace, WorkspaceFoldersChangeEvent, WorkspaceFolder, Disposable } from 'vscode';
import * as path from 'path';
import { statSync } from 'fs';
import { Subject } from 'rxjs';
import { ChildProcess } from 'child_process';
import * as cliInstance from './cli';
import { WindowUtil } from './util/windowUtils';
import { CliExitData } from './cli';
import { ToolsConfig } from './tools';
import { Platform } from './util/platform';
import * as odo from './odo/config';
import { ComponentSettings } from './odo/config';
import { GlyphChars } from './util/constants';
import { Progress } from './util/progress';
import format = require('string-format');
import bs = require('binary-search');
import yaml = require('js-yaml');
import fs = require('fs');
const {Collapsed} = TreeItemCollapsibleState;
export interface BuilderImage {
readonly name: string;
readonly tag: string;
}
export interface OpenShiftObject extends QuickPickItem {
getChildren(): ProviderResult<OpenShiftObject[]>;
getParent(): OpenShiftObject;
getName(): string;
contextValue: string;
compType?: string;
contextPath?: Uri;
deployed: boolean;
path?: string;
builderImage?: BuilderImage;
}
export enum ContextType {
CLUSTER = 'cluster',
PROJECT = 'project',
APPLICATION = 'application',
COMPONENT = 'componentNotPushed',
COMPONENT_PUSHED = 'component',
COMPONENT_NO_CONTEXT = 'componentNoContext',
SERVICE = 'service',
STORAGE = 'storage',
CLUSTER_DOWN = 'clusterDown',
LOGIN_REQUIRED = 'loginRequired',
COMPONENT_ROUTE = 'componentRoute'
}
export enum ComponentType {
LOCAL = 'local',
GIT = 'git',
BINARY = 'binary'
}
function verbose(_target: any, key: string, descriptor: any): void {
let fnKey: string | undefined;
let fn: Function | undefined;
if (typeof descriptor.value === 'function') {
fnKey = 'value';
fn = descriptor.value;
} else {
throw new Error('not supported');
}
descriptor[fnKey] = function (...args: any[]) {
const v = workspace.getConfiguration('openshiftConnector').get('outputVerbosityLevel');
const command = fn.apply(this, args);
return command + (v > 0 ? ` -v ${v}` : '');
};
}
export class Command {
static listProjects(): string {
return `odo project list -o json`;
}
@verbose
static listApplications(project: string): string {
return `odo application list --project ${project} -o json`;
}
static deleteProject(name: string): string {
return `odo project delete ${name} -o json`;
}
static waitForProjectToBeGone(project: string): string {
return `oc wait project/${project} --for delete`;
}
@verbose
static createProject(name: string): string {
return `odo project create ${name}`;
}
static listComponents(project: string, app: string): string {
return `odo list --app ${app} --project ${project} -o json`;
}
static listCatalogComponents(): string {
return `odo catalog list components`;
}
static listCatalogComponentsJson(): string {
return `${Command.listCatalogComponents()} -o json`;
}
static listCatalogServices(): string {
return `odo catalog list services`;
}
static listCatalogServicesJson(): string {
return `${Command.listCatalogServices()} -o json`;
}
static listStorageNames(): string {
return `odo storage list -o json`;
}
static printOcVersion(): string {
return 'oc version';
}
static listServiceInstances(project: string, app: string): string {
return `odo service list -o json --project ${project} --app ${app}`;
}
static describeApplication(project: string, app: string): string {
return `odo app describe ${app} --project ${project}`;
}
static deleteApplication(project: string, app: string): string {
return `odo app delete ${app} --project ${project} -f`;
}
static printOdoVersion(): string {
return 'odo version';
}
static printOdoVersionAndProjects(): string {
return 'odo version && odo project list';
}
static odoLogout(): string {
return `odo logout`;
}
static setOpenshiftContext(context: string): string {
return `oc config use-context ${context}`;
}
static odoLoginWithUsernamePassword(clusterURL: string, username: string, passwd: string): string {
const quote = Platform.OS === 'win32' ? `"` : `'`;
return `odo login ${clusterURL} -u ${quote}${username}${quote} -p ${quote}${passwd}${quote} --insecure-skip-tls-verify`;
}
static odoLoginWithToken(clusterURL: string, ocToken: string): string {
return `odo login ${clusterURL} --token=${ocToken} --insecure-skip-tls-verify`;
}
@verbose
static createStorage(storageName: string, mountPath: string, storageSize: string): string {
return `odo storage create ${storageName} --path=${mountPath} --size=${storageSize}`;
}
static deleteStorage(storage: string): string {
return `odo storage delete ${storage} -f`;
}
static waitForStorageToBeGone(project: string, app: string, storage: string): string {
return `oc wait pvc/${storage}-${app}-pvc --for=delete --namespace ${project}`;
}
static undeployComponent(project: string, app: string, component: string): string {
return `odo delete ${component} -f --app ${app} --project ${project}`;
}
static deleteComponent(project: string, app: string, component: string): string {
return `odo delete ${component} -f --app ${app} --project ${project} --all`;
}
static describeComponent(project: string, app: string, component: string): string {
return `odo describe ${component} --app ${app} --project ${project}`;
}
static describeComponentJson(project: string, app: string, component: string): string {
return `${Command.describeComponent(project, app, component)} -o json`;
}
static describeService(service: string): string {
return `odo catalog describe service ${service}`;
}
static showLog(project: string, app: string, component: string): string {
return `odo log ${component} --app ${app} --project ${project}`;
}
static showLogAndFollow(project: string, app: string, component: string): string {
return `odo log ${component} -f --app ${app} --project ${project}`;
}
static listComponentPorts(project: string, app: string, component: string): string {
return `oc get service ${component}-${app} --namespace ${project} -o jsonpath="{range .spec.ports[*]}{.port}{','}{end}"`;
}
static linkComponentTo(project: string, app: string, component: string, componentToLink: string, port?: string): string {
return `odo link ${componentToLink} --project ${project} --app ${app} --component ${component} --wait${port ? ` --port ${ port}` : ''}`;
}
static linkServiceTo(project: string, app: string, component: string, serviceToLink: string): string {
return `odo link ${serviceToLink} --project ${project} --app ${app} --component ${component} --wait --wait-for-target`;
}
@verbose
static pushComponent(): string {
return `odo push`;
}
@verbose
static watchComponent(project: string, app: string, component: string): string {
return `odo watch ${component} --app ${app} --project ${project}`;
}
@verbose
static createLocalComponent(project: string, app: string, type: string, version: string, name: string, folder: string): string {
return `odo create ${type}:${version} ${name} --context ${folder} --app ${app} --project ${project}`;
}
@verbose
static createGitComponent(project: string, app: string, type: string, version: string, name: string, git: string, ref: string): string {
return `odo create ${type}:${version} ${name} --git ${git} --ref ${ref} --app ${app} --project ${project}`;
}
@verbose
static createBinaryComponent(project: string, app: string, type: string, version: string, name: string, binary: string, context: string): string {
return `odo create ${type}:${version} ${name} --binary ${binary} --app ${app} --project ${project} --context ${context}`;
}
@verbose
static createService(project: string, app: string, template: string, plan: string, name: string): string {
return `odo service create ${template} --plan ${plan} ${name} --app ${app} --project ${project} -w`;
}
static deleteService(project: string, app: string, name: string): string {
return `odo service delete ${name} -f --project ${project} --app ${app}`;
}
static getServiceTemplate(project: string, service: string): string {
return `oc get ServiceInstance ${service} --namespace ${project} -o jsonpath="{$.metadata.labels.app\\.kubernetes\\.io/name}"`;
}
static waitForServiceToBeGone(project: string, service: string): string {
return `oc wait ServiceInstance/${service} --for delete --namespace ${project}`;
}
@verbose
static createComponentCustomUrl(name: string, port: string): string {
return `odo url create ${name} --port ${port}`;
}
static getComponentUrl(): string {
return `odo url list -o json`;
}
static deleteComponentUrl(name: string): string {
return `odo url delete -f ${name}`;
}
static getComponentJson(): string {
return `odo describe -o json`;
}
static unlinkComponents(project: string, app: string, comp1: string, comp2: string, port: string): string {
return `odo unlink --project ${project} --app ${app} ${comp2} --port ${port} --component ${comp1}`;
}
static unlinkService(project: string, app: string, service: string, comp: string): string {
return `odo unlink --project ${project} --app ${app} ${service} --component ${comp}`;
}
static getOpenshiftClusterRoute(): string {
return `oc get routes -n openshift-console -ojson`;
}
static getclusterVersion(): string {
return `oc get clusterversion -ojson`;
}
static showServerUrl(): string {
return `oc whoami --show-server`;
}
static showConsoleUrl(): string {
return `oc get configmaps console-public -n openshift-config-managed -o json`;
}
}
export class OpenShiftObjectImpl implements OpenShiftObject {
private readonly CONTEXT_DATA = {
cluster: {
icon: 'cluster-node.png',
tooltip: '{name}',
getChildren: () => this.odo.getProjects()
},
project: {
icon: 'project-node.png',
tooltip : 'Project: {label}',
getChildren: () => this.odo.getApplications(this)
},
application: {
icon: 'application-node.png',
tooltip: 'Application: {label}',
getChildren: () => this.odo.getApplicationChildren(this)
},
component: {
icon: '',
tooltip: 'Component: {label}',
description: '',
getChildren: () => this.odo.getComponentChildren(this)
},
componentNotPushed: {
icon: '',
tooltip: 'Component: {label}',
description: '',
getChildren: () => this.odo.getComponentChildren(this)
},
componentNoContext: {
icon: '',
tooltip: 'Component: {label}',
description: '',
getChildren: () => this.odo.getComponentChildren(this)
},
service: {
icon: 'service-node.png',
tooltip: 'Service: {label}',
getChildren: () => []
},
storage: {
icon: 'storage-node.png',
tooltip: 'Storage: {label}',
getChildren: () => []
},
clusterDown: {
icon: 'cluster-down.png',
tooltip: 'Cannot connect to the cluster',
getChildren: () => []
},
loginRequired: {
icon: 'cluster-down.png',
tooltip: 'Please Log in to the cluster',
getChildren: () => []
},
componentRoute: {
icon: 'url-node.png',
tooltip: 'URL: {label}',
getChildren: () => []
}
};
private explorerPath: string;
constructor(private parent: OpenShiftObject,
public readonly name: string,
public readonly contextValue: ContextType,
public deployed: boolean,
private readonly odo: Odo,
public readonly collapsibleState: TreeItemCollapsibleState = Collapsed,
public contextPath: Uri = undefined,
public readonly compType: string = undefined,
public readonly builderImage: BuilderImage = undefined) {
OdoImpl.data.setPathToObject(this);
}
get path(): string {
if (!this.explorerPath) {
let parent: OpenShiftObject;
const segments: string[] = [];
do {
segments.splice(0, 0, parent ? parent.getName() : this.getName());
parent = parent ? parent.getParent() : this.getParent();
} while (parent);
this.explorerPath = path.join(...segments);
}
return this.explorerPath;
}
get iconPath(): Uri {
if (this.contextValue === ContextType.COMPONENT_PUSHED || this.contextValue === ContextType.COMPONENT || this.contextValue === ContextType.COMPONENT_NO_CONTEXT) {
if (this.compType === ComponentType.GIT) {
return Uri.file(path.join(__dirname, "../../images/component", 'git.png'));
} if (this.compType === ComponentType.LOCAL) {
return Uri.file(path.join(__dirname, "../../images/component", 'workspace.png'));
} if (this.compType === ComponentType.BINARY) {
return Uri.file(path.join(__dirname, "../../images/component", 'binary.png'));
}
} else {
return Uri.file(path.join(__dirname, "../../images/context", this.CONTEXT_DATA[this.contextValue].icon));
}
}
get tooltip(): string {
return format(this.CONTEXT_DATA[this.contextValue].tooltip, this);
}
get label(): string {
const label = this.contextValue === ContextType.CLUSTER ? this.name.split('//')[1] : this.name;
return label;
}
get description(): string {
let suffix = '';
if (this.contextValue === ContextType.COMPONENT) {
suffix = `${GlyphChars.Space}${GlyphChars.NotPushed} not pushed`;
} else if (this.contextValue === ContextType.COMPONENT_PUSHED) {
suffix = `${GlyphChars.Space}${GlyphChars.Push} pushed`;
} else if (this.contextValue === ContextType.COMPONENT_NO_CONTEXT) {
suffix = `${GlyphChars.Space}${GlyphChars.NoContext} no context`;
}
return suffix;
}
getName(): string {
return this.name;
}
getChildren(): ProviderResult<OpenShiftObject[]> {
return this.CONTEXT_DATA[this.contextValue].getChildren();
}
getParent(): OpenShiftObject {
return this.parent;
}
}
export interface OdoEvent {
readonly type: 'deleted' | 'inserted' | 'changed';
readonly data: OpenShiftObject;
readonly reveal: boolean;
}
class OdoEventImpl implements OdoEvent {
constructor(readonly type: 'deleted' | 'inserted' | 'changed', readonly data: OpenShiftObject, readonly reveal: boolean = false) {
}
}
export interface Odo {
getClusters(): Promise<OpenShiftObject[]>;
getProjects(): Promise<OpenShiftObject[]>;
loadWorkspaceComponents(event: WorkspaceFoldersChangeEvent): void;
addWorkspaceComponent(WorkspaceFolder: WorkspaceFolder, component: OpenShiftObject);
getApplications(project: OpenShiftObject): Promise<OpenShiftObject[]>;
getApplicationChildren(application: OpenShiftObject): Promise<OpenShiftObject[]>;
getComponents(application: OpenShiftObject, condition?: (value: OpenShiftObject) => boolean): Promise<OpenShiftObject[]>;
getComponentTypes(): Promise<string[]>;
getComponentTypesJson(): Promise<any[]>;
getComponentChildren(component: OpenShiftObject): Promise<OpenShiftObject[]>;
getRoutes(component: OpenShiftObject): Promise<OpenShiftObject[]>;
getComponentPorts(component: OpenShiftObject): Promise<odo.Port[]>;
getComponentTypeVersions(componentName: string): Promise<string[]>;
getStorageNames(component: OpenShiftObject): Promise<OpenShiftObject[]>;
getServiceTemplates(): Promise<string[]>;
getServiceTemplatePlans(svc: string): Promise<string[]>;
getServices(application: OpenShiftObject): Promise<OpenShiftObject[]>;
execute(command: string, cwd?: string, fail?: boolean): Promise<CliExitData>;
executeInTerminal(command: string, cwd?: string): Promise<void>;
requireLogin(): Promise<boolean>;
clearCache?(): void;
createProject(name: string): Promise<OpenShiftObject>;
deleteProject(project: OpenShiftObject): Promise<OpenShiftObject>;
createApplication(application: OpenShiftObject): Promise<OpenShiftObject>;
deleteApplication(application: OpenShiftObject): Promise<OpenShiftObject>;
createComponentFromGit(application: OpenShiftObject, type: string, version: string, name: string, repoUri: string, context: Uri, ref: string): Promise<OpenShiftObject>;
createComponentFromFolder(application: OpenShiftObject, type: string, version: string, name: string, path: Uri): Promise<OpenShiftObject>;
createComponentFromBinary(application: OpenShiftObject, type: string, version: string, name: string, path: Uri, context: Uri): Promise<OpenShiftObject>;
deleteComponent(component: OpenShiftObject): Promise<OpenShiftObject>;
undeployComponent(component: OpenShiftObject): Promise<OpenShiftObject>;
deleteNotPushedComponent(component: OpenShiftObject): Promise<OpenShiftObject>;
createStorage(component: OpenShiftObject, name: string, mountPath: string, size: string): Promise<OpenShiftObject>;
deleteStorage(storage: OpenShiftObject): Promise<OpenShiftObject>;
createService(application: OpenShiftObject, templateName: string, planName: string, name: string): Promise<OpenShiftObject>;
deleteService(service: OpenShiftObject): Promise<OpenShiftObject>;
deleteURL(url: OpenShiftObject): Promise<OpenShiftObject>;
createComponentCustomUrl(component: OpenShiftObject, name: string, port: string): Promise<OpenShiftObject>;
readonly subject: Subject<OdoEvent>;
}
export function getInstance(): Odo {
return OdoImpl.Instance;
}
function compareNodes(a: OpenShiftObject, b: OpenShiftObject): number {
if (!a.contextValue) return -1;
if (!b.contextValue) return 1;
const acontext = a.contextValue.includes('_') ? a.contextValue.substr(0, a.contextValue.indexOf('_')) : a.contextValue;
const bcontext = b.contextValue.includes('_') ? b.contextValue.substr(0, b.contextValue.indexOf('_')) : b.contextValue;
const t = acontext.localeCompare(bcontext);
return t || a.label.localeCompare(b.label);
}
class OdoModel {
private parentToChildren: Map<OpenShiftObject, OpenShiftObject[]> = new Map();
private pathToObject = new Map<string, OpenShiftObject>();
private contextToObject = new Map<Uri, OpenShiftObject>();
private contextToSettings = new Map<Uri, ComponentSettings>();
private objectToProcess = new Map<OpenShiftObject, ChildProcess>();
public setParentToChildren(parent: OpenShiftObject, children: OpenShiftObject[]): OpenShiftObject[] {
if (!this.parentToChildren.has(parent)) {
this.parentToChildren.set(parent, children);
}
return children;
}
public getChildrenByParent(parent: OpenShiftObject): OpenShiftObject[] {
return this.parentToChildren.get(parent);
}
public clearTreeData(): void {
this.parentToChildren.clear();
this.pathToObject.clear();
this.contextToObject.clear();
this.addContexts(workspace.workspaceFolders? workspace.workspaceFolders : []);
}
public setPathToObject(object: OpenShiftObject): void {
if (!this.pathToObject.get(object.path)) {
this.pathToObject.set(object.path, object);
}
}
public getObjectByPath(path: string): OpenShiftObject {
return this.pathToObject.get(path);
}
public setContextToObject(object: OpenShiftObject): void {
if (object.contextPath) {
if (!this.contextToObject.has(object.contextPath)) {
this.contextToObject.set(object.contextPath, object );
}
}
}
public getObjectByContext(context: Uri): OpenShiftObject {
return this.contextToObject.get(context);
}
public setContextToSettings (settings: ComponentSettings): void {
if (!this.contextToSettings.has(settings.ContextPath)) {
this.contextToSettings.set(settings.ContextPath, settings);
}
}
public getSettingsByContext(context: Uri): odo.ComponentSettings {
return this.contextToSettings.get(context);
}
public getSettings(): odo.ComponentSettings[] {
return Array.from(this.contextToSettings.values());
}
public addContexts(folders: ReadonlyArray<WorkspaceFolder>): void {
for (const folder of folders) {
try {
const compData = yaml.safeLoad(fs.readFileSync(path.join(folder.uri.fsPath, '.odo', 'config.yaml'), 'utf8')) as odo.Config;
compData.ComponentSettings.ContextPath = folder.uri;
OdoImpl.data.setContextToSettings(compData.ComponentSettings);
} catch (ignore) {
// ignore errors when loading .yaml file
}
}
}
public async delete(item: OpenShiftObject): Promise<void> {
const array = await item.getParent().getChildren();
array.splice(array.indexOf(item), 1);
this.pathToObject.delete(item.path);
this.contextToObject.delete(item.contextPath);
const ps = this.objectToProcess.get(item);
if (ps) ps.kill('SIGINT');
}
public deleteContext(context: Uri): void {
this.contextToSettings.delete(context);
}
}
export class OdoImpl implements Odo {
public static data: OdoModel = new OdoModel();
public static ROOT: OpenShiftObject = new OpenShiftObjectImpl(undefined, '/', undefined, false, undefined);
private static cli: cliInstance.Cli = cliInstance.CliChannel.getInstance();
private static instance: Odo;
private readonly odoLoginMessages = [
'Please log in to the cluster',
'the server has asked for the client to provide credentials',
'Please login to your server',
'Unauthorized'
];
private readonly serverDownMessages = [
'Unable to connect to OpenShift cluster, is it down?',
'no such host',
'no route to host',
'connection refused'
];
private subjectInstance: Subject<OdoEvent> = new Subject<OdoEvent>();
public static get Instance(): Odo {
if (!OdoImpl.instance) {
OdoImpl.instance = new OdoImpl();
}
return OdoImpl.instance;
}
get subject(): Subject<OdoEvent> {
return this.subjectInstance;
}
async getClusters(): Promise<OpenShiftObject[]> {
let children = OdoImpl.data.getChildrenByParent(OdoImpl.ROOT);
if (!children) {
children = OdoImpl.data.setParentToChildren(OdoImpl.ROOT, await this._getClusters());
}
return children;
}
public async _getClusters(): Promise<OpenShiftObject[]> {
let clusters: OpenShiftObject[] = await this.getClustersWithOdo();
if (clusters.length === 0) {
clusters = await this.getClustersWithOc();
}
if (clusters.length > 0 && clusters[0].contextValue === ContextType.CLUSTER) {
// kick out migration if enabled
if (!await workspace.getConfiguration("openshiftConnector").get("disableCheckForMigration")) {
this.convertObjectsFromPreviousOdoReleases();
}
}
return clusters;
}
private async getClustersWithOc(): Promise<OpenShiftObject[]> {
let clusters: OpenShiftObject[] = [];
const result: cliInstance.CliExitData = await this.execute(Command.printOcVersion(), process.cwd(), false);
clusters = result.stdout.trim().split('\n').filter((value) => {
return value.includes('Server ');
}).map((value) => {
const server: string = value.substr(value.indexOf(' ')+1).trim();
return new OpenShiftObjectImpl(null, server, ContextType.CLUSTER, false, OdoImpl.instance, TreeItemCollapsibleState.Expanded);
});
return clusters;
}
private async getClustersWithOdo(): Promise<OpenShiftObject[]> {
let clusters: OpenShiftObject[] = [];
const result: cliInstance.CliExitData = await this.execute(
Command.printOdoVersionAndProjects(), process.cwd(), false
);
if (this.odoLoginMessages.some((element) => result.stderr ? result.stderr.includes(element) : false)) {
const loginErrorMsg = 'Please log in to the cluster';
return[new OpenShiftObjectImpl(null, loginErrorMsg, ContextType.LOGIN_REQUIRED, false, OdoImpl.instance, TreeItemCollapsibleState.None)];
}
if (this.serverDownMessages.some((element) => result.stderr ? result.stderr.includes(element) : false)) {
const clusterDownMsg = 'Cannot connect to the OpenShift cluster';
return [new OpenShiftObjectImpl(null, clusterDownMsg, ContextType.CLUSTER_DOWN, false, OdoImpl.instance, TreeItemCollapsibleState.None)];
}
commands.executeCommand('setContext', 'isLoggedIn', true);
clusters = result.stdout.trim().split('\n').filter((value) => {
return value.includes('Server:');
}).map((value) => {
const server: string = value.substr(value.indexOf(':')+1).trim();
return new OpenShiftObjectImpl(null, server, ContextType.CLUSTER, false, OdoImpl.instance, TreeItemCollapsibleState.Expanded);
});
return clusters;
}
async getProjects(): Promise<OpenShiftObject[]> {
const clusters = await this.getClusters();
let projects = OdoImpl.data.getChildrenByParent(clusters[0]);
if (!projects) {
projects = OdoImpl.data.setParentToChildren(clusters[0], await this._getProjects(clusters[0]));
}
return projects;
}
public async _getProjects(cluster: OpenShiftObject): Promise<OpenShiftObject[]> {
return this.execute(Command.listProjects()).then((result) => {
const projs = this.loadItems(result).map((value) => value.metadata.name);
return projs.map<OpenShiftObject>((value) => new OpenShiftObjectImpl(cluster, value, ContextType.PROJECT, false, OdoImpl.instance));
// TODO: load projects form workspace folders and add missing ones to the model even they
// are not created in cluster they should be visible in OpenShift Application Tree
}).catch((error) => {
window.showErrorMessage(`Cannot retrieve projects for current cluster. Error: ${error}`);
return [];
});
}
async getApplications(project: OpenShiftObject): Promise<OpenShiftObject[]> {
let applications = OdoImpl.data.getChildrenByParent(project);
if (!applications) {
applications = OdoImpl.data.setParentToChildren(project, await this._getApplications(project));
}
return applications;
}
public async _getApplications(project: OpenShiftObject): Promise<OpenShiftObject[]> {
const result: cliInstance.CliExitData = await this.execute(Command.listApplications(project.getName()));
let apps: string[] = this.loadItems(result).map((value) => value.metadata.name);
apps = [...new Set(apps)]; // remove duplicates form array
// extract apps from local not yet deployed components
OdoImpl.data.getSettings().forEach((component) => {
if (component.Project === project.getName() && !apps.find((item) => item === component.Application)) {
apps.push(component.Application);
}
});
return apps.map<OpenShiftObject>((value) => new OpenShiftObjectImpl(project, value, ContextType.APPLICATION, false, OdoImpl.instance)).sort(compareNodes);
}
public async getApplicationChildren(application: OpenShiftObject): Promise<OpenShiftObject[]> {
let children = OdoImpl.data.getChildrenByParent(application);
if (!children) {
children = OdoImpl.data.setParentToChildren(application, await this._getApplicationChildren(application));
}
return children;
}
async _getApplicationChildren(application: OpenShiftObject): Promise<OpenShiftObject[]> {
return [... await this._getComponents(application), ... await this._getServices(application)].sort(compareNodes);
}
async getComponents(application: OpenShiftObject, condition: (value: OpenShiftObject) => boolean = (value) => value.contextValue === ContextType.COMPONENT || value.contextValue === ContextType.COMPONENT_NO_CONTEXT || value.contextValue === ContextType.COMPONENT_PUSHED): Promise<OpenShiftObject[]> {
return (await this.getApplicationChildren(application)).filter(condition);
}
public async _getComponents(application: OpenShiftObject): Promise<OpenShiftObject[]> {
const result: cliInstance.CliExitData = await this.execute(Command.listComponents(application.getParent().getName(), application.getName()), Platform.getUserHomePath());
const componentObject = this.loadItems(result).map(value => ({ name: value.metadata.name, source: value.spec.source }));
const deployedComponents = componentObject.map<OpenShiftObject>((value) => {
let compSource = '';
try {
if (value.source.startsWith('https://')) {
compSource = ComponentType.GIT;
} else if (statSync(Uri.parse(value.source).fsPath).isFile()) {
compSource = ComponentType.BINARY;
} else if (statSync(Uri.parse(value.source).fsPath).isDirectory()) {
compSource = ComponentType.LOCAL;
}
} catch (ignore) {
// treat component as local in case of error when calling statSync
// for not existing file or folder
compSource = ComponentType.LOCAL;
}
return new OpenShiftObjectImpl(application, value.name, ContextType.COMPONENT_NO_CONTEXT, true, this, Collapsed, undefined, compSource);
});
const targetAppName = application.getName();
const targetPrjName = application.getParent().getName();
OdoImpl.data.getSettings().filter((comp) => comp.Application === targetAppName && comp.Project === targetPrjName).forEach((comp) => {
const item = deployedComponents.find((component) => component.getName() === comp.Name);
if (item) {
item.contextPath = comp.ContextPath;
item.deployed = true;
item.contextValue = ContextType.COMPONENT_PUSHED;
item.builderImage = {name: comp.Type.split(':')[0], tag: comp.Type.split(':')[1]};
} else {
deployedComponents.push(new OpenShiftObjectImpl(application, comp.Name, ContextType.COMPONENT, false, this, Collapsed, comp.ContextPath, comp.SourceType, {name: comp.Type.split(':')[0], tag: comp.Type.split(':')[1]}));
}
});
return deployedComponents;
}
public async getComponentTypes(): Promise<string[]> {
const result: cliInstance.CliExitData = await this.execute(Command.listCatalogComponentsJson());
return this.loadItems(result).map((value) => value.metadata.name);
}
public async getComponentTypesJson(): Promise<any> {
const result: cliInstance.CliExitData = await this.execute(Command.listCatalogComponentsJson());
return JSON.parse(result.stdout).items;
}
public async getComponentChildren(component: OpenShiftObject): Promise<OpenShiftObject[]> {
let children = OdoImpl.data.getChildrenByParent(component);
if (!children) {
children = OdoImpl.data.setParentToChildren(component, await this._getComponentChildren(component));
}
return children;
}
async _getComponentChildren(component: OpenShiftObject): Promise<OpenShiftObject[]> {
return [... await this._getStorageNames(component), ... await this._getRoutes(component)].sort(compareNodes);
}
async getRoutes(component: OpenShiftObject): Promise<OpenShiftObject[]> {
return (await this.getComponentChildren(component)).filter((value) => value.contextValue === ContextType.COMPONENT_ROUTE);
}
async getComponentPorts(component: OpenShiftObject): Promise<odo.Port[]> {
let ports: string[] = [];
if (component.contextValue === ContextType.COMPONENT_PUSHED) {
const portsResult: CliExitData = await this.execute(Command.getComponentJson(), component.contextPath.fsPath);
const serviceOpj = JSON.parse(portsResult.stdout);
ports = serviceOpj.spec.ports;
} else {
const settings: ComponentSettings = OdoImpl.data.getSettingsByContext(component.contextPath);
if (settings) {
ports = settings.Ports;
}
}
return ports.map<odo.Port>((port: string) => {
const data = port.split('/');
return {Number: Number.parseInt(data[0]), Protocol: data[1]};
});
}
public async _getRoutes(component: OpenShiftObject): Promise<OpenShiftObject[]> {
const result: cliInstance.CliExitData = await this.execute(Command.getComponentUrl(), component.contextPath ? component.contextPath.fsPath : Platform.getUserHomePath(), false);
return this.loadItems(result).map((value) => new OpenShiftObjectImpl(component, value.metadata.name, ContextType.COMPONENT_ROUTE, false, OdoImpl.instance, TreeItemCollapsibleState.None));
}
async getStorageNames(component: OpenShiftObject): Promise<OpenShiftObject[]> {
return (await this.getComponentChildren(component)).filter((value) => value.contextValue === ContextType.STORAGE);
}
public async _getStorageNames(component: OpenShiftObject): Promise<OpenShiftObject[]> {
const result: cliInstance.CliExitData = await this.execute(Command.listStorageNames(), component.contextPath ? component.contextPath.fsPath : Platform.getUserHomePath());
return this.loadItems(result).map<OpenShiftObject>((value) => new OpenShiftObjectImpl(component, value.metadata.name, ContextType.STORAGE, false, OdoImpl.instance, TreeItemCollapsibleState.None));
}
public async getComponentTypeVersions(componentName: string): Promise<any> {
const result: cliInstance.CliExitData = await this.execute(Command.listCatalogComponentsJson());
return this.loadItems(result).filter((value) => value.metadata.name === componentName)[0].spec.allTags;
}
public async getServiceTemplates(): Promise<string[]> {
let items: any[] = [];
const result: cliInstance.CliExitData = await this.execute(Command.listCatalogServicesJson(), Platform.getUserHomePath(), false);
try {
items = JSON.parse(result.stdout).items;
} catch (err) {
throw new Error(JSON.parse(result.stderr).message);
}
return items.map((value) => value.metadata.name);
}
public async getServiceTemplatePlans(svcName: string): Promise<string[]> {
const result: cliInstance.CliExitData = await this.execute(Command.listCatalogServicesJson(), Platform.getUserHomePath());
return this.loadItems(result).filter((value) => value.metadata.name === svcName)[0].spec.planList;
}
async getServices(application: OpenShiftObject): Promise<OpenShiftObject[]> {
return (await this.getApplicationChildren(application)).filter((value) => value.contextValue === ContextType.SERVICE);
}
public async _getServices(application: OpenShiftObject): Promise<OpenShiftObject[]> {
const appName: string = application.getName();
const projName: string = application.getParent().getName();
let services: OpenShiftObject[] = [];
try {
const result: cliInstance.CliExitData = await this.execute(Command.listServiceInstances(projName, appName));
services = this.loadItems(result)
.map((value) => new OpenShiftObjectImpl(application, value.metadata.name, ContextType.SERVICE, true, OdoImpl.instance, TreeItemCollapsibleState.None));
} catch (ignore) {
// ignore error in case service catalog is not configured
}
commands.executeCommand('setContext', 'servicePresent', services.length>0);
return services;
}
public async executeInTerminal(command: string, cwd: string = process.cwd(), name = 'OpenShift'): Promise<void> {
const cmd = command.split(' ')[0];
const toolLocation = await ToolsConfig.detectOrDownload(cmd);
let toolDirLocation: string;
if (toolLocation) {
toolDirLocation = path.dirname(toolLocation);
}
const terminal: Terminal = WindowUtil.createTerminal(name, cwd);
terminal.sendText(toolDirLocation ? command.replace(cmd, `"${toolLocation}"`).replace(new RegExp(`&& ${cmd}`, 'g'), `&& "${toolLocation}"`) : command, true);
terminal.show();
}
public async execute(command: string, cwd?: string, fail = true): Promise<CliExitData> {
const cmd = command.split(' ')[0];
const toolLocation = await ToolsConfig.detectOrDownload(cmd);
return OdoImpl.cli.execute(
toolLocation ? command.replace(cmd, `"${toolLocation}"`).replace(new RegExp(`&& ${cmd}`, 'g'), `&& "${toolLocation}"`) : command,
cwd ? {cwd} : { }
).then(async (result) => result.error && fail ? Promise.reject(result.error) : result).catch((err) => fail ? Promise.reject(err) : Promise.resolve({error: null, stdout: '', stderr: ''}));
}
public async requireLogin(): Promise<boolean> {
const result: cliInstance.CliExitData = await this.execute(Command.printOdoVersionAndProjects(), process.cwd(), false);
return this.odoLoginMessages.some((msg) => result.stderr.includes(msg));
}
private insert(array: OpenShiftObject[], item: OpenShiftObject): OpenShiftObject {
const i = bs(array, item, compareNodes);
array.splice(Math.abs(i)-1, 0, item);
return item;
}
private async insertAndReveal(item: OpenShiftObject): Promise<OpenShiftObject> {
// await OpenShiftExplorer.getInstance().reveal(this.insert(await item.getParent().getChildren(), item));
this.subject.next(new OdoEventImpl('inserted', this.insert(await item.getParent().getChildren(), item), true));
return item;
}
private async insertAndRefresh(item: OpenShiftObject): Promise<OpenShiftObject> {
// await OpenShiftExplorer.getInstance().refresh(this.insert(await item.getParent().getChildren(), item).getParent());
this.subject.next(new OdoEventImpl('changed', this.insert(await item.getParent().getChildren(), item).getParent()));
return item;
}
private deleteAndRefresh(item: OpenShiftObject): OpenShiftObject {
OdoImpl.data.delete(item);
// OpenShiftExplorer.getInstance().refresh(item.getParent());
this.subject.next(new OdoEventImpl('changed', item.getParent()));
return item;
}
public async deleteProject(project: OpenShiftObject): Promise<OpenShiftObject> {
await this.execute(Command.deleteProject(project.getName()));
await this.execute(Command.waitForProjectToBeGone(project.getName()), process.cwd(), false);
return this.deleteAndRefresh(project);
}
public async createProject(projectName: string): Promise<OpenShiftObject> {
await OdoImpl.instance.execute(Command.createProject(projectName));
const clusters = await this.getClusters();
return this.insertAndReveal(new OpenShiftObjectImpl(clusters[0], projectName, ContextType.PROJECT, false, this));
}
public async deleteApplication(app: OpenShiftObject): Promise<OpenShiftObject> {
const allComps = await OdoImpl.instance.getComponents(app);
const allContexts = [];
let callDelete = false;
allComps.forEach((component) => {
OdoImpl.data.delete(component); // delete component from model
if (!callDelete && component.contextValue === ContextType.COMPONENT_PUSHED || component.contextValue === ContextType.COMPONENT_NO_CONTEXT) {
callDelete = true; // if there is at least one component deployed in application `odo app delete` command should be called
}
if (component.contextPath) { // if component has context folder save it to remove from settings cache
allContexts.push(workspace.getWorkspaceFolder(component.contextPath));
}
});
if (callDelete) {
await this.execute(Command.deleteApplication(app.getParent().getName(), app.getName()));
}
// Chain workspace folder deltions, because when updateWorkspaceFoder called next call is possible only after
// listener registered with onDidChangeWorkspaceFolders called.
let result = Promise.resolve();
allContexts.forEach((wsFolder) => {
result = result.then(() => {
workspace.updateWorkspaceFolders(wsFolder.index, 1);
return new Promise<void>((resolve) => {
const disposable = workspace.onDidChangeWorkspaceFolders(() => {
disposable.dispose();
resolve();
});
});
});
});
return result.then(() => {
return this.deleteAndRefresh(app);
});
}
public async createApplication(application: OpenShiftObject): Promise<OpenShiftObject> {
const targetApplication = (await this.getApplications(application.getParent())).find((value) => value === application);
if (!targetApplication) {
await this.insertAndReveal(application);
}
return application;
}
public async createComponentFromFolder(application: OpenShiftObject, type: string, version: string, name: string, location: Uri): Promise<OpenShiftObject> {
await this.execute(Command.createLocalComponent(application.getParent().getName(), application.getName(), type, version, name, location.fsPath), location.fsPath);