Simplify add cluster view (#2716)

- Only shows editor, and will save all text to file

- Reports some validation errors, but doesn't block the add cluster
  button

- Cleanup kube helpers to facilitate clearer FS interactions

Signed-off-by: Sebastian Malton <sebastian@malton.name>
This commit is contained in:
Sebastian Malton authored and GitHub committed 2021-06-07 08:14:43 -04:00
1 parent 07c7653a70
commit 817c8e00db
18 files changed
+343 -395

No files matched your search

+116 -77
View File
@@ -28,6 +28,8 @@ import logger from "../main/logger";
import commandExists from "command-exists";
import { ExecValidationNotFoundError } from "./custom-errors";
import { Cluster, Context, newClusters, newContexts, newUsers, User } from "@kubernetes/client-node/dist/config_types";
import { resolvePath } from "./utils";
import Joi from "joi";
export type KubeConfigValidationOpts = {
validateCluster?: boolean;
@@ -37,50 +39,108 @@ export type KubeConfigValidationOpts = {
export const kubeConfigDefaultPath = path.join(os.homedir(), ".kube", "config");
function resolveTilde(filePath: string) {
if (filePath[0] === "~" && (filePath[1] === "/" || filePath.length === 1)) {
return filePath.replace("~", os.homedir());
}
export function loadConfigFromFileSync(filePath: string): ConfigResult {
const content = fse.readFileSync(resolvePath(filePath), "utf-8");
return filePath;
return loadConfigFromString(content);
}
function readResolvedPathSync(filePath: string): string {
return fse.readFileSync(path.resolve(resolveTilde(filePath)), "utf8");
export async function loadConfigFromFile(filePath: string): Promise<ConfigResult> {
const content = await fse.readFile(resolvePath(filePath), "utf-8");
return loadConfigFromString(content);
}
function checkRawCluster(rawCluster: any): boolean {
return Boolean(rawCluster?.name && rawCluster?.cluster?.server);
}
const clusterSchema = Joi.object({
name: Joi
.string()
.min(1)
.required(),
cluster: Joi
.object({
server: Joi
.string()
.min(1)
.required(),
})
.required(),
});
function checkRawUser(rawUser: any): boolean {
return Boolean(rawUser?.name);
}
const userSchema = Joi.object({
name: Joi.string()
.min(1)
.required(),
});
function checkRawContext(rawContext: any): boolean {
return Boolean(rawContext.name && rawContext.context?.cluster && rawContext.context?.user);
}
const contextSchema = Joi.object({
name: Joi.string()
.min(1)
.required(),
context: Joi.object({
cluster: Joi.string()
.min(1)
.required(),
user: Joi.string()
.min(1)
.required(),
}),
});
const kubeConfigSchema = Joi
.object({
users: Joi
.array()
.items(userSchema)
.optional(),
clusters: Joi
.array()
.items(clusterSchema)
.optional(),
contexts: Joi
.array()
.items(contextSchema)
.optional(),
"current-context": Joi
.string()
.min(1)
.optional(),
})
.required();
export interface KubeConfigOptions {
clusters: Cluster[];
users: User[];
contexts: Context[];
currentContext: string;
currentContext?: string;
}
function loadToOptions(rawYaml: string): KubeConfigOptions {
const obj = yaml.safeLoad(rawYaml);
export interface OptionsResult {
options: KubeConfigOptions;
error: Joi.ValidationError;
}
if (typeof obj !== "object" || !obj) {
throw new TypeError("KubeConfig root entry must be an object");
}
function loadToOptions(rawYaml: string): OptionsResult {
const parsed = yaml.safeLoad(rawYaml);
const { error } = kubeConfigSchema.validate(parsed, {
abortEarly: false,
allowUnknown: true,
});
const { value } = kubeConfigSchema.validate(parsed, {
abortEarly: false,
allowUnknown: true,
stripUnknown: {
arrays: true,
}
});
const { clusters: rawClusters, users: rawUsers, contexts: rawContexts, "current-context": currentContext } = value ?? {};
const clusters = newClusters(rawClusters);
const users = newUsers(rawUsers);
const contexts = newContexts(rawContexts);
const { clusters: rawClusters, users: rawUsers, contexts: rawContexts, "current-context": currentContext } = obj;
const clusters = newClusters(rawClusters?.filter(checkRawCluster));
const users = newUsers(rawUsers?.filter(checkRawUser));
const contexts = newContexts(rawContexts?.filter(checkRawContext));
return { clusters, users, contexts, currentContext };
return {
options: { clusters, users, contexts, currentContext },
error,
};
}
export function loadFromOptions(options: KubeConfigOptions): KubeConfig {
@@ -92,67 +152,44 @@ export function loadFromOptions(options: KubeConfigOptions): KubeConfig {
return kc;
}
export function loadConfig(pathOrContent?: string): KubeConfig {
return loadConfigFromString(
fse.pathExistsSync(pathOrContent)
? readResolvedPathSync(pathOrContent)
: pathOrContent
);
export interface ConfigResult {
config: KubeConfig;
error: Joi.ValidationError;
}
export function loadConfigFromString(content: string): KubeConfig {
return loadFromOptions(loadToOptions(content));
export function loadConfigFromString(content: string): ConfigResult {
const { options, error } = loadToOptions(content);
return {
config: loadFromOptions(options),
error,
};
}
/**
* KubeConfig is valid when there's at least one of each defined:
* - User
* - Cluster
* - Context
* @param config KubeConfig to check
*/
export function validateConfig(config: KubeConfig | string): KubeConfig {
if (typeof config == "string") {
config = loadConfig(config);
}
logger.debug(`validating kube config: ${JSON.stringify(config)}`);
if (!config.users || config.users.length == 0) {
throw new Error("No users provided in config");
}
if (!config.clusters || config.clusters.length == 0) {
throw new Error("No clusters provided in config");
}
if (!config.contexts || config.contexts.length == 0) {
throw new Error("No contexts provided in config");
}
return config;
export interface SplitConfigEntry {
config: KubeConfig,
error?: string;
}
/**
* Breaks kube config into several configs. Each context as it own KubeConfig object
*/
export function splitConfig(kubeConfig: KubeConfig): KubeConfig[] {
const configs: KubeConfig[] = [];
export function splitConfig(kubeConfig: KubeConfig): SplitConfigEntry[] {
const { contexts = [] } = kubeConfig;
if (!kubeConfig.contexts) {
return configs;
}
kubeConfig.contexts.forEach(ctx => {
const kc = new KubeConfig();
return contexts.map(context => {
const config = new KubeConfig();
kc.clusters = [kubeConfig.getCluster(ctx.cluster)].filter(n => n);
kc.users = [kubeConfig.getUser(ctx.user)].filter(n => n);
kc.contexts = [kubeConfig.getContextObject(ctx.name)].filter(n => n);
kc.setCurrentContext(ctx.name);
config.clusters = [kubeConfig.getCluster(context.cluster)].filter(Boolean);
config.users = [kubeConfig.getUser(context.user)].filter(Boolean);
config.contexts = [kubeConfig.getContextObject(context.name)].filter(Boolean);
config.setCurrentContext(context.name);
configs.push(kc);
return {
config,
error: validateKubeConfig(config, context.name)?.toString(),
};
});
return configs;
}
export function dumpConfigYaml(kubeConfig: Partial<KubeConfig>): string {
@@ -230,7 +267,7 @@ export function getNodeWarningConditions(node: V1Node) {
*
* Note: This function returns an error instead of throwing it, returning `undefined` if the validation passes
*/
export function validateKubeConfig(config: KubeConfig, contextName: string, validationOpts: KubeConfigValidationOpts = {}): Error | void {
export function validateKubeConfig(config: KubeConfig, contextName: string, validationOpts: KubeConfigValidationOpts = {}): Error | undefined {
try {
// we only receive a single context, cluster & user object here so lets validate them as this
// will be called when we add a new cluster to Lens
@@ -267,6 +304,8 @@ export function validateKubeConfig(config: KubeConfig, contextName: string, vali
return new ExecValidationNotFoundError(execCommand, isAbsolute);
}
}
return undefined;
} catch (error) {
return error;
}