-
Notifications
You must be signed in to change notification settings - Fork 33
/
clusters.ts
507 lines (464 loc) · 19.6 KB
/
clusters.ts
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
/* eslint-disable @typescript-eslint/naming-convention */
import * as vscode from "vscode";
import { WebviewWizard, WizardDefinition, SEVERITY, UPDATE_TITLE, WizardPageFieldDefinition, WizardPageSectionDefinition, BUTTONS, PerformFinishResponse, IWizardPage, ValidatorResponseItem } from "@redhat-developer/vscode-wizard";
import { ClientAccessor, Cluster, SaslMechanism, SaslOption, SslOption } from "../client";
import { ClusterSettings } from "../settings";
import { validateAuthentificationUserName, validateBroker, validateClusterName, validateFile } from "./validators";
import { KafkaExplorer } from "../explorer";
import { ClusterProvider, defaultClusterProviderId, getClusterProviders } from "../kafka-extensions/registry";
import { showErrorMessage } from "./multiStepInput";
export function openClusterWizard(clusterSettings: ClusterSettings, clientAccessor: ClientAccessor, explorer: KafkaExplorer, context: vscode.ExtensionContext) {
const providers = getClusterProviders();
if (providers.length === 1) {
return openClusterForm(undefined, clusterSettings, clientAccessor, explorer, context);
}
const wiz: WebviewWizard = createClusterWizard(providers, clusterSettings, clientAccessor, explorer, context);
wiz.open();
}
export function openClusterForm(cluster: Cluster | undefined, clusterSettings: ClusterSettings, clientAccessor: ClientAccessor, explorer: KafkaExplorer, context: vscode.ExtensionContext) {
const wiz: WebviewWizard = createEditClusterForm(cluster, clusterSettings, clientAccessor, explorer, context);
wiz.open();
}
interface AuthMechanism {
key: string,
label: string;
}
const authMechanisms: Array<AuthMechanism> = [
{ key: "none", label: "None" },
{ key: "plain", label: "SASL/PLAIN" },
{ key: "scram-sha-256", label: "SASL/SCRAM-256" },
{ key: "scram-sha-512", label: "SASL/SCRAM-512" }
];
interface ValidationContext {
clusterSettings: ClusterSettings;
wizard: WebviewWizard | null;
}
// --- Wizard page fields
// Fields for Page 1:
const CLUSTER_PROVIDER_ID_FIELD = "clusterProviderId";
// Fields for Page 2:
const CLUSTER_NAME_FIELD = "name";
const CLUSTER_BOOTSTRAP_FIELD = "bootstrap";
const DEFAULT_BROKER = 'localhost:9092';
// SASL fields
const CLUSTER_SASL_MECHANISM_FIELD = "saslOptions.mechanism";
const CLUSTER_SASL_USERNAME_FIELD = "saslOptions.username";
const CLUSTER_SASL_PASSWORD_FIELD = "saslOptions.password";
// SSL fields
const CLUSTER_SSL_FIELD = "ssl";
const CLUSTER_SSL_CA_FIELD = "ssl.ca";
const CLUSTER_SSL_KEY_FIELD = "ssl.key";
const CLUSTER_SSL_CERT_FIELD = "ssl.cert";
// --- Wizard page ID
const CLUSTER_PROVIDER_PAGE = 'cluster-provider-page';
const CLUSTER_FORM_PAGE = 'cluster-form-page';
function createClusterWizard(providers: ClusterProvider[], clusterSettings: ClusterSettings, clientAccessor: ClientAccessor, explorer: KafkaExplorer, context: vscode.ExtensionContext): WebviewWizard {
const valiationContext = {
clusterSettings: clusterSettings,
wizard: null
} as ValidationContext;
const clusterWizardDef: WizardDefinition = {
title: "Add New Cluster(s)",
hideWizardHeader: true,
pages: [
{
id: CLUSTER_PROVIDER_PAGE,
hideWizardPageHeader: true,
fields: [
{
id: CLUSTER_PROVIDER_ID_FIELD,
label: "Cluster provider:",
initialValue: `${defaultClusterProviderId}`,
type: "select",
optionProvider: {
getItems() {
return [...providers];
},
getValueItem(provider: string | ClusterProvider) {
return (<ClusterProvider>provider).id;
},
getLabelItem(provider: string | ClusterProvider) {
return (<ClusterProvider>provider).name;
}
}
}
]
},
{
id: CLUSTER_FORM_PAGE,
hideWizardPageHeader: true,
fields: createFields(),
validator: createValidator(valiationContext),
}
],
workflowManager: {
getNextPage(page: IWizardPage, data: any): IWizardPage | null {
if (page.getId() === CLUSTER_PROVIDER_PAGE) {
const selectedClusterProvider = getSelectedClusterProvider(data, providers);
if (selectedClusterProvider?.id !== defaultClusterProviderId) {
return null;
}
return page.getNextPage();
}
return null;
},
canFinish(wizard: WebviewWizard, data: any) {
const page = wizard.getCurrentPage();
if (page?.getId() === CLUSTER_PROVIDER_PAGE) {
const selectedClusterProvider = getSelectedClusterProvider(data, providers);
return (selectedClusterProvider !== undefined && selectedClusterProvider.id !== defaultClusterProviderId);
}
return page?.isPageComplete() || false;
},
async performFinish(wizard: WebviewWizard, data: any) {
const page = wizard.getCurrentPage();
if (page?.getId() === CLUSTER_FORM_PAGE) {
const cluster = createCluster(data);
saveCluster(false, data, cluster, clusterSettings, clientAccessor, explorer);
// Open the cluster in form page
openClusterForm(cluster, clusterSettings, clientAccessor, explorer, context);
} else {
const provider = getSelectedClusterProvider(data, providers);
if (provider) {
// Collect clusters...
let clusters: Cluster[] | undefined;
try {
clusters = await provider.collectClusters(clusterSettings);
if (!clusters || clusters.length === 0) {
return null;
}
}
catch (error) {
showErrorMessage("Error while collecting cluster(s)", error);
return null;
}
// Save clusters.
saveClusters(false, clusters, clusterSettings, clientAccessor, explorer);
}
}
return null;
}
}
};
return new WebviewWizard(`new-cluster`, "cluster", context, clusterWizardDef,
new Map<string, string>());
}
function getSelectedClusterProvider(data: any, providers: ClusterProvider[]): ClusterProvider | undefined {
return providers.find(provider => provider.id === data[CLUSTER_PROVIDER_ID_FIELD]);
}
function createEditClusterForm(cluster: Cluster | undefined, clusterSettings: ClusterSettings, clientAccessor: ClientAccessor, explorer: KafkaExplorer, context: vscode.ExtensionContext): WebviewWizard {
const valiationContext = {
clusterSettings: clusterSettings,
wizard: null
} as ValidationContext;
const clusterWizardDef: WizardDefinition = {
title: `${cluster?.name || 'New Cluster'}`,
showDirtyState: true,
hideWizardHeader: true,
pages: [
{
id: `cluster-form-page'}`,
hideWizardPageHeader: true,
fields: createFields(cluster),
validator: createValidator(valiationContext)
}
],
buttons: [{
id: BUTTONS.FINISH,
label: "Save"
}],
workflowManager: {
async performFinish(wizard: WebviewWizard, data: any) {
if (!cluster) {
cluster = createCluster(data);
}
// Save cluster
saveCluster(true, data, cluster, clusterSettings, clientAccessor, explorer);
// Update tab title
let newTitle: string = cluster.name;
return new Promise<PerformFinishResponse | null>((res, rej) => {
res({
close: false,
success: true,
returnObject: null,
templates: [
{ id: UPDATE_TITLE, content: newTitle },
]
});
});
}
}
};
const wizard = new WebviewWizard(`${cluster?.id}`, "cluster", context, clusterWizardDef,
new Map<string, string>());
valiationContext.wizard = wizard;
return wizard;
}
function createFields(cluster?: Cluster): (WizardPageFieldDefinition | WizardPageSectionDefinition)[] {
const tlsConnectionOptions: SslOption | undefined = <SslOption>cluster?.ssl;
return [
{
id: CLUSTER_NAME_FIELD,
label: "Name:",
initialValue: `${cluster?.name || ''}`,
type: "textbox",
placeholder: 'Friendly name'
},
{
id: CLUSTER_BOOTSTRAP_FIELD,
label: "Bootstrap server:",
initialValue: `${cluster ? (cluster?.bootstrap || '') : DEFAULT_BROKER}`,
type: "textbox",
placeholder: 'Broker(s) (localhost:9092,localhost:9093...)'
},
{
id: 'sasl-section',
label: 'Authentication',
childFields: [
{
id: CLUSTER_SASL_MECHANISM_FIELD,
label: "Mechanism:",
initialValue: `${cluster?.saslOption?.mechanism || "none"}`,
type: "select",
optionProvider: {
getItems() {
return authMechanisms;
},
getValueItem(mechanism: AuthMechanism) {
return mechanism.key;
},
getLabelItem(mechanism: AuthMechanism) {
return mechanism.label;
}
}
},
{
id: CLUSTER_SASL_USERNAME_FIELD,
label: "Username:",
initialValue: `${cluster?.saslOption?.username || ''}`,
type: "textbox"
},
{
id: CLUSTER_SASL_PASSWORD_FIELD,
label: "Password:",
initialValue: `${cluster?.saslOption?.password || ''}`,
type: "password"
}
]
},
{
id: 'ssl-section',
label: 'SSL',
childFields: [
{
id: CLUSTER_SSL_FIELD,
label: "Enable SSL",
initialValue: !(cluster?.ssl === undefined || cluster?.ssl === false) ? 'true' : undefined,
type: "checkbox"
},
{
id: CLUSTER_SSL_CA_FIELD,
label: "Certificate Authority:",
initialValue: tlsConnectionOptions?.ca,
type: "file-picker",
placeholder: "Select file in PEM format.",
dialogOptions: {
canSelectMany: false,
filters: {
'All': ['*'],
'PEM': ['pem', 'crt', 'cer', 'key']
}
}
},
{
id: CLUSTER_SSL_KEY_FIELD,
label: "Client key:",
initialValue: tlsConnectionOptions?.key,
type: "file-picker",
placeholder: "Select file in PEM format.",
dialogOptions: {
canSelectMany: false,
filters: {
'All': ['*'],
'PEM': ['pem', 'crt', 'cer', 'key']
}
}
},
{
id: CLUSTER_SSL_CERT_FIELD,
label: "Client certificate:",
initialValue: tlsConnectionOptions?.cert,
type: "file-picker",
placeholder: "Select file in PEM format.",
dialogOptions: {
canSelectMany: false,
filters: {
'All': ['*'],
'PEM': ['pem', 'crt', 'cer', 'key']
}
}
}
]
}
];
}
function createValidator(validationContext: ValidationContext) {
return (parameters?: any) => {
const clusterName = validationContext.wizard?.title;
const diagnostics: Array<ValidatorResponseItem> = [];
// 1. Validate cluster name
const clusterSettings = validationContext.clusterSettings;
const existingClusterNames = clusterSettings.getAll()
.filter(c => clusterName === undefined || c.name !== clusterName)
.map(c => c.name);
const clustername = parameters[CLUSTER_NAME_FIELD];
let result = validateClusterName(clustername, existingClusterNames);
if (result) {
diagnostics.push(
{
template: {
id: CLUSTER_NAME_FIELD,
content: result
},
severity: SEVERITY.ERROR
}
);
}
// 2. Validate bootstrap broker
const bootstrap = parameters[CLUSTER_BOOTSTRAP_FIELD];
result = validateBroker(bootstrap);
if (result) {
diagnostics.push(
{
template: {
id: CLUSTER_BOOTSTRAP_FIELD,
content: result
},
severity: SEVERITY.ERROR
}
);
}
// 3. Validate username if SASL is enabled
if (parameters[CLUSTER_SASL_MECHANISM_FIELD] !== 'none') {
const username = parameters[CLUSTER_SASL_USERNAME_FIELD];
result = validateAuthentificationUserName(username);
if (result) {
diagnostics.push(
{
template: {
id: CLUSTER_SASL_USERNAME_FIELD,
content: result
},
severity: SEVERITY.ERROR
}
);
}
// check if SSL checkbox is checked
if (!(parameters[CLUSTER_SSL_FIELD] === true || parameters[CLUSTER_SSL_FIELD] === 'true')) {
diagnostics.push(
{
template: {
id: CLUSTER_SSL_FIELD,
content: 'SSL should be enabled since Authentication is enabled.'
},
severity: SEVERITY.ERROR
}
);
}
}
// 4. Validate certificate files
validateCertificateFile(parameters, CLUSTER_SSL_CA_FIELD, diagnostics);
validateCertificateFile(parameters, CLUSTER_SSL_KEY_FIELD, diagnostics);
validateCertificateFile(parameters, CLUSTER_SSL_CERT_FIELD, diagnostics);
return { items: diagnostics };
};
}
function saveCluster(update: boolean, data: any, cluster: Cluster, clusterSettings: ClusterSettings, clientAccessor: ClientAccessor, explorer: KafkaExplorer) {
cluster.name = data[CLUSTER_NAME_FIELD];
cluster.bootstrap = data[CLUSTER_BOOTSTRAP_FIELD];
cluster.saslOption = createSaslOption(data);
cluster.ssl = createSsl(data);
saveClusters(update, [cluster], clusterSettings, clientAccessor, explorer);
}
function saveClusters(update: boolean, clusters: Cluster[], clusterSettings: ClusterSettings, clientAccessor: ClientAccessor, explorer: KafkaExplorer) {
try {
// Save collected clusters in settings.
let createdClusterNames = '';
for (const cluster of clusters) {
clusterSettings.upsert(cluster);
clientAccessor.remove(cluster.id);
if (createdClusterNames !== '') {
createdClusterNames += '\', \'';
}
createdClusterNames += cluster.name;
}
vscode.window.showInformationMessage(`${clusters.length > 1 ? `${clusters.length} clusters` : 'Cluster'} '${createdClusterNames}' ${update ? 'updated' : 'created'} successfully`);
// Refresh the explorer
explorer.refresh();
// Selecting the created cluster is done with TreeView#reveal
// 1. Show the treeview of the explorer (otherwise reveal will not work)
explorer.show();
// 2. the reveal() call must occur within a timeout(),
// while waiting for a fix in https://github.com/microsoft/vscode/issues/114149
setTimeout(() => {
if (clusters) {
explorer.selectClusterByName(clusters[0].name);
}
}, 1000);
}
catch (error) {
showErrorMessage(`Error while ${update ? 'updating' : 'creating'} cluster`, error);
}
}
function createSaslOption(data: any): SaslOption | undefined {
const mechanism = data[CLUSTER_SASL_MECHANISM_FIELD] as SaslMechanism;
if (mechanism) {
const username = data[CLUSTER_SASL_USERNAME_FIELD];
const password = data[CLUSTER_SASL_PASSWORD_FIELD];
return {
mechanism,
username,
password
} as SaslOption;
}
}
function createSsl(data: any): SslOption | boolean {
const ca = data[CLUSTER_SSL_CA_FIELD];
const key = data[CLUSTER_SSL_KEY_FIELD];
const cert = data[CLUSTER_SSL_CERT_FIELD];
if (ca || key || cert) {
return {
ca,
key,
cert
} as SslOption;
}
return data[CLUSTER_SSL_FIELD] === true || data[CLUSTER_SSL_FIELD] === 'true';
}
function createCluster(data: any): Cluster {
const name = data[CLUSTER_NAME_FIELD];
const bootstrap = data[CLUSTER_BOOTSTRAP_FIELD];
const sanitizedName = name.replace(/[^a-zA-Z0-9]/g, "");
const suffix = Buffer.from(bootstrap).toString("base64").replace(/=/g, "");
return {
id: `${sanitizedName}-${suffix}`
} as Cluster;
}
function validateCertificateFile(parameters: any, fieldId: string, diagnostics: Array<ValidatorResponseItem>) {
const fileName = parameters[fieldId];
if (!fileName || fileName === '') {
return;
}
const result = validateFile(fileName);
if (result) {
diagnostics.push(
{
template: {
id: fieldId,
content: result
},
severity: SEVERITY.ERROR
}
);
}
}