mirror of
https://github.com/lensapp/lens.git
synced 2025-05-20 05:10:56 +00:00
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:
1 parent
07c7653a70
commit
817c8e00db
18 files changed
+343
-395
No files matched your search
@@ -22,8 +22,10 @@
|
||||
import fs from "fs";
|
||||
import mockFs from "mock-fs";
|
||||
import yaml from "js-yaml";
|
||||
import path from "path";
|
||||
import fse from "fs-extra";
|
||||
import { Cluster } from "../../main/cluster";
|
||||
import { ClusterStore, getClusterIdFromHost } from "../cluster-store";
|
||||
import { ClusterId, ClusterStore, getClusterIdFromHost } from "../cluster-store";
|
||||
import { Console } from "console";
|
||||
import { stdout, stderr } from "process";
|
||||
|
||||
@@ -54,6 +56,15 @@ users:
|
||||
token: kubeconfig-user-q4lm4:xxxyyyy
|
||||
`;
|
||||
|
||||
function embed(clusterId: ClusterId, contents: any): string {
|
||||
const absPath = ClusterStore.getCustomKubeConfigPath(clusterId);
|
||||
|
||||
fse.ensureDirSync(path.dirname(absPath));
|
||||
fse.writeFileSync(absPath, contents, { encoding: "utf-8", mode: 0o600 });
|
||||
|
||||
return absPath;
|
||||
}
|
||||
|
||||
jest.mock("electron", () => {
|
||||
return {
|
||||
app: {
|
||||
@@ -102,7 +113,7 @@ describe("empty config", () => {
|
||||
icon: "data:image/jpeg;base64, iVBORw0KGgoAAAANSUhEUgAAA1wAAAKoCAYAAABjkf5",
|
||||
clusterName: "minikube"
|
||||
},
|
||||
kubeConfigPath: ClusterStore.embedCustomKubeConfig("foo", kubeconfig)
|
||||
kubeConfigPath: embed("foo", kubeconfig)
|
||||
})
|
||||
);
|
||||
});
|
||||
@@ -130,7 +141,7 @@ describe("empty config", () => {
|
||||
preferences: {
|
||||
clusterName: "prod"
|
||||
},
|
||||
kubeConfigPath: ClusterStore.embedCustomKubeConfig("prod", kubeconfig)
|
||||
kubeConfigPath: embed("prod", kubeconfig)
|
||||
}),
|
||||
new Cluster({
|
||||
id: "dev",
|
||||
@@ -138,7 +149,7 @@ describe("empty config", () => {
|
||||
preferences: {
|
||||
clusterName: "dev"
|
||||
},
|
||||
kubeConfigPath: ClusterStore.embedCustomKubeConfig("dev", kubeconfig)
|
||||
kubeConfigPath: embed("dev", kubeconfig)
|
||||
})
|
||||
);
|
||||
});
|
||||
@@ -149,7 +160,7 @@ describe("empty config", () => {
|
||||
});
|
||||
|
||||
it("check if cluster's kubeconfig file saved", () => {
|
||||
const file = ClusterStore.embedCustomKubeConfig("boo", "kubeconfig");
|
||||
const file = embed("boo", "kubeconfig");
|
||||
|
||||
expect(fs.readFileSync(file, "utf8")).toBe("kubeconfig");
|
||||
});
|
||||
@@ -160,6 +171,7 @@ describe("config with existing clusters", () => {
|
||||
beforeEach(() => {
|
||||
ClusterStore.resetInstance();
|
||||
const mockOpts = {
|
||||
"temp-kube-config": kubeconfig,
|
||||
"tmp": {
|
||||
"lens-cluster-store.json": JSON.stringify({
|
||||
__internal__: {
|
||||
@@ -170,20 +182,20 @@ describe("config with existing clusters", () => {
|
||||
clusters: [
|
||||
{
|
||||
id: "cluster1",
|
||||
kubeConfigPath: kubeconfig,
|
||||
kubeConfigPath: "./temp-kube-config",
|
||||
contextName: "foo",
|
||||
preferences: { terminalCWD: "/foo" },
|
||||
workspace: "default"
|
||||
},
|
||||
{
|
||||
id: "cluster2",
|
||||
kubeConfigPath: kubeconfig,
|
||||
kubeConfigPath: "./temp-kube-config",
|
||||
contextName: "foo2",
|
||||
preferences: { terminalCWD: "/foo2" }
|
||||
},
|
||||
{
|
||||
id: "cluster3",
|
||||
kubeConfigPath: kubeconfig,
|
||||
kubeConfigPath: "./temp-kube-config",
|
||||
contextName: "foo",
|
||||
preferences: { terminalCWD: "/foo" },
|
||||
workspace: "foo",
|
||||
@@ -256,6 +268,8 @@ users:
|
||||
|
||||
ClusterStore.resetInstance();
|
||||
const mockOpts = {
|
||||
"invalid-kube-config": invalidKubeconfig,
|
||||
"valid-kube-config": kubeconfig,
|
||||
"tmp": {
|
||||
"lens-cluster-store.json": JSON.stringify({
|
||||
__internal__: {
|
||||
@@ -266,14 +280,14 @@ users:
|
||||
clusters: [
|
||||
{
|
||||
id: "cluster1",
|
||||
kubeConfigPath: invalidKubeconfig,
|
||||
kubeConfigPath: "./invalid-kube-config",
|
||||
contextName: "test",
|
||||
preferences: { terminalCWD: "/foo" },
|
||||
workspace: "foo",
|
||||
},
|
||||
{
|
||||
id: "cluster2",
|
||||
kubeConfigPath: kubeconfig,
|
||||
kubeConfigPath: "./valid-kube-config",
|
||||
contextName: "foo",
|
||||
preferences: { terminalCWD: "/foo" },
|
||||
workspace: "default"
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
*/
|
||||
|
||||
import { KubeConfig } from "@kubernetes/client-node";
|
||||
import { validateKubeConfig, loadConfig, getNodeWarningConditions } from "../kube-helpers";
|
||||
import { validateKubeConfig, loadConfigFromString, getNodeWarningConditions } from "../kube-helpers";
|
||||
|
||||
const kubeconfig = `
|
||||
apiVersion: v1
|
||||
@@ -59,8 +59,6 @@ users:
|
||||
command: foo
|
||||
`;
|
||||
|
||||
const kc = new KubeConfig();
|
||||
|
||||
interface kubeconfig {
|
||||
apiVersion: string,
|
||||
clusters: [{
|
||||
@@ -88,6 +86,8 @@ let mockKubeConfig: kubeconfig;
|
||||
|
||||
describe("kube helpers", () => {
|
||||
describe("validateKubeconfig", () => {
|
||||
const kc = new KubeConfig();
|
||||
|
||||
beforeAll(() => {
|
||||
kc.loadFromString(kubeconfig);
|
||||
});
|
||||
@@ -164,12 +164,12 @@ describe("kube helpers", () => {
|
||||
it("invalid yaml string", () => {
|
||||
const invalidYAMLString = "fancy foo config";
|
||||
|
||||
expect(() => loadConfig(invalidYAMLString)).toThrowError("must be an object");
|
||||
expect(loadConfigFromString(invalidYAMLString).error).toBeInstanceOf(Error);
|
||||
});
|
||||
it("empty contexts", () => {
|
||||
const emptyContexts = `apiVersion: v1\ncontexts:`;
|
||||
const emptyContexts = `apiVersion: v1\ncontexts: []`;
|
||||
|
||||
expect(() => loadConfig(emptyContexts)).not.toThrow();
|
||||
expect(loadConfigFromString(emptyContexts).error).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -200,17 +200,17 @@ describe("kube helpers", () => {
|
||||
});
|
||||
|
||||
it("single context is ok", async () => {
|
||||
const kc:KubeConfig = loadConfig(JSON.stringify(mockKubeConfig));
|
||||
const { config } = loadConfigFromString(JSON.stringify(mockKubeConfig));
|
||||
|
||||
expect(kc.getCurrentContext()).toBe("minikube");
|
||||
expect(config.getCurrentContext()).toBe("minikube");
|
||||
});
|
||||
|
||||
it("multiple context is ok", async () => {
|
||||
mockKubeConfig.contexts.push({context: {cluster: "cluster-2", user: "cluster-2"}, name: "cluster-2"});
|
||||
const kc:KubeConfig = loadConfig(JSON.stringify(mockKubeConfig));
|
||||
const { config } = loadConfigFromString(JSON.stringify(mockKubeConfig));
|
||||
|
||||
expect(kc.getCurrentContext()).toBe("minikube");
|
||||
expect(kc.contexts.length).toBe(2);
|
||||
expect(config.getCurrentContext()).toBe("minikube");
|
||||
expect(config.contexts.length).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -243,40 +243,40 @@ describe("kube helpers", () => {
|
||||
it("empty name in context causes it to be removed", async () => {
|
||||
mockKubeConfig.contexts.push({context: {cluster: "cluster-2", user: "cluster-2"}, name: ""});
|
||||
expect(mockKubeConfig.contexts.length).toBe(2);
|
||||
const kc:KubeConfig = loadConfig(JSON.stringify(mockKubeConfig));
|
||||
const { config } = loadConfigFromString(JSON.stringify(mockKubeConfig));
|
||||
|
||||
expect(kc.getCurrentContext()).toBe("minikube");
|
||||
expect(kc.contexts.length).toBe(1);
|
||||
expect(config.getCurrentContext()).toBe("minikube");
|
||||
expect(config.contexts.length).toBe(1);
|
||||
});
|
||||
|
||||
it("empty cluster in context causes it to be removed", async () => {
|
||||
mockKubeConfig.contexts.push({context: {cluster: "", user: "cluster-2"}, name: "cluster-2"});
|
||||
expect(mockKubeConfig.contexts.length).toBe(2);
|
||||
const kc:KubeConfig = loadConfig(JSON.stringify(mockKubeConfig));
|
||||
const { config } = loadConfigFromString(JSON.stringify(mockKubeConfig));
|
||||
|
||||
expect(kc.getCurrentContext()).toBe("minikube");
|
||||
expect(kc.contexts.length).toBe(1);
|
||||
expect(config.getCurrentContext()).toBe("minikube");
|
||||
expect(config.contexts.length).toBe(1);
|
||||
});
|
||||
|
||||
it("empty user in context causes it to be removed", async () => {
|
||||
mockKubeConfig.contexts.push({context: {cluster: "cluster-2", user: ""}, name: "cluster-2"});
|
||||
expect(mockKubeConfig.contexts.length).toBe(2);
|
||||
const kc:KubeConfig = loadConfig(JSON.stringify(mockKubeConfig));
|
||||
const { config } = loadConfigFromString(JSON.stringify(mockKubeConfig));
|
||||
|
||||
expect(kc.getCurrentContext()).toBe("minikube");
|
||||
expect(kc.contexts.length).toBe(1);
|
||||
expect(config.getCurrentContext()).toBe("minikube");
|
||||
expect(config.contexts.length).toBe(1);
|
||||
});
|
||||
|
||||
it("invalid context in between valid contexts is removed", async () => {
|
||||
mockKubeConfig.contexts.push({context: {cluster: "cluster-2", user: ""}, name: "cluster-2"});
|
||||
mockKubeConfig.contexts.push({context: {cluster: "cluster-3", user: "cluster-3"}, name: "cluster-3"});
|
||||
expect(mockKubeConfig.contexts.length).toBe(3);
|
||||
const kc:KubeConfig = loadConfig(JSON.stringify(mockKubeConfig));
|
||||
const { config } = loadConfigFromString(JSON.stringify(mockKubeConfig));
|
||||
|
||||
expect(kc.getCurrentContext()).toBe("minikube");
|
||||
expect(kc.contexts.length).toBe(2);
|
||||
expect(kc.contexts[0].name).toBe("minikube");
|
||||
expect(kc.contexts[1].name).toBe("cluster-3");
|
||||
expect(config.getCurrentContext()).toBe("minikube");
|
||||
expect(config.contexts.length).toBe(2);
|
||||
expect(config.contexts[0].name).toBe("minikube");
|
||||
expect(config.contexts[1].name).toBe("cluster-3");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -66,19 +66,6 @@ describe("user store tests", () => {
|
||||
expect(us.lastSeenAppVersion).toBe("1.2.3");
|
||||
});
|
||||
|
||||
it("allows adding and listing seen contexts", () => {
|
||||
const us = UserStore.getInstance();
|
||||
|
||||
us.seenContexts.add("foo");
|
||||
expect(us.seenContexts.size).toBe(1);
|
||||
|
||||
us.seenContexts.add("foo");
|
||||
us.seenContexts.add("bar");
|
||||
expect(us.seenContexts.size).toBe(2); // check 'foo' isn't added twice
|
||||
expect(us.seenContexts.has("foo")).toBe(true);
|
||||
expect(us.seenContexts.has("bar")).toBe(true);
|
||||
});
|
||||
|
||||
it("allows setting and getting preferences", () => {
|
||||
const us = UserStore.getInstance();
|
||||
|
||||
|
||||
@@ -26,11 +26,9 @@ import { action, comparer, computed, makeObservable, observable, reaction } from
|
||||
import { BaseStore } from "./base-store";
|
||||
import { Cluster, ClusterState } from "../main/cluster";
|
||||
import migrations from "../migrations/cluster-store";
|
||||
import * as uuid from "uuid";
|
||||
import logger from "../main/logger";
|
||||
import { appEventBus } from "./event-bus";
|
||||
import { dumpConfigYaml } from "./kube-helpers";
|
||||
import { saveToAppFiles } from "./utils/saveToAppFiles";
|
||||
import type { KubeConfig } from "@kubernetes/client-node";
|
||||
import { handleRequest, requestMain, subscribeToBroadcast, unsubscribeAllFromBroadcast } from "./ipc";
|
||||
import { disposer, noop, toJS } from "./utils";
|
||||
|
||||
@@ -116,19 +114,10 @@ export class ClusterStore extends BaseStore<ClusterStoreModel> {
|
||||
return path.resolve((app || remote.app).getPath("userData"), "kubeconfigs");
|
||||
}
|
||||
|
||||
static getCustomKubeConfigPath(clusterId: ClusterId): string {
|
||||
static getCustomKubeConfigPath(clusterId: ClusterId = uuid.v4()): string {
|
||||
return path.resolve(ClusterStore.storedKubeConfigFolder, clusterId);
|
||||
}
|
||||
|
||||
static embedCustomKubeConfig(clusterId: ClusterId, kubeConfig: KubeConfig | string): string {
|
||||
const filePath = ClusterStore.getCustomKubeConfigPath(clusterId);
|
||||
const fileContents = typeof kubeConfig == "string" ? kubeConfig : dumpConfigYaml(kubeConfig);
|
||||
|
||||
saveToAppFiles(filePath, fileContents, { mode: 0o600 });
|
||||
|
||||
return filePath;
|
||||
}
|
||||
|
||||
@observable clusters = observable.map<ClusterId, Cluster>();
|
||||
@observable removedClusters = observable.map<ClusterId, Cluster>();
|
||||
|
||||
|
||||
+116
-77
@@ -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;
|
||||
}
|
||||
|
||||
@@ -22,24 +22,19 @@
|
||||
import type { ThemeId } from "../renderer/theme.store";
|
||||
import { app, remote } from "electron";
|
||||
import semver from "semver";
|
||||
import { readFile } from "fs-extra";
|
||||
import { action, computed, observable, reaction, makeObservable } from "mobx";
|
||||
import moment from "moment-timezone";
|
||||
import { BaseStore } from "./base-store";
|
||||
import migrations from "../migrations/user-store";
|
||||
import { getAppVersion } from "./utils/app-version";
|
||||
import { kubeConfigDefaultPath, loadConfig } from "./kube-helpers";
|
||||
import { appEventBus } from "./event-bus";
|
||||
import logger from "../main/logger";
|
||||
import path from "path";
|
||||
import os from "os";
|
||||
import { fileNameMigration } from "../migrations/user-store";
|
||||
import { ObservableToggleSet, toJS } from "../renderer/utils";
|
||||
|
||||
export interface UserStoreModel {
|
||||
kubeConfigPath: string;
|
||||
lastSeenAppVersion: string;
|
||||
seenContexts: string[];
|
||||
preferences: UserPreferencesModel;
|
||||
}
|
||||
|
||||
@@ -47,7 +42,7 @@ export interface KubeconfigSyncEntry extends KubeconfigSyncValue {
|
||||
filePath: string;
|
||||
}
|
||||
|
||||
export interface KubeconfigSyncValue {}
|
||||
export interface KubeconfigSyncValue { }
|
||||
|
||||
export interface UserPreferencesModel {
|
||||
httpsProxy?: string;
|
||||
@@ -77,13 +72,6 @@ export class UserStore extends BaseStore<UserStoreModel> {
|
||||
}
|
||||
|
||||
@observable lastSeenAppVersion = "0.0.0";
|
||||
|
||||
/**
|
||||
* used in add-cluster page for providing context
|
||||
*/
|
||||
@observable kubeConfigPath = kubeConfigDefaultPath;
|
||||
@observable seenContexts = observable.set<string>();
|
||||
@observable newContexts = observable.set<string>();
|
||||
@observable allowTelemetry = true;
|
||||
@observable allowUntrustedCAs = false;
|
||||
@observable colorTheme = UserStore.defaultTheme;
|
||||
@@ -121,10 +109,6 @@ export class UserStore extends BaseStore<UserStoreModel> {
|
||||
await fileNameMigration();
|
||||
await super.load();
|
||||
|
||||
// refresh new contexts
|
||||
await this.refreshNewContexts();
|
||||
reaction(() => this.kubeConfigPath, () => this.refreshNewContexts());
|
||||
|
||||
if (app) {
|
||||
// track telemetry availability
|
||||
reaction(() => this.allowTelemetry, allowed => {
|
||||
@@ -180,15 +164,6 @@ export class UserStore extends BaseStore<UserStoreModel> {
|
||||
this.hiddenTableColumns.get(tableId)?.toggle(columnId);
|
||||
}
|
||||
|
||||
@action
|
||||
resetKubeConfigPath() {
|
||||
this.kubeConfigPath = kubeConfigDefaultPath;
|
||||
}
|
||||
|
||||
@computed get isDefaultKubeConfigPath(): boolean {
|
||||
return this.kubeConfigPath === kubeConfigDefaultPath;
|
||||
}
|
||||
|
||||
@action
|
||||
async resetTheme() {
|
||||
await this.whenLoaded;
|
||||
@@ -206,44 +181,14 @@ export class UserStore extends BaseStore<UserStoreModel> {
|
||||
this.localeTimezone = tz;
|
||||
}
|
||||
|
||||
protected async refreshNewContexts() {
|
||||
try {
|
||||
const kubeConfig = await readFile(this.kubeConfigPath, "utf8");
|
||||
|
||||
if (kubeConfig) {
|
||||
this.newContexts.clear();
|
||||
loadConfig(kubeConfig).getContexts()
|
||||
.filter(ctx => ctx.cluster)
|
||||
.filter(ctx => !this.seenContexts.has(ctx.name))
|
||||
.forEach(ctx => this.newContexts.add(ctx.name));
|
||||
}
|
||||
} catch (err) {
|
||||
logger.error(err);
|
||||
this.resetKubeConfigPath();
|
||||
}
|
||||
}
|
||||
|
||||
@action
|
||||
markNewContextsAsSeen() {
|
||||
const { seenContexts, newContexts } = this;
|
||||
|
||||
this.seenContexts.replace([...seenContexts, ...newContexts]);
|
||||
this.newContexts.clear();
|
||||
}
|
||||
|
||||
@action
|
||||
protected async fromStore(data: Partial<UserStoreModel> = {}) {
|
||||
const { lastSeenAppVersion, seenContexts = [], preferences, kubeConfigPath } = data;
|
||||
const { lastSeenAppVersion, preferences } = data;
|
||||
|
||||
if (lastSeenAppVersion) {
|
||||
this.lastSeenAppVersion = lastSeenAppVersion;
|
||||
}
|
||||
|
||||
if (kubeConfigPath) {
|
||||
this.kubeConfigPath = kubeConfigPath;
|
||||
}
|
||||
this.seenContexts.replace(seenContexts);
|
||||
|
||||
if (!preferences) {
|
||||
return;
|
||||
}
|
||||
@@ -287,9 +232,7 @@ export class UserStore extends BaseStore<UserStoreModel> {
|
||||
}
|
||||
|
||||
const model: UserStoreModel = {
|
||||
kubeConfigPath: this.kubeConfigPath,
|
||||
lastSeenAppVersion: this.lastSeenAppVersion,
|
||||
seenContexts: Array.from(this.seenContexts),
|
||||
preferences: {
|
||||
httpsProxy: toJS(this.httpsProxy),
|
||||
shell: toJS(this.shell),
|
||||
|
||||
@@ -21,7 +21,9 @@
|
||||
|
||||
// Common utils (main OR renderer)
|
||||
|
||||
export const noop: any = () => { /* empty */ };
|
||||
export function noop<T extends any[]>(...args: T): void {
|
||||
return void args;
|
||||
}
|
||||
|
||||
export * from "./app-version";
|
||||
export * from "./autobind";
|
||||
@@ -39,8 +41,8 @@ export * from "./escapeRegExp";
|
||||
export * from "./extended-map";
|
||||
export * from "./getRandId";
|
||||
export * from "./openExternal";
|
||||
export * from "./paths";
|
||||
export * from "./reject-promise";
|
||||
export * from "./saveToAppFiles";
|
||||
export * from "./singleton";
|
||||
export * from "./splitArray";
|
||||
export * from "./tar";
|
||||
|
||||
@@ -19,17 +19,17 @@
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
// Save file to electron app directory (e.g. "/Users/$USER/Library/Application Support/Lens" for MacOS)
|
||||
import path from "path";
|
||||
import { app, remote } from "electron";
|
||||
import { ensureDirSync, writeFileSync } from "fs-extra";
|
||||
import type { WriteFileOptions } from "fs";
|
||||
import os from "os";
|
||||
|
||||
export function saveToAppFiles(filePath: string, contents: any, options?: WriteFileOptions): string {
|
||||
const absPath = path.resolve((app || remote.app).getPath("userData"), filePath);
|
||||
function resolveTilde(filePath: string) {
|
||||
if (filePath[0] === "~" && (filePath[1] === "/" || filePath.length === 1)) {
|
||||
return filePath.replace("~", os.homedir());
|
||||
}
|
||||
|
||||
ensureDirSync(path.dirname(absPath));
|
||||
writeFileSync(absPath, contents, options);
|
||||
return filePath;
|
||||
}
|
||||
|
||||
return absPath;
|
||||
export function resolvePath(filePath: string): string {
|
||||
return path.resolve(resolveTilde(filePath));
|
||||
}
|
||||
Reference in new issue
Block a user