forked from redhat-developer/vscode-openshift-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexplorer.ts
More file actions
283 lines (251 loc) · 11.2 KB
/
explorer.ts
File metadata and controls
283 lines (251 loc) · 11.2 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
/*-----------------------------------------------------------------------------------------------
* Copyright (c) Red Hat, Inc. All rights reserved.
* Licensed under the MIT License. See LICENSE file in the project root for license information.
*-----------------------------------------------------------------------------------------------*/
import {
TreeDataProvider,
TreeItem,
Event,
EventEmitter,
Disposable,
TreeView,
window,
extensions,
version,
commands,
Uri,
TreeItemCollapsibleState,
ThemeIcon,
} from 'vscode';
import * as path from 'path';
import * as fs from 'fs';
import { Platform } from './util/platform';
import { WatchUtil, FileContentChangeNotifier } from './util/watch';
import { KubeConfigUtils } from './util/kubeUtils';
import { vsCommand } from './vscommand';
import { KubernetesObject, Context } from '@kubernetes/client-node';
import { CliChannel } from './cli';
import { Command } from './odo/command';
import { newInstance, Odo3 } from './odo3';
const kubeConfigFolder: string = path.join(Platform.getUserHomePath(), '.kube');
type ExplorerItem = KubernetesObject | Context | TreeItem;
type PackageJSON = {
version: string;
bugs: string;
};
const CREATE_OR_SET_PROJECT_ITEM = {
label: 'Create new or set active Project',
command: {
title: 'Create new or ser active Project',
command: 'openshift.project.set'
}
};
export class OpenShiftExplorer implements TreeDataProvider<ExplorerItem>, Disposable {
private static instance: OpenShiftExplorer;
private treeView: TreeView<ExplorerItem>;
private fsw: FileContentChangeNotifier;
private kubeContext: Context;
private kubeConfig: KubeConfigUtils;
private eventEmitter: EventEmitter<ExplorerItem | undefined> =
new EventEmitter<ExplorerItem | undefined>();
readonly onDidChangeTreeData: Event<ExplorerItem | undefined> = this
.eventEmitter.event;
private odo3: Odo3 = newInstance();
private constructor() {
try {
this.kubeConfig = new KubeConfigUtils();
this.kubeContext = this.kubeConfig.getContextObject(this.kubeConfig.currentContext);
} catch (err) {
// ignore config loading error and let odo report it on first call
}
try {
this.fsw = WatchUtil.watchFileForContextChange(kubeConfigFolder, 'config');
} catch (err) {
void window.showWarningMessage('Couldn\'t install watcher for Kubernetes configuration file. OpenShift Application Explorer view won\'t be updated automatically.');
}
this.fsw?.emitter?.on('file-changed', () => {
const ku2 = new KubeConfigUtils();
const newCtx = ku2.getContextObject(ku2.currentContext);
if (!this.kubeContext
|| (this.kubeContext.cluster !== newCtx.cluster
|| this.kubeContext.user !== newCtx.user
|| this.kubeContext.namespace !== newCtx.namespace)) {
this.refresh();
}
this.kubeContext = newCtx;
this.kubeConfig = ku2;
});
this.treeView = window.createTreeView<ExplorerItem>('openshiftProjectExplorer', {
treeDataProvider: this,
});
}
async getCurrentClusterUrl(): Promise<string | undefined> {
// print odo version and Server URL if user is logged in
const result = await CliChannel.getInstance().executeTool(Command.printOdoVersion());
// search for line with 'Server:' substring
const clusterLine = result.stdout.trim().split('\n').find((value) => value.includes('Server:'));
// if line with Server: is printed out it means user is logged in
void commands.executeCommand('setContext', 'isLoggedIn', !!clusterLine);
// cut out server url after 'Server:' substring
return clusterLine ? clusterLine.substring(clusterLine.indexOf(':') + 1).trim() : undefined;
}
static getInstance(): OpenShiftExplorer {
if (!OpenShiftExplorer.instance) {
OpenShiftExplorer.instance = new OpenShiftExplorer();
}
return OpenShiftExplorer.instance;
}
// eslint-disable-next-line class-methods-use-this
getTreeItem(element: ExplorerItem): TreeItem | Thenable<TreeItem> {
if ('command' in element) {
return element;
}
if('label' in element) {
return {
contextValue: 'openshift.openConfigFile',
label: element.label,
collapsibleState: TreeItemCollapsibleState.None,
tooltip: 'Default KubeConfig',
description: element.description,
iconPath: new ThemeIcon('file')
};
}
// check if element is Context instance
if ('name' in element && 'cluster' in element && 'user' in element) { // Context instance could be without namespace
return {
contextValue: 'openshift.k8sContext',
label: this.kubeConfig.getCluster(element.cluster).server,
collapsibleState: TreeItemCollapsibleState.Collapsed,
iconPath: path.resolve(__dirname, '../../images/context/cluster-node.png')
};
}
// otherwise it is a KubernetesObject instance
if ('kind' in element) {
if (element.kind === 'project') {
return {
contextValue: 'openshift.project',
label: element.metadata.name,
collapsibleState: TreeItemCollapsibleState.Collapsed,
iconPath: path.resolve(__dirname, '../../images/context/project-node.png')
}
}
return {
contextValue: 'openshift.k8sObject',
label: element.metadata.name,
collapsibleState: TreeItemCollapsibleState.None,
iconPath: path.resolve(__dirname, '../../images/context/component-node.png'),
command: {
title: 'Load',
command: 'openshift.resource.load',
arguments: [element]
}
};
}
return {
label: 'Unknown element'
}
}
// eslint-disable-next-line class-methods-use-this
async getChildren(element?: ExplorerItem): Promise<ExplorerItem[]> {
let result: ExplorerItem[] = [];
if (!element) {
try {
await this.odo3.getNamespaces()
result = [this.kubeContext];
if (this.kubeContext) {
const homeDir = this.kubeConfig.findHomeDir();
if (homeDir){
const config = path.join(homeDir, '.kube', 'config');
result.unshift({label: 'Default KubeConfig', description: `${config}`})
}
}
} catch (err) {
// ignore because ether server is not accessible or user is logged out
}
} else if ('name' in element) { // we are dealing with context here
// user is logged into cluster from current context
// and project should be show as child node of current context
// there are several possible scenarios
// (1) there is no namespace set in context and default namespace/project exists
// * example is kubernetes provisioned with docker-desktop
// * could also be the case with CRC provisioned for the first time
// (2) there is no namespace set in context and default namespace/project does not exist
// * example is sandbox context created when login to sandbox first time
// (3) there is namespace set in context and namespace exists in the cluster
// (4) there is namespace set in context and namespace does not exist in the cluster
const pOrNs = await this.odo3.getNamespaces();
if (this.kubeContext.namespace) {
if (pOrNs.find(item => item?.metadata.name === this.kubeContext.namespace)) {
result = [{
kind: 'project',
metadata: {
name: this.kubeContext.namespace,
},
} as KubernetesObject]
} else {
result = [CREATE_OR_SET_PROJECT_ITEM]
}
} else {
// get list of projects or namespaces
// find default namespace
if (pOrNs.find(item => item?.metadata.name === 'default')) {
result = [{
kind: 'project',
metadata: {
name: 'default',
},
} as KubernetesObject]
} else {
result = [CREATE_OR_SET_PROJECT_ITEM]
}
}
} else {
result = [...await this.odo3.getDeploymentConfigs(), ...await this.odo3.getDeployments()];
}
if (!element) {
await commands.executeCommand('setContext', 'openshift.app.explorer.init', result.length === 0);
}
return result;
}
refresh(target?: ExplorerItem): void {
this.eventEmitter.fire(target);
}
dispose(): void {
this.fsw?.watcher?.close();
this.treeView.dispose();
}
@vsCommand('openshift.resource.load')
public static loadResource(component: KubernetesObject) {
void commands.executeCommand('extension.vsKubernetesLoad', {namespace: component.metadata.namespace, kindName: `${component.kind}/${component.metadata.name}`});
}
@vsCommand('openshift.resource.openInConsole')
public static openInConsole(component: KubernetesObject) {
void commands.executeCommand('extension.vsKubernetesLoad', {namespace: component.metadata.namespace, kindName: `${component.kind}/${component.metadata.name}`});
}
@vsCommand('openshift.explorer.reportIssue')
static async reportIssue(): Promise<unknown> {
const extensionPath = path.resolve(__dirname, '..', '..');
const templatePath = path.join(extensionPath,'resources', 'issueReport.md');
const template = fs.readFileSync(templatePath, 'utf-8');
return commands.executeCommand('workbench.action.openIssueReporter', {
extensionId: 'redhat.vscode-openshift-connector',
issueBody: template
});
}
@vsCommand('openshift.open.configFile')
async openConfigFile(context: TreeItem): Promise<void> {
if(context.description && typeof context.description === 'string'){
await commands.executeCommand('vscode.open', Uri.file(context.description));
}
}
static issueUrl(): string {
const packageJSON: PackageJSON = extensions.getExtension('redhat.vscode-openshift-connector')
.packageJSON as PackageJSON;
const body = [
`VS Code version: ${version}`,
`OS: ${Platform.OS}`,
`Extension version: ${packageJSON.version}`,
].join('\n');
return `${packageJSON.bugs}/new?labels=kind/bug&title=&body=**Environment**\n${body}\n**Description**`;
}
}