forked from redhat-developer/vscode-openshift-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcluster.ts
More file actions
828 lines (773 loc) · 36.8 KB
/
cluster.ts
File metadata and controls
828 lines (773 loc) · 36.8 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
/*-----------------------------------------------------------------------------------------------
* Copyright (c) Red Hat, Inc. All rights reserved.
* Licensed under the MIT License. See LICENSE file in the project root for license information.
*-----------------------------------------------------------------------------------------------*/
import { KubernetesObject } from '@kubernetes/client-node';
import { ExtensionContext, InputBox, QuickInputButton, QuickInputButtons, QuickPickItem, QuickPickItemButtonEvent, ThemeIcon, Uri, commands, env, window, workspace } from 'vscode';
import { CommandText } from '../base/command';
import { CliChannel } from '../cli';
import { OpenShiftExplorer } from '../explorer';
import { Oc } from '../oc/ocWrapper';
import { Command } from '../odo/command';
import { Odo } from '../odo/odoWrapper';
import * as NameValidator from '../openshift/nameValidator';
import { TokenStore } from '../util/credentialManager';
import { Filters } from '../util/filters';
import { KubeConfigUtils } from '../util/kubeUtils';
import { LoginUtil } from '../util/loginUtil';
import { Platform } from '../util/platform';
import { Progress } from '../util/progress';
import { VsCommandError, vsCommand } from '../vscommand';
import { OpenShiftTerminalManager } from '../webview/openshift-terminal/openShiftTerminal';
import OpenShiftItem, { clusterRequired } from './openshiftItem';
import fetch = require('make-fetch-happen');
class quickBtn implements QuickInputButton {
constructor(public iconPath: ThemeIcon, public tooltip: string) { }
}
export class Cluster extends OpenShiftItem {
public static extensionContext: ExtensionContext;
@vsCommand('openshift.explorer.logout')
static async logout(): Promise<string> {
const value = await window.showWarningMessage(
'Do you want to logout of cluster?',
'Logout',
'Cancel',
);
if (value === 'Logout') {
return Oc.Instance.logout()
.catch((error) =>
Promise.reject(
new VsCommandError(
`Failed to logout of the current cluster with '${error}'!`,
'Failed to logout of the current cluster',
),
),
)
.then(async () => {
OpenShiftExplorer.getInstance().refresh();
Cluster.serverlessView.refresh();
void commands.executeCommand('setContext', 'isLoggedIn', false);
const logoutInfo = await window.showInformationMessage(
'Successfully logged out. Do you want to login to a new cluster',
'Yes',
'No',
);
if (logoutInfo === 'Yes') {
return Cluster.login(undefined, true);
}
return null;
});
}
return null;
}
@vsCommand('openshift.explorer.refresh')
static refresh(): void {
OpenShiftExplorer.getInstance().refresh();
Cluster.serverlessView.refresh();
}
@vsCommand('openshift.about')
static async about(): Promise<void> {
await OpenShiftTerminalManager.getInstance().executeInTerminal(Command.printOdoVersion(), undefined, 'Show odo Version');
}
@vsCommand('openshift.oc.about')
static async ocAbout(): Promise<void> {
await OpenShiftTerminalManager.getInstance().executeInTerminal(new CommandText('oc', 'version'), undefined, 'Show OKD CLI Tool Version');
}
@vsCommand('openshift.output')
static showOpenShiftOutput(): void {
CliChannel.getInstance().showOutput();
}
@vsCommand('openshift.open.developerConsole', true)
@clusterRequired()
static async openOpenshiftConsole(): Promise<void> {
return Progress.execFunctionWithProgress('Opening Console Dashboard', async (progress) => {
const consoleUrl = (await Oc.Instance.getConsoleInfo()).url;
progress.report({ increment: 100, message: 'Starting default browser' });
return commands.executeCommand('vscode.open', Uri.parse(consoleUrl));
});
}
@vsCommand('openshift.open.operatorBackedServiceCatalog')
@clusterRequired()
static async openOpenshiftConsoleTopography(): Promise<void> {
return Progress.execFunctionWithProgress(
'Opening Operator Backed Service Catalog',
async (progress) => {
const [consoleInfo, namespace] = await Promise.all([
Oc.Instance.getConsoleInfo(),
Odo.Instance.getActiveProject(),
]);
progress.report({ increment: 100, message: 'Starting default browser' });
// eg. https://console-openshift-console.apps-crc.testing/catalog/ns/default?catalogType=OperatorBackedService
// FIXME: handle standard k8s dashboard
return commands.executeCommand(
'vscode.open',
Uri.parse(
`${consoleInfo.url}/catalog/ns/${namespace}?catalogType=OperatorBackedService`,
),
);
},
);
}
@vsCommand('openshift.resource.openInDeveloperConsole')
@clusterRequired()
static async openInDeveloperConsole(resource: KubernetesObject): Promise<void> {
return Progress.execFunctionWithProgress('Opening Console Dashboard', async (progress) => {
const consoleInfo = await Oc.Instance.getConsoleInfo();
progress.report({ increment: 100, message: 'Starting default browser' });
// FIXME: handle standard k8s dashboard
return commands.executeCommand(
'vscode.open',
Uri.parse(
`${consoleInfo.url}/topology/ns/${resource.metadata.namespace}?selectId=${resource.metadata.uid}&view=graph`,
),
);
});
}
@vsCommand('openshift.explorer.switchContext')
static async switchContext(): Promise<string> {
return new Promise<string>((resolve, reject) => {
const k8sConfig = new KubeConfigUtils();
const contexts = k8sConfig.contexts.filter(
(item) => item.name !== k8sConfig.currentContext,
);
const deleteBtn = new quickBtn(new ThemeIcon('trash'), 'Delete');
const quickPick = window.createQuickPick();
const contextNames: QuickPickItem[] = contexts.map((ctx) => ({
label: `${ctx.name}`,
buttons: [deleteBtn],
}));
quickPick.items = contextNames;
const cancelBtn = new quickBtn(new ThemeIcon('close'), 'Cancel');
quickPick.buttons = [QuickInputButtons.Back, cancelBtn];
if (contextNames.length === 0) {
void window
.showInformationMessage(
'You have no Kubernetes contexts yet, please login to a cluster.',
'Login',
'Cancel',
)
.then((command: string) => {
if (command === 'Login') {
resolve(Cluster.login(undefined, true));
}
resolve(null);
});
} else {
let selection: readonly QuickPickItem[] | undefined;
const hideDisposable = quickPick.onDidHide(() => resolve(null));
quickPick.onDidChangeSelection((selects) => {
selection = selects;
});
quickPick.onDidAccept(() => {
const choice = selection[0];
hideDisposable.dispose();
quickPick.hide();
Oc.Instance.setContext(choice.label)
.then(() => resolve(`Cluster context is changed to: ${choice.label}.`))
.catch(reject);
});
quickPick.onDidTriggerButton((button) => {
if (button === QuickInputButtons.Back || button === cancelBtn) quickPick.hide();
});
quickPick.onDidTriggerItemButton(async (event: QuickPickItemButtonEvent<QuickPickItem>) => {
if (event.button === deleteBtn) {
await window.showInformationMessage(`Do you want to delete '${event.item.label}' Context from Kubernetes configuration?`, 'Yes', 'No')
.then((command: string) => {
if (command === 'Yes') {
const context = k8sConfig.getContextObject(event.item.label);
const index = contexts.indexOf(context);
if (index > -1) {
Oc.Instance.deleteContext(context.name)
.then(() => resolve(`Context ${context.name} deleted.`))
.catch(reject);
}
}
});
}
});
quickPick.show();
}
});
}
static async getUrl(): Promise<string | null | undefined> {
const clusterURl = await Cluster.getUrlFromClipboard();
return await Cluster.showQuickPick(clusterURl);
}
private static async showQuickPick(clusterURl: string): Promise<string> {
return new Promise<string | null>((resolve, reject) => {
const k8sConfig = new KubeConfigUtils();
const deleteBtn = new quickBtn(new ThemeIcon('trash'), 'Delete');
const createUrl: QuickPickItem = { label: '$(plus) Provide new URL...' };
const clusterItems = k8sConfig.getServers();
const quickPick = window.createQuickPick();
const contextNames: QuickPickItem[] = clusterItems.map((ctx) => ({
...ctx,
buttons: ctx.description ? [] : [deleteBtn],
}));
quickPick.items = [createUrl, ...contextNames];
const cancelBtn = new quickBtn(new ThemeIcon('close'), 'Cancel');
quickPick.buttons = [QuickInputButtons.Back, cancelBtn];
let selection: readonly QuickPickItem[] | undefined;
const hideDisposable = quickPick.onDidHide(() => resolve(null));
quickPick.onDidAccept(async () => {
const choice = selection[0];
hideDisposable.dispose();
quickPick.hide();
if (choice.label === createUrl.label) {
const prompt = 'Provide new Cluster URL to connect';
const validateInput = (value: string) => NameValidator.validateUrl('Invalid URL provided', value);
const newURL = await this.enterValue(prompt, '', false, validateInput);
if (newURL === null) return null; // Cancel
else if (!newURL) resolve(await Cluster.showQuickPick(clusterURl)); // Back
else resolve(newURL);
} else {
resolve(choice.label);
}
});
quickPick.onDidChangeSelection((selects) => {
selection = selects;
});
quickPick.onDidTriggerButton((button) => {
hideDisposable.dispose();
quickPick.hide();
if (button === QuickInputButtons.Back) quickPick.hide();
else if (button === cancelBtn) resolve(null);
});
quickPick.onDidTriggerItemButton(async (event) => {
if (event.button === deleteBtn) {
await window.showInformationMessage(`Do you want to delete ${event.item.label} Cluster and all the related Contexts and Users form Kubernetes configuration?`, 'Yes', 'No')
.then( async (command: string) => {
if (command === 'Yes') {
const cluster = k8sConfig.getClusters().find((kubeConfigCluster) => kubeConfigCluster.server === event.item.label);
const contexts = k8sConfig.getContexts().filter((kubeContext) => kubeContext.cluster === cluster.name);
// find users and remove duplicates
const users = [ ...new Set(contexts.map(context => k8sConfig.getUser(context.user)))];
await Promise.all(
contexts.map((context) =>
Oc.Instance.deleteContext(context.name),
),
)
.then(() =>
Promise.all(
users.map((user) =>
Oc.Instance.deleteUser(user.name)
),
),
)
.then(() =>
Oc.Instance.deleteCluster(cluster.name)
)
.catch(reject);
}
});
}
});
quickPick.show();
});
}
@vsCommand('openshift.explorer.stopCluster')
static async stop(): Promise<void> {
let pathSelectionDialog;
let newPathPrompt;
let crcBinary;
const crcPath: string = workspace
.getConfiguration('openshiftToolkit')
.get('crcBinaryLocation');
if (crcPath) {
newPathPrompt = { label: '$(plus) Provide different OpenShift Local file path' };
pathSelectionDialog = await window.showQuickPick(
[{ label: `${crcPath}`, description: 'Fetched from settings' }, newPathPrompt],
{ placeHolder: 'Select OpenShift Local file path', ignoreFocusOut: true },
);
}
if (!pathSelectionDialog) return;
if (pathSelectionDialog.label === newPathPrompt.label) {
const crcBinaryLocation = await window.showOpenDialog({
canSelectFiles: true,
canSelectFolders: false,
canSelectMany: false,
defaultUri: Uri.file(Platform.getUserHomePath()),
openLabel: 'Add OpenShift Local file path.',
});
if (!crcBinaryLocation) return null;
crcBinary = crcBinaryLocation[0].fsPath;
} else {
crcBinary = crcPath;
}
void OpenShiftTerminalManager.getInstance().executeInTerminal(new CommandText(`${crcBinary}`, 'stop'), undefined, 'Stop OpenShift Local');
}
/*
* Shows a Quick Pick to select a cluster login method. Returns either:
* - login method string, or
* - `null` in case of user cancelled (pressed `ESC`), or
* - `undefined` if user pressed `Back` button
* @returns string contaning cluster login method name or null if cancelled or undefined if Back is pressed
*/
private static async getLoginMethod(): Promise<string | null | undefined> {
return new Promise<string | null | undefined>((resolve, reject) => {
const loginActions: QuickPickItem[] = [
{
label: 'Credentials',
description: 'Log in to the given server using credentials',
},
{
label: 'Token',
description: 'Log in to the given server using bearer token',
}
];
const quickPick = window.createQuickPick();
quickPick.items = [...loginActions];
const cancelBtn = new quickBtn(new ThemeIcon('close'), 'Cancel');
quickPick.buttons = [QuickInputButtons.Back, cancelBtn];
let selection: readonly QuickPickItem[] | undefined;
const hideDisposable = quickPick.onDidHide(() => resolve(null));
quickPick.onDidAccept(() => {
const choice = selection[0];
hideDisposable.dispose();
quickPick.hide();
resolve(choice.label);
});
quickPick.onDidChangeSelection((selects) => {
selection = selects;
});
quickPick.onDidTriggerButton((button) => {
hideDisposable.dispose();
quickPick.hide();
if (button === QuickInputButtons.Back) resolve(undefined);
else if (button === cancelBtn) resolve(null);
});
quickPick.show();
});
}
@vsCommand('openshift.explorer.login')
static async login(context?: any, skipConfirmation = false): Promise<string> {
const response = await Cluster.requestLoginConfirmation(skipConfirmation);
if (response !== 'Yes') return null;
let clusterURL: string;
enum Step {
selectCluster = 'selectCluster',
selectLoginMethod = 'selectLoginMethod',
loginUsingCredentials = 'loginUsingCredentials',
loginUsingToken = 'loginUsingToken'
}
let step: Step = Step.selectCluster;
while (step !== undefined) {
switch (step) {
case Step.selectCluster: {
let clusterIsUp = false;
do {
clusterURL = await Cluster.getUrl();
if (!clusterURL) return null;
try {
await fetch(`${clusterURL}/api`, {
// disable cert checking. crc uses a self-signed cert,
// which means this request will always fail on crc unless cert checking is disabled
strictSSL: false
});
// since the fetch didn't throw an exception,
// a route to the cluster is available,
// so it's running
clusterIsUp = true;
} catch (e) {
let clusterURLObj: any = undefined;
try {
clusterURLObj = new URL(clusterURL);
} catch (_) {
// Ignore
}
if (clusterURLObj && clusterURLObj.hostname === 'api.crc.testing') {
const startCrc = 'Start OpenShift Local';
const promptResponse = await window.showWarningMessage(
'The cluster appears to be a OpenShift Local cluster, but it isn\'t running',
'Use a different cluster',
startCrc,
);
if (promptResponse === startCrc){
await commands.executeCommand('openshift.explorer.addCluster', 'crc');
// no point in continuing with the wizard,
// it will take the cluster a few minutes to stabilize
return null;
}
} else if (clusterURLObj && /api\.sandbox-.*openshiftapps\.com/.test(clusterURLObj.hostname)) {
const devSandboxSignup = 'Sign up for OpenShift Dev Sandbox';
const promptResponse = await window.showWarningMessage(
'The cluster appears to be a OpenShift Dev Sandbox cluster, but it isn\'t running',
'Use a different cluster',
devSandboxSignup,
);
if (promptResponse === devSandboxSignup){
await commands.executeCommand('openshift.explorer.addCluster', 'sandbox');
// no point in continuing with the wizard,
// the user needs to sign up for the service
return null;
}
} else {
void window.showWarningMessage(
'Unable to contact the cluster. Is it running and accessible?',
);
}
}
} while (!clusterIsUp);
step = Step.selectLoginMethod;
break;
}
case Step.selectLoginMethod: {
const result = await Cluster.getLoginMethod();
if (result === null) { // User cancelled the operation
return null;
} else if (!result) { // Back button is hit
step = Step.selectCluster;
} else if(result === 'Credentials') {
step = Step.loginUsingCredentials;
} else if (result === 'Token') {
step = Step.loginUsingToken;
}
break;
}
case Step.loginUsingCredentials: // Drop down
case Step.loginUsingToken: {
const clusterVersions: string = step === Step.loginUsingCredentials
? await Cluster.credentialsLogin(true, clusterURL)
: await Cluster.tokenLogin(clusterURL, true);
if (clusterVersions === null) { // User cancelled the operation
return null;
} else if (!clusterVersions) { // Back button is hit
step = Step.selectLoginMethod;
} else {
// login successful
return null;
}
break;
}
default:
break;
}
}
}
private static async requestLoginConfirmation(skipConfirmation = false): Promise<string> {
let response = 'Yes';
if (!skipConfirmation && !(await LoginUtil.Instance.requireLogin())) {
const cluster = new KubeConfigUtils().getCurrentCluster();
response = await window.showInformationMessage(
`You are already logged into ${cluster.server} cluster. Do you want to login to a different cluster?`,
'Yes',
'No',
);
}
return response;
}
private static async save(
username: string,
password: string,
checkpassword: string,
): Promise<void> {
if (password === checkpassword) return;
const response = await window.showInformationMessage(
'Do you want to save username and password?',
'Yes',
'No',
);
if (response === 'Yes') {
await TokenStore.setUserName(username);
await TokenStore.setItem('login', username, password);
}
}
/*
* Shows a Quick Pick to select or type in a username. Returns either:
* - username string, or
* - `null` in case of user cancelled (pressed `ESC`), or
* - `undefined` if user pressed `Back` button
* @returns string contaning user name or null if cancelled or undefined if Back is pressed
*/
private static async getUserName(clusterURL: string, addUserLabel: string): Promise<string | null | undefined> {
return new Promise<string | null | undefined>((resolve, reject) => {
const users = new KubeConfigUtils().getClusterUsers(clusterURL);
const addUser: QuickPickItem = { label: addUserLabel };
const quickPick = window.createQuickPick();
quickPick.items = [addUser, ...users];
const cancelBtn = new quickBtn(new ThemeIcon('close'), 'Cancel');
quickPick.buttons = [QuickInputButtons.Back, cancelBtn];
let selection: readonly QuickPickItem[] | undefined;
const hideDisposable = quickPick.onDidHide(() => resolve(null));
quickPick.onDidAccept(() => {
const choice = selection[0];
hideDisposable.dispose();
quickPick.hide();
resolve(choice.label);
});
quickPick.onDidChangeSelection((selects) => {
selection = selects;
});
quickPick.onDidTriggerButton((button) => {
hideDisposable.dispose();
quickPick.hide();
if (button === QuickInputButtons.Back) resolve(undefined);
else if (button === cancelBtn) resolve(null);
});
quickPick.show();
});
}
/*
* Shows a Input Field to type in a username. Returns either:
* - username string, or
* - `null` in case of user cancelled (pressed `ESC`), or
* - `undefined` if user pressed `Back` button
* @returns string contaning user name or null if cancelled or undefined if Back is pressed
*/
private static async enterValue(prompt: string, initialValue: string, password: boolean, validate ): Promise<string | null | undefined> {
return new Promise<string | null | undefined>((resolve, reject) => {
const input: InputBox = window.createInputBox();
input.value = initialValue;
input.prompt = prompt;
input.password = password;
const enterBtn = new quickBtn(new ThemeIcon('check'), 'Enter');
const cancelBtn = new quickBtn(new ThemeIcon('close'), 'Cancel');
input.buttons = [QuickInputButtons.Back, enterBtn, cancelBtn];
const validationMessage: string = validate(input.value? input.value : '');
input.ignoreFocusOut = true;
if (validationMessage) {
input.validationMessage = validationMessage;
}
const acceptInput = async () => {
const value = input.value;
input.enabled = false;
input.busy = true;
if (!(await validate(value))) {
input.hide();
resolve(value);
}
input.enabled = true;
input.busy = false;
};
input.onDidAccept(acceptInput);
input.onDidChangeValue(async text => {
const current = validate(text);
const validating = current;
const validationMessage = await current;
if (current === validating) {
input.validationMessage = validationMessage;
}
});
input.onDidHide(() => {
input.dispose();
})
input.onDidTriggerButton(async (event) => {
if (event === QuickInputButtons.Back) resolve(undefined);
else if (event === enterBtn) await acceptInput();
else if (event === cancelBtn) {
resolve(null);
input.dispose();
}
});
input.show();
});
}
@vsCommand('openshift.explorer.login.credentialsLogin')
static async credentialsLogin(skipConfirmation = false, userClusterUrl?: string, userName?: string, userPassword?: string): Promise<string | null | undefined> {
let password: string;
const response = await Cluster.requestLoginConfirmation(skipConfirmation);
if (response !== 'Yes') return null;
let clusterURL = userClusterUrl;
if (!clusterURL) {
clusterURL = await Cluster.getUrl();
}
if (!clusterURL) return null;
enum Step {
'getUserName',
'enterUserName',
'enterPassword'
}
let username = userName;
// const getUserName = await TokenStore.getUserName();
let passwd = userPassword;
let step: Step = Step.getUserName;
while (step !== undefined) {
switch (step) {
case Step.getUserName:
if (!username) {
const addUserLabel = '$(plus) Add new user...';
const choice = await this.getUserName(clusterURL, addUserLabel);
if (!choice) return choice; // Back or Cancel
if (choice === addUserLabel) {
step = Step.enterUserName;
} else {
username = choice;
step = Step.enterPassword;
}
}
break;
case Step.enterUserName:
if (!username) {
const prompt = 'Provide Username for basic authentication to the API server';
const validateInput = (value: string) => NameValidator.emptyName('User name cannot be empty', value);
const newUsername = await this.enterValue(prompt, '', false, validateInput);
if (newUsername === null) {
return null; // Cancel
} else if (!newUsername) {
username = undefined;
step = Step.getUserName; // Back
} else {
username = newUsername;
step = Step.enterPassword;
}
}
break;
case Step.enterPassword:
if (!passwd) {
password = await TokenStore.getItem('login', username);
const prompt = 'Provide Password for basic authentication to the API server';
const validateInput = (value: string) => NameValidator.emptyName('Password cannot be empty', value);
const newPassword = await this.enterValue(prompt, password, true, validateInput);
if (newPassword === null) {
return null; // Cancel
} else if (!newPassword) {
username = undefined;
step = Step.getUserName; // Back
} else {
passwd = newPassword;
step = undefined;
}
}
break;
default: // Shouldn't happen, but force cycle exit
step = undefined;
break;
}
}
if (!username || !passwd) return null;
// If there is saved password for the username - read it
password = await TokenStore.getItem('login', username);
try {
await Oc.Instance.loginWithUsernamePassword(clusterURL, username, passwd);
await Cluster.save(username, passwd, password);
return await Cluster.loginMessage(clusterURL);
} catch (error) {
if (error instanceof VsCommandError) {
throw new VsCommandError(
`Failed to login to cluster '${clusterURL}' with '${Filters.filterPassword(
error.message,
)}'!`,
`Failed to login to cluster. ${error.telemetryMessage}`,
);
} else {
throw new VsCommandError(
`Failed to login to cluster '${clusterURL}' with '${Filters.filterPassword(
error.message,
)}'!`,
'Failed to login to cluster',
);
}
}
}
static async readFromClipboard(): Promise<string> {
let r = '';
try {
r = await env.clipboard.readText();
} catch (ignore) {
// ignore exceptions and return empty string
}
return r;
}
static async getUrlFromClipboard(): Promise<string | null> {
const clipboard = await Cluster.readFromClipboard();
if (NameValidator.ocLoginCommandMatches(clipboard)) {
return NameValidator.clusterURL(clipboard);
}
return null;
}
@vsCommand('openshift.explorer.login.tokenLogin')
static async tokenLogin(
userClusterUrl: string,
skipConfirmation = false,
userToken?: string,
): Promise<string | null> {
let token: string;
const response = await Cluster.requestLoginConfirmation(skipConfirmation);
if (response !== 'Yes') return null;
let clusterURL = userClusterUrl;
let clusterUrlFromClipboard: string;
if (!clusterURL) {
clusterUrlFromClipboard = await Cluster.getUrlFromClipboard();
}
if (
(!clusterURL && clusterUrlFromClipboard) ||
clusterURL?.trim() === clusterUrlFromClipboard
) {
token = NameValidator.getToken(await Cluster.readFromClipboard());
clusterURL = clusterUrlFromClipboard;
}
if (!clusterURL) {
clusterURL = await Cluster.getUrl();
}
let ocToken: string;
if (!userToken) {
const prompt = 'Provide Bearer token for authentication to the API server';
const validateInput = (value: string) => NameValidator.emptyName('Bearer token cannot be empty', value);
const initialValue = token ? token : '';
ocToken = await this.enterValue(prompt, initialValue, true, validateInput);
if (ocToken === null) {
return null; // Cancel
} else if (!ocToken) {
return undefined; // Back
}
} else {
ocToken = userToken;
}
return Progress.execFunctionWithProgress(`Login to the cluster: ${clusterURL}`, () =>
Oc.Instance.loginWithToken(clusterURL, token)
.then(() => Cluster.loginMessage(clusterURL))
.catch((error) =>
Promise.reject(
new VsCommandError(
`Failed to login to cluster '${clusterURL}' with '${Filters.filterToken(
error.message,
)}'!`,
'Failed to login to cluster',
),
),
),
);
}
static validateLoginToken(token: string): boolean {
const sha256Regex = new RegExp('^sha256~([A-Za-z0-9_]+)');
return sha256Regex.test(token);
}
@vsCommand('openshift.explorer.login.clipboard')
static async loginUsingClipboardToken(
apiEndpointUrl: string,
oauthRequestTokenUrl: string,
): Promise<string | null> {
const clipboard = await Cluster.readFromClipboard();
if (!clipboard) {
const choice = await window.showErrorMessage(
'Cannot parse token in clipboard. Please click `Get token` button below, copy token into clipboard and press `Login to Sandbox` button again.',
'Get token',
);
if (choice === 'Get token') {
await commands.executeCommand('vscode.open', Uri.parse(oauthRequestTokenUrl));
}
return;
}
return Cluster.tokenLogin(apiEndpointUrl, true, clipboard);
}
static async loginUsingClipboardInfo(dashboardUrl: string): Promise<string | null> {
const clipboard = await Cluster.readFromClipboard();
if (!NameValidator.ocLoginCommandMatches(clipboard)) {
const choice = await window.showErrorMessage('Cannot parse login command in clipboard. Please open cluster dashboard and select `Copy login command` from user name dropdown in the upper right corner. Copy full login command to clipboard. Switch back to VSCode window and press `Login to Sandbox` button again.',
'Open Dashboard');
if (choice === 'Open Dashboard') {
await commands.executeCommand('vscode.open', Uri.parse(dashboardUrl));
}
return;
}
const url = NameValidator.clusterURL(clipboard);
const token = NameValidator.getToken(clipboard);
return Cluster.tokenLogin(url, true, token);
}
static async loginMessage(clusterURL: string): Promise<string> {
OpenShiftExplorer.getInstance().refresh();
Cluster.serverlessView.refresh();
await commands.executeCommand('setContext', 'isLoggedIn', true);
return `Successfully logged in to '${clusterURL}'`;
}
}