-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathtasks.ts
494 lines (432 loc) · 19 KB
/
tasks.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
/**
* Copyright (C) 2024 Hedera Hashgraph, LLC
*
* Licensed under the Apache License, Version 2.0 (the ""License"");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an ""AS IS"" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import {Task} from '../../core/task.js';
import {Flags as flags} from '../flags.js';
import type {ListrTaskWrapper} from 'listr2';
import type {ConfigBuilder} from '../../types/aliases.js';
import {type BaseCommand} from '../base.js';
import {splitFlagInput} from '../../core/helpers.js';
import * as constants from '../../core/constants.js';
import path from 'path';
import chalk from 'chalk';
import {ListrLease} from '../../core/lease/listr_lease.js';
import {ErrorMessages} from '../../core/error_messages.js';
import {SoloError} from '../../core/errors.js';
import {type Context} from '@kubernetes/client-node';
import {RemoteConfigManager} from '../../core/config/remote/remote_config_manager.js';
import {type RemoteConfigDataWrapper} from '../../core/config/remote/remote_config_data_wrapper.js';
import {type K8} from '../../core/k8.js';
import {ListrEnquirerPromptAdapter} from '@listr2/prompt-adapter-enquirer';
import {type LocalConfig} from '../../core/config/local_config.js';
import {type Cluster} from '@kubernetes/client-node/dist/config_types.js';
export class ClusterCommandTasks {
private readonly parent: BaseCommand;
constructor(
parent,
private readonly k8: K8,
) {
this.parent = parent;
}
testConnectionToCluster(cluster: string, localConfig: LocalConfig, parentTask: ListrTaskWrapper<Context, any, any>) {
const self = this;
return {
title: `Test connection to cluster: ${chalk.cyan(cluster)}`,
task: async (_, subTask: ListrTaskWrapper<Context, any, any>) => {
let context = localConfig.clusterContextMapping[cluster];
if (!context) {
const isQuiet = self.parent.getConfigManager().getFlag(flags.quiet);
if (isQuiet) {
context = self.parent.getK8().getKubeConfig().currentContext;
} else {
context = await self.promptForContext(parentTask, cluster);
}
localConfig.clusterContextMapping[cluster] = context;
}
if (!(await self.parent.getK8().testClusterConnection(context, cluster))) {
subTask.title = `${subTask.title} - ${chalk.red('Cluster connection failed')}`;
throw new SoloError(`${ErrorMessages.INVALID_CONTEXT_FOR_CLUSTER_DETAILED(context, cluster)}`);
}
},
};
}
validateRemoteConfigForCluster(
cluster: string,
currentCluster: Cluster,
localConfig: LocalConfig,
currentRemoteConfig: RemoteConfigDataWrapper,
) {
const self = this;
return {
title: `Pull and validate remote configuration for cluster: ${chalk.cyan(cluster)}`,
task: async (_, subTask: ListrTaskWrapper<Context, any, any>) => {
const context = localConfig.clusterContextMapping[cluster];
self.parent.getK8().setCurrentContext(context);
const remoteConfigFromOtherCluster = await self.parent.getRemoteConfigManager().get();
if (!RemoteConfigManager.compare(currentRemoteConfig, remoteConfigFromOtherCluster)) {
throw new SoloError(ErrorMessages.REMOTE_CONFIGS_DO_NOT_MATCH(currentCluster.name, cluster));
}
},
};
}
readClustersFromRemoteConfig(argv) {
const self = this;
return {
title: 'Read clusters from remote config',
task: async (ctx, task) => {
const localConfig = this.parent.getLocalConfig();
const currentCluster = this.parent.getK8().getKubeConfig().getCurrentCluster();
const currentRemoteConfig: RemoteConfigDataWrapper = await this.parent.getRemoteConfigManager().get();
const subTasks = [];
const remoteConfigClusters = Object.keys(currentRemoteConfig.clusters);
const otherRemoteConfigClusters: string[] = remoteConfigClusters.filter(c => c !== currentCluster.name);
// Validate connections for the other clusters
for (const cluster of otherRemoteConfigClusters) {
subTasks.push(self.testConnectionToCluster(cluster, localConfig, task));
}
// Pull and validate RemoteConfigs from the other clusters
for (const cluster of otherRemoteConfigClusters) {
subTasks.push(self.validateRemoteConfigForCluster(cluster, currentCluster, localConfig, currentRemoteConfig));
}
return task.newListr(subTasks, {
concurrent: false,
rendererOptions: {collapseSubtasks: false},
});
},
};
}
updateLocalConfig(argv) {
return new Task('Update local configuration', async (ctx: any, task: ListrTaskWrapper<any, any, any>) => {
this.parent.logger.info('Compare local and remote configuration...');
const configManager = this.parent.getConfigManager();
const isQuiet = configManager.getFlag(flags.quiet);
await this.parent.getRemoteConfigManager().modify(async remoteConfig => {
// Update current deployment with cluster list from remoteConfig
const localConfig = this.parent.getLocalConfig();
const localDeployments = localConfig.deployments;
const remoteClusterList = [];
const namespace = remoteConfig.metadata.name;
localConfig.currentDeploymentName = remoteConfig.metadata.name;
if (localConfig.deployments[namespace]) {
for (const cluster of Object.keys(remoteConfig.clusters)) {
if (localConfig.currentDeploymentName === remoteConfig.clusters[cluster]) {
remoteClusterList.push(cluster);
}
}
ctx.config.clusters = remoteClusterList;
localDeployments[localConfig.currentDeploymentName].clusters = ctx.config.clusters;
} else {
const clusters = Object.keys(remoteConfig.clusters);
localDeployments[namespace] = {clusters};
ctx.config.clusters = clusters;
}
localConfig.setDeployments(localDeployments);
const contexts = splitFlagInput(configManager.getFlag(flags.context));
for (let i = 0; i < ctx.config.clusters.length; i++) {
const cluster = ctx.config.clusters[i];
const context = contexts[i];
// If a context is provided use it to update the mapping
if (context) {
localConfig.clusterContextMapping[cluster] = context;
} else if (!localConfig.clusterContextMapping[cluster]) {
// In quiet mode use the currently selected context to update the mapping
if (isQuiet) {
localConfig.clusterContextMapping[cluster] = this.parent.getK8().getKubeConfig().getCurrentContext();
}
// Prompt the user to select a context if mapping value is missing
else {
localConfig.clusterContextMapping[cluster] = await this.promptForContext(task, cluster);
}
}
}
this.parent.logger.info('Update local configuration...');
await localConfig.write();
});
});
}
private async getSelectedContext(task, selectedCluster, localConfig, isQuiet) {
let selectedContext;
if (isQuiet) {
selectedContext = this.parent.getK8().getKubeConfig().getCurrentContext();
} else {
selectedContext = await this.promptForContext(task, selectedCluster);
localConfig.clusterContextMapping[selectedCluster] = selectedContext;
}
return selectedContext;
}
private async promptForContext(task, cluster) {
const kubeContexts = this.parent.getK8().getContexts();
return flags.context.prompt(
task,
kubeContexts.map(c => c.name),
cluster,
);
}
private async selectContextForFirstCluster(task, clusters, localConfig, isQuiet) {
const selectedCluster = clusters[0];
if (localConfig.clusterContextMapping[selectedCluster]) {
return localConfig.clusterContextMapping[selectedCluster];
}
// If cluster does not exist in LocalConfig mapping prompt the user to select a context or use the current one
else {
return this.getSelectedContext(task, selectedCluster, localConfig, isQuiet);
}
}
/**
* Prepare values arg for cluster setup command
*
* @param [chartDir] - local charts directory (default is empty)
* @param [prometheusStackEnabled] - a bool to denote whether to install prometheus stack
* @param [minioEnabled] - a bool to denote whether to install minio
* @param [certManagerEnabled] - a bool to denote whether to install cert manager
* @param [certManagerCrdsEnabled] - a bool to denote whether to install cert manager CRDs
*/
private prepareValuesArg(
chartDir = flags.chartDirectory.definition.defaultValue as string,
prometheusStackEnabled = flags.deployPrometheusStack.definition.defaultValue as boolean,
minioEnabled = flags.deployMinio.definition.defaultValue as boolean,
certManagerEnabled = flags.deployCertManager.definition.defaultValue as boolean,
certManagerCrdsEnabled = flags.deployCertManagerCrds.definition.defaultValue as boolean,
) {
let valuesArg = chartDir ? `-f ${path.join(chartDir, 'solo-cluster-setup', 'values.yaml')}` : '';
valuesArg += ` --set cloud.prometheusStack.enabled=${prometheusStackEnabled}`;
valuesArg += ` --set cloud.certManager.enabled=${certManagerEnabled}`;
valuesArg += ` --set cert-manager.installCRDs=${certManagerCrdsEnabled}`;
valuesArg += ` --set cloud.minio.enabled=${minioEnabled}`;
if (certManagerEnabled && !certManagerCrdsEnabled) {
this.parent.logger.showUser(
chalk.yellowBright('> WARNING:'),
chalk.yellow(
'cert-manager CRDs are required for cert-manager, please enable it if you have not installed it independently.',
),
);
}
return valuesArg;
}
/** Show list of installed chart */
private async showInstalledChartList(clusterSetupNamespace: string) {
this.parent.logger.showList(
'Installed Charts',
await this.parent.getChartManager().getInstalledCharts(clusterSetupNamespace),
);
}
selectContext(argv) {
return new Task('Read local configuration settings', async (ctx: any, task: ListrTaskWrapper<any, any, any>) => {
this.parent.logger.info('Read local configuration settings...');
const configManager = this.parent.getConfigManager();
const isQuiet = configManager.getFlag(flags.quiet);
const deploymentName: string = configManager.getFlag(flags.namespace);
let clusters = splitFlagInput(configManager.getFlag(flags.clusterName));
const contexts = splitFlagInput(configManager.getFlag(flags.context));
const localConfig = this.parent.getLocalConfig();
let selectedContext;
let selectedCluster;
// If one or more contexts are provided use the first one
if (contexts.length) {
selectedContext = contexts[0];
}
// If one or more clusters are provided use the first one to determine the context
// from the mapping in the LocalConfig
else if (clusters.length) {
selectedCluster = clusters[0];
selectedContext = await this.selectContextForFirstCluster(task, clusters, localConfig, isQuiet);
}
// If a deployment name is provided get the clusters associated with the deployment from the LocalConfig
// and select the context from the mapping, corresponding to the first deployment cluster
else if (deploymentName) {
const deployment = localConfig.deployments[deploymentName];
if (deployment && deployment.clusters.length) {
selectedCluster = deployment.clusters[0];
selectedContext = await this.selectContextForFirstCluster(task, deployment.clusters, localConfig, isQuiet);
}
// The provided deployment does not exist in the LocalConfig
else {
// Add the deployment to the LocalConfig with the currently selected cluster and context in KubeConfig
if (isQuiet) {
selectedContext = this.parent.getK8().getKubeConfig().getCurrentContext();
selectedCluster = this.parent.getK8().getKubeConfig().getCurrentCluster().name;
localConfig.deployments[deploymentName] = {
clusters: [selectedCluster],
};
if (!localConfig.clusterContextMapping[selectedCluster]) {
localConfig.clusterContextMapping[selectedCluster] = selectedContext;
}
}
// Prompt user for clusters and contexts
else {
const promptedClusters = await flags.clusterName.prompt(task, '');
clusters = splitFlagInput(promptedClusters);
for (const cluster of clusters) {
if (!localConfig.clusterContextMapping[cluster]) {
localConfig.clusterContextMapping[cluster] = await this.promptForContext(task, cluster);
}
}
selectedCluster = clusters[0];
selectedContext = localConfig.clusterContextMapping[clusters[0]];
}
}
}
const connectionValid = await this.parent.getK8().testClusterConnection(selectedContext, selectedCluster);
if (!connectionValid) {
throw new SoloError(ErrorMessages.INVALID_CONTEXT_FOR_CLUSTER(selectedContext));
}
this.parent.getK8().setCurrentContext(selectedContext);
});
}
initialize(argv: any, configInit: ConfigBuilder) {
const {requiredFlags, optionalFlags} = argv;
argv.flags = [...requiredFlags, ...optionalFlags];
return new Task('Initialize', async (ctx: any, task: ListrTaskWrapper<any, any, any>) => {
if (argv[flags.devMode.name]) {
this.parent.logger.setDevMode(true);
}
ctx.config = await configInit(argv, ctx, task);
});
}
showClusterList() {
return new Task('List all available clusters', async (ctx: any, task: ListrTaskWrapper<any, any, any>) => {
this.parent.logger.showList('Clusters', this.parent.getK8().getClusters());
});
}
getClusterInfo() {
return new Task('Get cluster info', async (ctx: any, task: ListrTaskWrapper<any, any, any>) => {
try {
const cluster = this.parent.getK8().getKubeConfig().getCurrentCluster();
this.parent.logger.showJSON(`Cluster Information (${cluster.name})`, cluster);
this.parent.logger.showUser('\n');
} catch (e: Error | unknown) {
this.parent.logger.showUserError(e);
}
});
}
prepareChartValues(argv) {
const self = this;
return new Task(
'Prepare chart values',
async (ctx: any, task: ListrTaskWrapper<any, any, any>) => {
ctx.chartPath = await this.parent.prepareChartPath(
ctx.config.chartDir,
constants.SOLO_TESTING_CHART_URL,
constants.SOLO_CLUSTER_SETUP_CHART,
);
// if minio is already present, don't deploy it
if (ctx.config.deployMinio && (await self.k8.isMinioInstalled(ctx.config.clusterSetupNamespace))) {
ctx.config.deployMinio = false;
}
// if prometheus is found, don't deploy it
if (
ctx.config.deployPrometheusStack &&
!(await self.k8.isPrometheusInstalled(ctx.config.clusterSetupNamespace))
) {
ctx.config.deployPrometheusStack = false;
}
// if cert manager is installed, don't deploy it
if (
(ctx.config.deployCertManager || ctx.config.deployCertManagerCrds) &&
(await self.k8.isCertManagerInstalled())
) {
ctx.config.deployCertManager = false;
ctx.config.deployCertManagerCrds = false;
}
// If all are already present or not wanted, skip installation
if (
!ctx.config.deployPrometheusStack &&
!ctx.config.deployMinio &&
!ctx.config.deployCertManager &&
!ctx.config.deployCertManagerCrds
) {
ctx.isChartInstalled = true;
return;
}
ctx.valuesArg = this.prepareValuesArg(
ctx.config.chartDir,
ctx.config.deployPrometheusStack,
ctx.config.deployMinio,
ctx.config.deployCertManager,
ctx.config.deployCertManagerCrds,
);
},
ctx => ctx.isChartInstalled,
);
}
installClusterChart(argv) {
const parent = this.parent;
return new Task(
`Install '${constants.SOLO_CLUSTER_SETUP_CHART}' chart`,
async (ctx: any, task: ListrTaskWrapper<any, any, any>) => {
const clusterSetupNamespace = ctx.config.clusterSetupNamespace;
const version = ctx.config.soloChartVersion;
const valuesArg = ctx.valuesArg;
try {
parent.logger.debug(`Installing chart chartPath = ${ctx.chartPath}, version = ${version}`);
await parent
.getChartManager()
.install(clusterSetupNamespace, constants.SOLO_CLUSTER_SETUP_CHART, ctx.chartPath, version, valuesArg);
} catch (e: Error | unknown) {
// if error, uninstall the chart and rethrow the error
parent.logger.debug(
`Error on installing ${constants.SOLO_CLUSTER_SETUP_CHART}. attempting to rollback by uninstalling the chart`,
e,
);
try {
await parent.getChartManager().uninstall(clusterSetupNamespace, constants.SOLO_CLUSTER_SETUP_CHART);
} catch {
// ignore error during uninstall since we are doing the best-effort uninstall here
}
throw e;
}
if (argv.dev) {
await this.showInstalledChartList(clusterSetupNamespace);
}
},
ctx => ctx.isChartInstalled,
);
}
acquireNewLease(argv) {
return new Task('Acquire new lease', async (ctx: any, task: ListrTaskWrapper<any, any, any>) => {
const lease = await this.parent.getLeaseManager().create();
return ListrLease.newAcquireLeaseTask(lease, task);
});
}
uninstallClusterChart(argv) {
const parent = this.parent;
const self = this;
return new Task(
`Uninstall '${constants.SOLO_CLUSTER_SETUP_CHART}' chart`,
async (ctx: any, task: ListrTaskWrapper<any, any, any>) => {
const clusterSetupNamespace = ctx.config.clusterSetupNamespace;
if (!argv.force && (await self.k8.isRemoteConfigPresentInAnyNamespace())) {
const confirm = await task.prompt(ListrEnquirerPromptAdapter).run({
type: 'toggle',
default: false,
message:
'There is remote config for one of the deployments' +
'Are you sure you would like to uninstall the cluster?',
});
if (!confirm) {
// eslint-disable-next-line n/no-process-exit
process.exit(0);
}
}
await parent.getChartManager().uninstall(clusterSetupNamespace, constants.SOLO_CLUSTER_SETUP_CHART);
if (argv.dev) {
await this.showInstalledChartList(clusterSetupNamespace);
}
},
ctx => !ctx.isChartInstalled,
);
}
}