mirror of
https://github.com/lensapp/lens.git
synced 2025-05-20 05:10:56 +00:00
Cascade different refactorings to eliminate global shared state from app paths
Co-authored-by: Mikko Aspiala <mikko.aspiala@gmail.com> Signed-off-by: Janne Savolainen <janne.savolainen@live.fi>
This commit is contained in:
1 parent
908a40975e
commit
9d33fff906
336 files changed
+9105
-3307
No files matched your search
@@ -20,29 +20,18 @@
|
||||
*/
|
||||
|
||||
import mockFs from "mock-fs";
|
||||
import { AppPaths } from "../app-paths";
|
||||
import { BaseStore } from "../base-store";
|
||||
import { action, comparer, makeObservable, observable, toJS } from "mobx";
|
||||
import { readFileSync } from "fs";
|
||||
import { getDisForUnitTesting } from "../../test-utils/get-dis-for-unit-testing";
|
||||
|
||||
AppPaths.init();
|
||||
import directoryForUserDataInjectable
|
||||
from "../app-paths/directory-for-user-data/directory-for-user-data.injectable";
|
||||
|
||||
jest.mock("electron", () => ({
|
||||
app: {
|
||||
getVersion: () => "99.99.99",
|
||||
getName: () => "lens",
|
||||
setName: jest.fn(),
|
||||
setPath: jest.fn(),
|
||||
getPath: () => "tmp",
|
||||
getLocale: () => "en",
|
||||
setLoginItemSettings: jest.fn(),
|
||||
},
|
||||
ipcMain: {
|
||||
handle: jest.fn(),
|
||||
on: jest.fn(),
|
||||
removeAllListeners: jest.fn(),
|
||||
off: jest.fn(),
|
||||
send: jest.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -105,10 +94,17 @@ describe("BaseStore", () => {
|
||||
let store: TestStore;
|
||||
|
||||
beforeEach(async () => {
|
||||
const dis = getDisForUnitTesting({ doGeneralOverrides: true });
|
||||
|
||||
dis.mainDi.override(directoryForUserDataInjectable, () => "some-user-data-directory");
|
||||
|
||||
await dis.runSetups();
|
||||
|
||||
store = undefined;
|
||||
TestStore.resetInstance();
|
||||
|
||||
const mockOpts = {
|
||||
"tmp": {
|
||||
"some-user-data-directory": {
|
||||
"test-store.json": JSON.stringify({}),
|
||||
},
|
||||
};
|
||||
@@ -130,7 +126,7 @@ describe("BaseStore", () => {
|
||||
a: "foo", b: "bar", c: "hello",
|
||||
});
|
||||
|
||||
const data = JSON.parse(readFileSync("tmp/test-store.json").toString());
|
||||
const data = JSON.parse(readFileSync("some-user-data-directory/test-store.json").toString());
|
||||
|
||||
expect(data).toEqual({ a: "foo", b: "bar", c: "hello" });
|
||||
});
|
||||
@@ -153,7 +149,7 @@ describe("BaseStore", () => {
|
||||
|
||||
expect(fileSpy).toHaveBeenCalledTimes(2);
|
||||
|
||||
const data = JSON.parse(readFileSync("tmp/test-store.json").toString());
|
||||
const data = JSON.parse(readFileSync("some-user-data-directory/test-store.json").toString());
|
||||
|
||||
expect(data).toEqual({ a: "a", b: "b", c: "" });
|
||||
});
|
||||
|
||||
@@ -24,17 +24,29 @@ 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 } from "../cluster-store";
|
||||
import type { Cluster } from "../cluster/cluster";
|
||||
import { ClusterStore } from "../cluster-store/cluster-store";
|
||||
import { Console } from "console";
|
||||
import { stdout, stderr } from "process";
|
||||
import type { ClusterId } from "../cluster-types";
|
||||
import { getCustomKubeConfigPath } from "../utils";
|
||||
import { AppPaths } from "../app-paths";
|
||||
import getCustomKubeConfigDirectoryInjectable from "../app-paths/get-custom-kube-config-directory/get-custom-kube-config-directory.injectable";
|
||||
import clusterStoreInjectable from "../cluster-store/cluster-store.injectable";
|
||||
import type { ClusterModel } from "../cluster-types";
|
||||
import type {
|
||||
DependencyInjectionContainer,
|
||||
} from "@ogre-tools/injectable";
|
||||
|
||||
|
||||
import { getDisForUnitTesting } from "../../test-utils/get-dis-for-unit-testing";
|
||||
import { createClusterInjectionToken } from "../cluster/create-cluster-injection-token";
|
||||
|
||||
import directoryForUserDataInjectable
|
||||
from "../app-paths/directory-for-user-data/directory-for-user-data.injectable";
|
||||
|
||||
console = new Console(stdout, stderr);
|
||||
|
||||
const testDataIcon = fs.readFileSync("test-data/cluster-store-migration-icon.png");
|
||||
const testDataIcon = fs.readFileSync(
|
||||
"test-data/cluster-store-migration-icon.png",
|
||||
);
|
||||
const kubeconfig = `
|
||||
apiVersion: v1
|
||||
clusters:
|
||||
@@ -59,25 +71,17 @@ users:
|
||||
token: kubeconfig-user-q4lm4:xxxyyyy
|
||||
`;
|
||||
|
||||
function embed(clusterId: ClusterId, contents: any): string {
|
||||
const absPath = getCustomKubeConfigPath(clusterId);
|
||||
const embed = (directoryName: string, contents: any): string => {
|
||||
fse.ensureDirSync(path.dirname(directoryName));
|
||||
fse.writeFileSync(directoryName, contents, {
|
||||
encoding: "utf-8",
|
||||
mode: 0o600,
|
||||
});
|
||||
|
||||
fse.ensureDirSync(path.dirname(absPath));
|
||||
fse.writeFileSync(absPath, contents, { encoding: "utf-8", mode: 0o600 });
|
||||
|
||||
return absPath;
|
||||
}
|
||||
return directoryName;
|
||||
};
|
||||
|
||||
jest.mock("electron", () => ({
|
||||
app: {
|
||||
getVersion: () => "99.99.99",
|
||||
getName: () => "lens",
|
||||
setName: jest.fn(),
|
||||
setPath: jest.fn(),
|
||||
getPath: () => "tmp",
|
||||
getLocale: () => "en",
|
||||
setLoginItemSettings: jest.fn(),
|
||||
},
|
||||
ipcMain: {
|
||||
handle: jest.fn(),
|
||||
on: jest.fn(),
|
||||
@@ -87,157 +91,194 @@ jest.mock("electron", () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
AppPaths.init();
|
||||
describe("cluster-store", () => {
|
||||
let mainDi: DependencyInjectionContainer;
|
||||
let clusterStore: ClusterStore;
|
||||
let createCluster: (model: ClusterModel) => Cluster;
|
||||
|
||||
describe("empty config", () => {
|
||||
beforeEach(async () => {
|
||||
ClusterStore.getInstance(false)?.unregisterIpcListener();
|
||||
ClusterStore.resetInstance();
|
||||
const mockOpts = {
|
||||
"tmp": {
|
||||
"lens-cluster-store.json": JSON.stringify({}),
|
||||
},
|
||||
};
|
||||
const dis = getDisForUnitTesting({ doGeneralOverrides: true });
|
||||
|
||||
mockFs(mockOpts);
|
||||
mockFs();
|
||||
|
||||
ClusterStore.createInstance();
|
||||
mainDi = dis.mainDi;
|
||||
|
||||
mainDi.override(directoryForUserDataInjectable, () => "some-directory-for-user-data");
|
||||
|
||||
await dis.runSetups();
|
||||
|
||||
createCluster = mainDi.inject(createClusterInjectionToken);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
mockFs.restore();
|
||||
});
|
||||
describe("empty config", () => {
|
||||
let getCustomKubeConfigDirectory: (directoryName: string) => string;
|
||||
|
||||
describe("with foo cluster added", () => {
|
||||
beforeEach(() => {
|
||||
ClusterStore.getInstance().addCluster(
|
||||
new Cluster({
|
||||
beforeEach(async () => {
|
||||
getCustomKubeConfigDirectory = mainDi.inject(
|
||||
getCustomKubeConfigDirectoryInjectable,
|
||||
);
|
||||
|
||||
// TODO: Remove these by removing Singleton base-class from BaseStore
|
||||
ClusterStore.getInstance(false)?.unregisterIpcListener();
|
||||
ClusterStore.resetInstance();
|
||||
|
||||
const mockOpts = {
|
||||
"some-directory-for-user-data": {
|
||||
"lens-cluster-store.json": JSON.stringify({}),
|
||||
},
|
||||
};
|
||||
|
||||
mockFs(mockOpts);
|
||||
|
||||
clusterStore = mainDi.inject(clusterStoreInjectable);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
mockFs.restore();
|
||||
});
|
||||
|
||||
describe("with foo cluster added", () => {
|
||||
beforeEach(() => {
|
||||
const cluster = createCluster({
|
||||
id: "foo",
|
||||
contextName: "foo",
|
||||
preferences: {
|
||||
terminalCWD: "/tmp",
|
||||
terminalCWD: "/some-directory-for-user-data",
|
||||
icon: "data:image/jpeg;base64, iVBORw0KGgoAAAANSUhEUgAAA1wAAAKoCAYAAABjkf5",
|
||||
clusterName: "minikube",
|
||||
},
|
||||
kubeConfigPath: embed("foo", kubeconfig),
|
||||
}),
|
||||
);
|
||||
});
|
||||
kubeConfigPath: embed(
|
||||
getCustomKubeConfigDirectory("foo"),
|
||||
kubeconfig,
|
||||
),
|
||||
});
|
||||
|
||||
it("adds new cluster to store", async () => {
|
||||
const storedCluster = ClusterStore.getInstance().getById("foo");
|
||||
|
||||
expect(storedCluster.id).toBe("foo");
|
||||
expect(storedCluster.preferences.terminalCWD).toBe("/tmp");
|
||||
expect(storedCluster.preferences.icon).toBe("data:image/jpeg;base64, iVBORw0KGgoAAAANSUhEUgAAA1wAAAKoCAYAAABjkf5");
|
||||
});
|
||||
});
|
||||
|
||||
describe("with prod and dev clusters added", () => {
|
||||
beforeEach(() => {
|
||||
const store = ClusterStore.getInstance();
|
||||
|
||||
store.addCluster({
|
||||
id: "prod",
|
||||
contextName: "foo",
|
||||
preferences: {
|
||||
clusterName: "prod",
|
||||
},
|
||||
kubeConfigPath: embed("prod", kubeconfig),
|
||||
clusterStore.addCluster(cluster);
|
||||
});
|
||||
store.addCluster({
|
||||
id: "dev",
|
||||
contextName: "foo2",
|
||||
preferences: {
|
||||
clusterName: "dev",
|
||||
},
|
||||
kubeConfigPath: embed("dev", kubeconfig),
|
||||
|
||||
it("adds new cluster to store", async () => {
|
||||
const storedCluster = clusterStore.getById("foo");
|
||||
|
||||
expect(storedCluster.id).toBe("foo");
|
||||
expect(storedCluster.preferences.terminalCWD).toBe("/some-directory-for-user-data");
|
||||
expect(storedCluster.preferences.icon).toBe(
|
||||
"data:image/jpeg;base64, iVBORw0KGgoAAAANSUhEUgAAA1wAAAKoCAYAAABjkf5",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("check if store can contain multiple clusters", () => {
|
||||
expect(ClusterStore.getInstance().hasClusters()).toBeTruthy();
|
||||
expect(ClusterStore.getInstance().clusters.size).toBe(2);
|
||||
});
|
||||
describe("with prod and dev clusters added", () => {
|
||||
beforeEach(() => {
|
||||
const store = clusterStore;
|
||||
|
||||
it("check if cluster's kubeconfig file saved", () => {
|
||||
const file = embed("boo", "kubeconfig");
|
||||
|
||||
expect(fs.readFileSync(file, "utf8")).toBe("kubeconfig");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("config with existing clusters", () => {
|
||||
beforeEach(() => {
|
||||
ClusterStore.resetInstance();
|
||||
const mockOpts = {
|
||||
"temp-kube-config": kubeconfig,
|
||||
"tmp": {
|
||||
"lens-cluster-store.json": JSON.stringify({
|
||||
__internal__: {
|
||||
migrations: {
|
||||
version: "99.99.99",
|
||||
},
|
||||
store.addCluster({
|
||||
id: "prod",
|
||||
contextName: "foo",
|
||||
preferences: {
|
||||
clusterName: "prod",
|
||||
},
|
||||
clusters: [
|
||||
{
|
||||
id: "cluster1",
|
||||
kubeConfigPath: "./temp-kube-config",
|
||||
contextName: "foo",
|
||||
preferences: { terminalCWD: "/foo" },
|
||||
workspace: "default",
|
||||
kubeConfigPath: embed(
|
||||
getCustomKubeConfigDirectory("prod"),
|
||||
kubeconfig,
|
||||
),
|
||||
});
|
||||
store.addCluster({
|
||||
id: "dev",
|
||||
contextName: "foo2",
|
||||
preferences: {
|
||||
clusterName: "dev",
|
||||
},
|
||||
kubeConfigPath: embed(
|
||||
getCustomKubeConfigDirectory("dev"),
|
||||
kubeconfig,
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
it("check if store can contain multiple clusters", () => {
|
||||
expect(clusterStore.hasClusters()).toBeTruthy();
|
||||
expect(clusterStore.clusters.size).toBe(2);
|
||||
});
|
||||
|
||||
it("check if cluster's kubeconfig file saved", () => {
|
||||
const file = embed(getCustomKubeConfigDirectory("boo"), "kubeconfig");
|
||||
|
||||
expect(fs.readFileSync(file, "utf8")).toBe("kubeconfig");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("config with existing clusters", () => {
|
||||
beforeEach(() => {
|
||||
ClusterStore.resetInstance();
|
||||
|
||||
const mockOpts = {
|
||||
"temp-kube-config": kubeconfig,
|
||||
"some-directory-for-user-data": {
|
||||
"lens-cluster-store.json": JSON.stringify({
|
||||
__internal__: {
|
||||
migrations: {
|
||||
version: "99.99.99",
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "cluster2",
|
||||
kubeConfigPath: "./temp-kube-config",
|
||||
contextName: "foo2",
|
||||
preferences: { terminalCWD: "/foo2" },
|
||||
},
|
||||
{
|
||||
id: "cluster3",
|
||||
kubeConfigPath: "./temp-kube-config",
|
||||
contextName: "foo",
|
||||
preferences: { terminalCWD: "/foo" },
|
||||
workspace: "foo",
|
||||
ownerRef: "foo",
|
||||
},
|
||||
],
|
||||
}),
|
||||
},
|
||||
};
|
||||
clusters: [
|
||||
{
|
||||
id: "cluster1",
|
||||
kubeConfigPath: "./temp-kube-config",
|
||||
contextName: "foo",
|
||||
preferences: { terminalCWD: "/foo" },
|
||||
workspace: "default",
|
||||
},
|
||||
{
|
||||
id: "cluster2",
|
||||
kubeConfigPath: "./temp-kube-config",
|
||||
contextName: "foo2",
|
||||
preferences: { terminalCWD: "/foo2" },
|
||||
},
|
||||
{
|
||||
id: "cluster3",
|
||||
kubeConfigPath: "./temp-kube-config",
|
||||
contextName: "foo",
|
||||
preferences: { terminalCWD: "/foo" },
|
||||
workspace: "foo",
|
||||
ownerRef: "foo",
|
||||
},
|
||||
],
|
||||
}),
|
||||
},
|
||||
};
|
||||
|
||||
mockFs(mockOpts);
|
||||
mockFs(mockOpts);
|
||||
|
||||
return ClusterStore.createInstance();
|
||||
clusterStore = mainDi.inject(clusterStoreInjectable);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
mockFs.restore();
|
||||
});
|
||||
|
||||
it("allows to retrieve a cluster", () => {
|
||||
const storedCluster = clusterStore.getById("cluster1");
|
||||
|
||||
expect(storedCluster.id).toBe("cluster1");
|
||||
expect(storedCluster.preferences.terminalCWD).toBe("/foo");
|
||||
});
|
||||
|
||||
it("allows getting all of the clusters", async () => {
|
||||
const storedClusters = clusterStore.clustersList;
|
||||
|
||||
expect(storedClusters.length).toBe(3);
|
||||
expect(storedClusters[0].id).toBe("cluster1");
|
||||
expect(storedClusters[0].preferences.terminalCWD).toBe("/foo");
|
||||
expect(storedClusters[1].id).toBe("cluster2");
|
||||
expect(storedClusters[1].preferences.terminalCWD).toBe("/foo2");
|
||||
expect(storedClusters[2].id).toBe("cluster3");
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
mockFs.restore();
|
||||
});
|
||||
|
||||
it("allows to retrieve a cluster", () => {
|
||||
const storedCluster = ClusterStore.getInstance().getById("cluster1");
|
||||
|
||||
expect(storedCluster.id).toBe("cluster1");
|
||||
expect(storedCluster.preferences.terminalCWD).toBe("/foo");
|
||||
});
|
||||
|
||||
it("allows getting all of the clusters", async () => {
|
||||
const storedClusters = ClusterStore.getInstance().clustersList;
|
||||
|
||||
expect(storedClusters.length).toBe(3);
|
||||
expect(storedClusters[0].id).toBe("cluster1");
|
||||
expect(storedClusters[0].preferences.terminalCWD).toBe("/foo");
|
||||
expect(storedClusters[1].id).toBe("cluster2");
|
||||
expect(storedClusters[1].preferences.terminalCWD).toBe("/foo2");
|
||||
expect(storedClusters[2].id).toBe("cluster3");
|
||||
});
|
||||
});
|
||||
|
||||
describe("config with invalid cluster kubeconfig", () => {
|
||||
beforeEach(() => {
|
||||
const invalidKubeconfig = `
|
||||
describe("config with invalid cluster kubeconfig", () => {
|
||||
beforeEach(() => {
|
||||
const invalidKubeconfig = `
|
||||
apiVersion: v1
|
||||
clusters:
|
||||
- cluster:
|
||||
@@ -257,302 +298,317 @@ users:
|
||||
token: kubeconfig-user-q4lm4:xxxyyyy
|
||||
`;
|
||||
|
||||
ClusterStore.resetInstance();
|
||||
const mockOpts = {
|
||||
"invalid-kube-config": invalidKubeconfig,
|
||||
"valid-kube-config": kubeconfig,
|
||||
"tmp": {
|
||||
"lens-cluster-store.json": JSON.stringify({
|
||||
__internal__: {
|
||||
migrations: {
|
||||
version: "99.99.99",
|
||||
},
|
||||
},
|
||||
clusters: [
|
||||
{
|
||||
id: "cluster1",
|
||||
kubeConfigPath: "./invalid-kube-config",
|
||||
contextName: "test",
|
||||
preferences: { terminalCWD: "/foo" },
|
||||
workspace: "foo",
|
||||
},
|
||||
{
|
||||
id: "cluster2",
|
||||
kubeConfigPath: "./valid-kube-config",
|
||||
contextName: "foo",
|
||||
preferences: { terminalCWD: "/foo" },
|
||||
workspace: "default",
|
||||
},
|
||||
ClusterStore.resetInstance();
|
||||
|
||||
],
|
||||
}),
|
||||
},
|
||||
};
|
||||
const mockOpts = {
|
||||
"invalid-kube-config": invalidKubeconfig,
|
||||
"valid-kube-config": kubeconfig,
|
||||
"some-directory-for-user-data": {
|
||||
"lens-cluster-store.json": JSON.stringify({
|
||||
__internal__: {
|
||||
migrations: {
|
||||
version: "99.99.99",
|
||||
},
|
||||
},
|
||||
clusters: [
|
||||
{
|
||||
id: "cluster1",
|
||||
kubeConfigPath: "./invalid-kube-config",
|
||||
contextName: "test",
|
||||
preferences: { terminalCWD: "/foo" },
|
||||
workspace: "foo",
|
||||
},
|
||||
{
|
||||
id: "cluster2",
|
||||
kubeConfigPath: "./valid-kube-config",
|
||||
contextName: "foo",
|
||||
preferences: { terminalCWD: "/foo" },
|
||||
workspace: "default",
|
||||
},
|
||||
],
|
||||
}),
|
||||
},
|
||||
};
|
||||
|
||||
mockFs(mockOpts);
|
||||
mockFs(mockOpts);
|
||||
|
||||
return ClusterStore.createInstance();
|
||||
clusterStore = mainDi.inject(clusterStoreInjectable);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
mockFs.restore();
|
||||
});
|
||||
|
||||
it("does not enable clusters with invalid kubeconfig", () => {
|
||||
const storedClusters = clusterStore.clustersList;
|
||||
|
||||
expect(storedClusters.length).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
mockFs.restore();
|
||||
describe("pre 2.0 config with an existing cluster", () => {
|
||||
beforeEach(() => {
|
||||
ClusterStore.resetInstance();
|
||||
|
||||
const mockOpts = {
|
||||
"some-directory-for-user-data": {
|
||||
"lens-cluster-store.json": JSON.stringify({
|
||||
__internal__: {
|
||||
migrations: {
|
||||
version: "1.0.0",
|
||||
},
|
||||
},
|
||||
cluster1: minimalValidKubeConfig,
|
||||
}),
|
||||
},
|
||||
};
|
||||
|
||||
mockFs(mockOpts);
|
||||
|
||||
clusterStore = mainDi.inject(clusterStoreInjectable);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
mockFs.restore();
|
||||
});
|
||||
|
||||
it("migrates to modern format with kubeconfig in a file", async () => {
|
||||
const config = clusterStore.clustersList[0].kubeConfigPath;
|
||||
|
||||
expect(fs.readFileSync(config, "utf8")).toContain(`"contexts":[`);
|
||||
});
|
||||
});
|
||||
|
||||
it("does not enable clusters with invalid kubeconfig", () => {
|
||||
const storedClusters = ClusterStore.getInstance().clustersList;
|
||||
describe("pre 2.6.0 config with a cluster that has arrays in auth config", () => {
|
||||
beforeEach(() => {
|
||||
ClusterStore.resetInstance();
|
||||
const mockOpts = {
|
||||
"some-directory-for-user-data": {
|
||||
"lens-cluster-store.json": JSON.stringify({
|
||||
__internal__: {
|
||||
migrations: {
|
||||
version: "2.4.1",
|
||||
},
|
||||
},
|
||||
cluster1: {
|
||||
kubeConfig: JSON.stringify({
|
||||
apiVersion: "v1",
|
||||
clusters: [
|
||||
{
|
||||
cluster: {
|
||||
server: "https://10.211.55.6:8443",
|
||||
},
|
||||
name: "minikube",
|
||||
},
|
||||
],
|
||||
contexts: [
|
||||
{
|
||||
context: {
|
||||
cluster: "minikube",
|
||||
user: "minikube",
|
||||
name: "minikube",
|
||||
},
|
||||
name: "minikube",
|
||||
},
|
||||
],
|
||||
"current-context": "minikube",
|
||||
kind: "Config",
|
||||
preferences: {},
|
||||
users: [
|
||||
{
|
||||
name: "minikube",
|
||||
user: {
|
||||
"client-certificate": "/Users/foo/.minikube/client.crt",
|
||||
"client-key": "/Users/foo/.minikube/client.key",
|
||||
"auth-provider": {
|
||||
config: {
|
||||
"access-token": ["should be string"],
|
||||
expiry: ["should be string"],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
},
|
||||
}),
|
||||
},
|
||||
};
|
||||
|
||||
expect(storedClusters.length).toBe(1);
|
||||
mockFs(mockOpts);
|
||||
|
||||
clusterStore = mainDi.inject(clusterStoreInjectable);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
mockFs.restore();
|
||||
});
|
||||
|
||||
it("replaces array format access token and expiry into string", async () => {
|
||||
const file = clusterStore.clustersList[0].kubeConfigPath;
|
||||
const config = fs.readFileSync(file, "utf8");
|
||||
const kc = yaml.load(config) as Record<string, any>;
|
||||
|
||||
expect(kc.users[0].user["auth-provider"].config["access-token"]).toBe(
|
||||
"should be string",
|
||||
);
|
||||
expect(kc.users[0].user["auth-provider"].config["expiry"]).toBe(
|
||||
"should be string",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("pre 2.6.0 config with a cluster icon", () => {
|
||||
beforeEach(() => {
|
||||
ClusterStore.resetInstance();
|
||||
const mockOpts = {
|
||||
"some-directory-for-user-data": {
|
||||
"lens-cluster-store.json": JSON.stringify({
|
||||
__internal__: {
|
||||
migrations: {
|
||||
version: "2.4.1",
|
||||
},
|
||||
},
|
||||
cluster1: {
|
||||
kubeConfig: minimalValidKubeConfig,
|
||||
icon: "icon_path",
|
||||
preferences: {
|
||||
terminalCWD: "/some-directory-for-user-data",
|
||||
},
|
||||
},
|
||||
}),
|
||||
icon_path: testDataIcon,
|
||||
},
|
||||
};
|
||||
|
||||
mockFs(mockOpts);
|
||||
|
||||
clusterStore = mainDi.inject(clusterStoreInjectable);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
mockFs.restore();
|
||||
});
|
||||
|
||||
it("moves the icon into preferences", async () => {
|
||||
const storedClusterData = clusterStore.clustersList[0];
|
||||
|
||||
expect(storedClusterData.hasOwnProperty("icon")).toBe(false);
|
||||
expect(storedClusterData.preferences.hasOwnProperty("icon")).toBe(true);
|
||||
expect(
|
||||
storedClusterData.preferences.icon.startsWith("data:;base64,"),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("for a pre 2.7.0-beta.0 config without a workspace", () => {
|
||||
beforeEach(() => {
|
||||
ClusterStore.resetInstance();
|
||||
const mockOpts = {
|
||||
"some-directory-for-user-data": {
|
||||
"lens-cluster-store.json": JSON.stringify({
|
||||
__internal__: {
|
||||
migrations: {
|
||||
version: "2.6.6",
|
||||
},
|
||||
},
|
||||
cluster1: {
|
||||
kubeConfig: minimalValidKubeConfig,
|
||||
preferences: {
|
||||
terminalCWD: "/some-directory-for-user-data",
|
||||
},
|
||||
},
|
||||
}),
|
||||
},
|
||||
};
|
||||
|
||||
mockFs(mockOpts);
|
||||
|
||||
clusterStore = mainDi.inject(clusterStoreInjectable);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
mockFs.restore();
|
||||
});
|
||||
});
|
||||
|
||||
describe("pre 3.6.0-beta.1 config with an existing cluster", () => {
|
||||
beforeEach(() => {
|
||||
ClusterStore.resetInstance();
|
||||
const mockOpts = {
|
||||
"some-directory-for-user-data": {
|
||||
"lens-cluster-store.json": JSON.stringify({
|
||||
__internal__: {
|
||||
migrations: {
|
||||
version: "3.5.0",
|
||||
},
|
||||
},
|
||||
clusters: [
|
||||
{
|
||||
id: "cluster1",
|
||||
kubeConfig: minimalValidKubeConfig,
|
||||
contextName: "cluster",
|
||||
preferences: {
|
||||
icon: "store://icon_path",
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
icon_path: testDataIcon,
|
||||
},
|
||||
};
|
||||
|
||||
mockFs(mockOpts);
|
||||
|
||||
clusterStore = mainDi.inject(clusterStoreInjectable);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
mockFs.restore();
|
||||
});
|
||||
|
||||
it("migrates to modern format with kubeconfig in a file", async () => {
|
||||
const config = clusterStore.clustersList[0].kubeConfigPath;
|
||||
|
||||
expect(fs.readFileSync(config, "utf8")).toBe(minimalValidKubeConfig);
|
||||
});
|
||||
|
||||
it("migrates to modern format with icon not in file", async () => {
|
||||
const { icon } = clusterStore.clustersList[0].preferences;
|
||||
|
||||
expect(icon.startsWith("data:;base64,")).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const minimalValidKubeConfig = JSON.stringify({
|
||||
apiVersion: "v1",
|
||||
clusters: [{
|
||||
name: "minikube",
|
||||
cluster: {
|
||||
server: "https://192.168.64.3:8443",
|
||||
clusters: [
|
||||
{
|
||||
name: "minikube",
|
||||
cluster: {
|
||||
server: "https://192.168.64.3:8443",
|
||||
},
|
||||
},
|
||||
}],
|
||||
],
|
||||
"current-context": "minikube",
|
||||
contexts: [{
|
||||
context: {
|
||||
cluster: "minikube",
|
||||
user: "minikube",
|
||||
contexts: [
|
||||
{
|
||||
context: {
|
||||
cluster: "minikube",
|
||||
user: "minikube",
|
||||
},
|
||||
name: "minikube",
|
||||
},
|
||||
name: "minikube",
|
||||
}],
|
||||
users: [{
|
||||
name: "minikube",
|
||||
user: {
|
||||
"client-certificate": "/Users/foo/.minikube/client.crt",
|
||||
"client-key": "/Users/foo/.minikube/client.key",
|
||||
],
|
||||
users: [
|
||||
{
|
||||
name: "minikube",
|
||||
user: {
|
||||
"client-certificate": "/Users/foo/.minikube/client.crt",
|
||||
"client-key": "/Users/foo/.minikube/client.key",
|
||||
},
|
||||
},
|
||||
}],
|
||||
],
|
||||
kind: "Config",
|
||||
preferences: {},
|
||||
});
|
||||
|
||||
describe("pre 2.0 config with an existing cluster", () => {
|
||||
beforeEach(() => {
|
||||
ClusterStore.resetInstance();
|
||||
const mockOpts = {
|
||||
"tmp": {
|
||||
"lens-cluster-store.json": JSON.stringify({
|
||||
__internal__: {
|
||||
migrations: {
|
||||
version: "1.0.0",
|
||||
},
|
||||
},
|
||||
cluster1: minimalValidKubeConfig,
|
||||
}),
|
||||
},
|
||||
};
|
||||
|
||||
mockFs(mockOpts);
|
||||
|
||||
return ClusterStore.createInstance();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
mockFs.restore();
|
||||
});
|
||||
|
||||
it("migrates to modern format with kubeconfig in a file", async () => {
|
||||
const config = ClusterStore.getInstance().clustersList[0].kubeConfigPath;
|
||||
|
||||
expect(fs.readFileSync(config, "utf8")).toContain(`"contexts":[`);
|
||||
});
|
||||
});
|
||||
|
||||
describe("pre 2.6.0 config with a cluster that has arrays in auth config", () => {
|
||||
beforeEach(() => {
|
||||
ClusterStore.resetInstance();
|
||||
const mockOpts = {
|
||||
"tmp": {
|
||||
"lens-cluster-store.json": JSON.stringify({
|
||||
__internal__: {
|
||||
migrations: {
|
||||
version: "2.4.1",
|
||||
},
|
||||
},
|
||||
cluster1: {
|
||||
kubeConfig: JSON.stringify({
|
||||
apiVersion: "v1",
|
||||
clusters: [{
|
||||
cluster: {
|
||||
server: "https://10.211.55.6:8443",
|
||||
},
|
||||
name: "minikube",
|
||||
}],
|
||||
contexts: [{
|
||||
context: {
|
||||
cluster: "minikube",
|
||||
user: "minikube",
|
||||
name: "minikube",
|
||||
},
|
||||
name: "minikube",
|
||||
}],
|
||||
"current-context": "minikube",
|
||||
kind: "Config",
|
||||
preferences: {},
|
||||
users: [{
|
||||
name: "minikube",
|
||||
user: {
|
||||
"client-certificate": "/Users/foo/.minikube/client.crt",
|
||||
"client-key": "/Users/foo/.minikube/client.key",
|
||||
"auth-provider": {
|
||||
config: {
|
||||
"access-token": [
|
||||
"should be string",
|
||||
],
|
||||
expiry: [
|
||||
"should be string",
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
}],
|
||||
}),
|
||||
},
|
||||
}),
|
||||
},
|
||||
};
|
||||
|
||||
mockFs(mockOpts);
|
||||
|
||||
return ClusterStore.createInstance();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
mockFs.restore();
|
||||
});
|
||||
|
||||
it("replaces array format access token and expiry into string", async () => {
|
||||
const file = ClusterStore.getInstance().clustersList[0].kubeConfigPath;
|
||||
const config = fs.readFileSync(file, "utf8");
|
||||
const kc = yaml.load(config) as Record<string, any>;
|
||||
|
||||
expect(kc.users[0].user["auth-provider"].config["access-token"]).toBe("should be string");
|
||||
expect(kc.users[0].user["auth-provider"].config["expiry"]).toBe("should be string");
|
||||
});
|
||||
});
|
||||
|
||||
describe("pre 2.6.0 config with a cluster icon", () => {
|
||||
beforeEach(() => {
|
||||
ClusterStore.resetInstance();
|
||||
const mockOpts = {
|
||||
"tmp": {
|
||||
"lens-cluster-store.json": JSON.stringify({
|
||||
__internal__: {
|
||||
migrations: {
|
||||
version: "2.4.1",
|
||||
},
|
||||
},
|
||||
cluster1: {
|
||||
kubeConfig: minimalValidKubeConfig,
|
||||
icon: "icon_path",
|
||||
preferences: {
|
||||
terminalCWD: "/tmp",
|
||||
},
|
||||
},
|
||||
}),
|
||||
"icon_path": testDataIcon,
|
||||
},
|
||||
};
|
||||
|
||||
mockFs(mockOpts);
|
||||
|
||||
return ClusterStore.createInstance();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
mockFs.restore();
|
||||
});
|
||||
|
||||
it("moves the icon into preferences", async () => {
|
||||
const storedClusterData = ClusterStore.getInstance().clustersList[0];
|
||||
|
||||
expect(storedClusterData.hasOwnProperty("icon")).toBe(false);
|
||||
expect(storedClusterData.preferences.hasOwnProperty("icon")).toBe(true);
|
||||
expect(storedClusterData.preferences.icon.startsWith("data:;base64,")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("for a pre 2.7.0-beta.0 config without a workspace", () => {
|
||||
beforeEach(() => {
|
||||
ClusterStore.resetInstance();
|
||||
const mockOpts = {
|
||||
"tmp": {
|
||||
"lens-cluster-store.json": JSON.stringify({
|
||||
__internal__: {
|
||||
migrations: {
|
||||
version: "2.6.6",
|
||||
},
|
||||
},
|
||||
cluster1: {
|
||||
kubeConfig: minimalValidKubeConfig,
|
||||
preferences: {
|
||||
terminalCWD: "/tmp",
|
||||
},
|
||||
},
|
||||
}),
|
||||
},
|
||||
};
|
||||
|
||||
mockFs(mockOpts);
|
||||
|
||||
return ClusterStore.createInstance();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
mockFs.restore();
|
||||
});
|
||||
});
|
||||
|
||||
describe("pre 3.6.0-beta.1 config with an existing cluster", () => {
|
||||
beforeEach(() => {
|
||||
ClusterStore.resetInstance();
|
||||
const mockOpts = {
|
||||
"tmp": {
|
||||
"lens-cluster-store.json": JSON.stringify({
|
||||
__internal__: {
|
||||
migrations: {
|
||||
version: "3.5.0",
|
||||
},
|
||||
},
|
||||
clusters: [
|
||||
{
|
||||
id: "cluster1",
|
||||
kubeConfig: minimalValidKubeConfig,
|
||||
contextName: "cluster",
|
||||
preferences: {
|
||||
icon: "store://icon_path",
|
||||
},
|
||||
},
|
||||
],
|
||||
}),
|
||||
"icon_path": testDataIcon,
|
||||
},
|
||||
};
|
||||
|
||||
mockFs(mockOpts);
|
||||
|
||||
return ClusterStore.createInstance();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
mockFs.restore();
|
||||
});
|
||||
|
||||
it("migrates to modern format with kubeconfig in a file", async () => {
|
||||
const config = ClusterStore.getInstance().clustersList[0].kubeConfigPath;
|
||||
|
||||
expect(fs.readFileSync(config, "utf8")).toBe(minimalValidKubeConfig);
|
||||
});
|
||||
|
||||
it("migrates to modern format with icon not in file", async () => {
|
||||
const { icon } = ClusterStore.getInstance().clustersList[0].preferences;
|
||||
|
||||
expect(icon.startsWith("data:;base64,")).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -19,7 +19,7 @@
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { appEventBus, AppEvent } from "../event-bus";
|
||||
import { appEventBus, AppEvent } from "../app-event-bus/event-bus";
|
||||
import { Console } from "console";
|
||||
import { stdout, stderr } from "process";
|
||||
|
||||
|
||||
@@ -23,10 +23,11 @@ import { anyObject } from "jest-mock-extended";
|
||||
import { merge } from "lodash";
|
||||
import mockFs from "mock-fs";
|
||||
import logger from "../../main/logger";
|
||||
import { AppPaths } from "../app-paths";
|
||||
import type { CatalogEntity, CatalogEntityData, CatalogEntityKindData } from "../catalog";
|
||||
import { ClusterStore } from "../cluster-store";
|
||||
import { HotbarStore } from "../hotbar-store";
|
||||
import { getDiForUnitTesting } from "../../main/getDiForUnitTesting";
|
||||
import directoryForUserDataInjectable
|
||||
from "../app-paths/directory-for-user-data/directory-for-user-data.injectable";
|
||||
|
||||
jest.mock("../../main/catalog/catalog-entity-registry", () => ({
|
||||
catalogEntityRegistry: {
|
||||
@@ -109,37 +110,24 @@ const awsCluster = getMockCatalogEntity({
|
||||
},
|
||||
});
|
||||
|
||||
jest.mock("electron", () => ({
|
||||
app: {
|
||||
getVersion: () => "99.99.99",
|
||||
getName: () => "lens",
|
||||
setName: jest.fn(),
|
||||
setPath: jest.fn(),
|
||||
getPath: () => "tmp",
|
||||
getLocale: () => "en",
|
||||
setLoginItemSettings: jest.fn(),
|
||||
},
|
||||
ipcMain: {
|
||||
on: jest.fn(),
|
||||
handle: jest.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
AppPaths.init();
|
||||
|
||||
describe("HotbarStore", () => {
|
||||
beforeEach(() => {
|
||||
beforeEach(async () => {
|
||||
const di = getDiForUnitTesting({ doGeneralOverrides: true });
|
||||
|
||||
di.override(directoryForUserDataInjectable, () => "some-directory-for-user-data");
|
||||
|
||||
await di.runSetups();
|
||||
|
||||
mockFs({
|
||||
"tmp": {
|
||||
"some-directory-for-user-data": {
|
||||
"lens-hotbar-store.json": JSON.stringify({}),
|
||||
},
|
||||
});
|
||||
ClusterStore.createInstance();
|
||||
|
||||
HotbarStore.createInstance();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
ClusterStore.resetInstance();
|
||||
HotbarStore.resetInstance();
|
||||
mockFs.restore();
|
||||
});
|
||||
@@ -339,7 +327,7 @@ describe("HotbarStore", () => {
|
||||
beforeEach(() => {
|
||||
HotbarStore.resetInstance();
|
||||
const mockOpts = {
|
||||
"tmp": {
|
||||
"some-directory-for-user-data": {
|
||||
"lens-hotbar-store.json": JSON.stringify({
|
||||
__internal__: {
|
||||
migrations: {
|
||||
|
||||
@@ -1,107 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) 2021 OpenLens Authors
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { SearchStore } from "../search-store";
|
||||
import { Console } from "console";
|
||||
import { stdout, stderr } from "process";
|
||||
|
||||
jest.mock("electron", () => ({
|
||||
app: {
|
||||
getPath: () => "/foo",
|
||||
},
|
||||
}));
|
||||
|
||||
console = new Console(stdout, stderr);
|
||||
|
||||
let searchStore: SearchStore = null;
|
||||
const logs = [
|
||||
"1:M 30 Oct 2020 16:17:41.553 # Connection with replica 172.17.0.12:6379 lost",
|
||||
"1:M 30 Oct 2020 16:17:41.623 * Replica 172.17.0.12:6379 asks for synchronization",
|
||||
"1:M 30 Oct 2020 16:17:41.623 * Starting Partial resynchronization request from 172.17.0.12:6379 accepted. Sending 0 bytes of backlog starting from offset 14407.",
|
||||
];
|
||||
|
||||
describe("search store tests", () => {
|
||||
beforeEach(async () => {
|
||||
searchStore = new SearchStore();
|
||||
});
|
||||
|
||||
it("does nothing with empty search query", () => {
|
||||
searchStore.onSearch([], "");
|
||||
expect(searchStore.occurrences).toEqual([]);
|
||||
});
|
||||
|
||||
it("doesn't break if no text provided", () => {
|
||||
searchStore.onSearch(null, "replica");
|
||||
expect(searchStore.occurrences).toEqual([]);
|
||||
|
||||
searchStore.onSearch([], "replica");
|
||||
expect(searchStore.occurrences).toEqual([]);
|
||||
});
|
||||
|
||||
it("find 3 occurrences across 3 lines", () => {
|
||||
searchStore.onSearch(logs, "172");
|
||||
expect(searchStore.occurrences).toEqual([0, 1, 2]);
|
||||
});
|
||||
|
||||
it("find occurrences within 1 line (case-insensitive)", () => {
|
||||
searchStore.onSearch(logs, "Starting");
|
||||
expect(searchStore.occurrences).toEqual([2, 2]);
|
||||
});
|
||||
|
||||
it("sets overlay index equal to first occurrence", () => {
|
||||
searchStore.onSearch(logs, "Replica");
|
||||
expect(searchStore.activeOverlayIndex).toBe(0);
|
||||
});
|
||||
|
||||
it("set overlay index to next occurrence", () => {
|
||||
searchStore.onSearch(logs, "172");
|
||||
searchStore.setNextOverlayActive();
|
||||
expect(searchStore.activeOverlayIndex).toBe(1);
|
||||
});
|
||||
|
||||
it("sets overlay to last occurrence", () => {
|
||||
searchStore.onSearch(logs, "172");
|
||||
searchStore.setPrevOverlayActive();
|
||||
expect(searchStore.activeOverlayIndex).toBe(2);
|
||||
});
|
||||
|
||||
it("gets line index where overlay is located", () => {
|
||||
searchStore.onSearch(logs, "synchronization");
|
||||
expect(searchStore.activeOverlayLine).toBe(1);
|
||||
});
|
||||
|
||||
it("escapes string for using in regex", () => {
|
||||
const regex = SearchStore.escapeRegex("some.interesting-query\\#?()[]");
|
||||
|
||||
expect(regex).toBe("some\\.interesting\\-query\\\\\\#\\?\\(\\)\\[\\]");
|
||||
});
|
||||
|
||||
it("gets active find number", () => {
|
||||
searchStore.onSearch(logs, "172");
|
||||
searchStore.setNextOverlayActive();
|
||||
expect(searchStore.activeFind).toBe(2);
|
||||
});
|
||||
|
||||
it("gets total finds number", () => {
|
||||
searchStore.onSearch(logs, "Starting");
|
||||
expect(searchStore.totalFinds).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -43,18 +43,39 @@ import { SemVer } from "semver";
|
||||
import electron from "electron";
|
||||
import { stdout, stderr } from "process";
|
||||
import { ThemeStore } from "../../renderer/theme.store";
|
||||
import type { ClusterStoreModel } from "../cluster-store";
|
||||
import { AppPaths } from "../app-paths";
|
||||
import type { ClusterStoreModel } from "../cluster-store/cluster-store";
|
||||
import { getDisForUnitTesting } from "../../test-utils/get-dis-for-unit-testing";
|
||||
import userStoreInjectable from "../user-store/user-store.injectable";
|
||||
import type { DependencyInjectionContainer } from "@ogre-tools/injectable";
|
||||
import directoryForUserDataInjectable from "../app-paths/directory-for-user-data/directory-for-user-data.injectable";
|
||||
|
||||
console = new Console(stdout, stderr);
|
||||
AppPaths.init();
|
||||
|
||||
describe("user store tests", () => {
|
||||
let userStore: UserStore;
|
||||
let mainDi: DependencyInjectionContainer;
|
||||
|
||||
beforeEach(async () => {
|
||||
const dis = getDisForUnitTesting({ doGeneralOverrides: true });
|
||||
|
||||
mockFs();
|
||||
|
||||
mainDi = dis.mainDi;
|
||||
|
||||
mainDi.override(directoryForUserDataInjectable, () => "some-directory-for-user-data");
|
||||
|
||||
await dis.runSetups();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
mockFs.restore();
|
||||
});
|
||||
|
||||
describe("for an empty config", () => {
|
||||
beforeEach(() => {
|
||||
mockFs({ tmp: { "config.json": "{}", "kube_config": "{}" }});
|
||||
mockFs({ "some-directory-for-user-data": { "config.json": "{}", "kube_config": "{}" }});
|
||||
|
||||
(UserStore.createInstance() as any).refreshNewContexts = jest.fn(() => Promise.resolve());
|
||||
userStore = mainDi.inject(userStoreInjectable);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -63,46 +84,38 @@ describe("user store tests", () => {
|
||||
});
|
||||
|
||||
it("allows setting and retrieving lastSeenAppVersion", () => {
|
||||
const us = UserStore.getInstance();
|
||||
|
||||
us.lastSeenAppVersion = "1.2.3";
|
||||
expect(us.lastSeenAppVersion).toBe("1.2.3");
|
||||
userStore.lastSeenAppVersion = "1.2.3";
|
||||
expect(userStore.lastSeenAppVersion).toBe("1.2.3");
|
||||
});
|
||||
|
||||
it("allows setting and getting preferences", () => {
|
||||
const us = UserStore.getInstance();
|
||||
userStore.httpsProxy = "abcd://defg";
|
||||
|
||||
us.httpsProxy = "abcd://defg";
|
||||
expect(userStore.httpsProxy).toBe("abcd://defg");
|
||||
expect(userStore.colorTheme).toBe(ThemeStore.defaultTheme);
|
||||
|
||||
expect(us.httpsProxy).toBe("abcd://defg");
|
||||
expect(us.colorTheme).toBe(ThemeStore.defaultTheme);
|
||||
|
||||
us.colorTheme = "light";
|
||||
expect(us.colorTheme).toBe("light");
|
||||
userStore.colorTheme = "light";
|
||||
expect(userStore.colorTheme).toBe("light");
|
||||
});
|
||||
|
||||
it("correctly resets theme to default value", async () => {
|
||||
const us = UserStore.getInstance();
|
||||
|
||||
us.colorTheme = "some other theme";
|
||||
us.resetTheme();
|
||||
expect(us.colorTheme).toBe(ThemeStore.defaultTheme);
|
||||
userStore.colorTheme = "some other theme";
|
||||
userStore.resetTheme();
|
||||
expect(userStore.colorTheme).toBe(ThemeStore.defaultTheme);
|
||||
});
|
||||
|
||||
it("correctly calculates if the last seen version is an old release", () => {
|
||||
const us = UserStore.getInstance();
|
||||
expect(userStore.isNewVersion).toBe(true);
|
||||
|
||||
expect(us.isNewVersion).toBe(true);
|
||||
|
||||
us.lastSeenAppVersion = (new SemVer(electron.app.getVersion())).inc("major").format();
|
||||
expect(us.isNewVersion).toBe(false);
|
||||
userStore.lastSeenAppVersion = (new SemVer(electron.app.getVersion())).inc("major").format();
|
||||
expect(userStore.isNewVersion).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("migrations", () => {
|
||||
beforeEach(() => {
|
||||
mockFs({
|
||||
"tmp": {
|
||||
"some-directory-for-user-data": {
|
||||
"config.json": JSON.stringify({
|
||||
user: { username: "foobar" },
|
||||
preferences: { colorTheme: "light" },
|
||||
@@ -112,7 +125,7 @@ describe("user store tests", () => {
|
||||
clusters: [
|
||||
{
|
||||
id: "foobar",
|
||||
kubeConfigPath: "tmp/extension_data/foo/bar",
|
||||
kubeConfigPath: "some-directory-for-user-data/extension_data/foo/bar",
|
||||
},
|
||||
{
|
||||
id: "barfoo",
|
||||
@@ -129,7 +142,7 @@ describe("user store tests", () => {
|
||||
},
|
||||
});
|
||||
|
||||
UserStore.createInstance();
|
||||
userStore = mainDi.inject(userStoreInjectable);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -138,16 +151,12 @@ describe("user store tests", () => {
|
||||
});
|
||||
|
||||
it("sets last seen app version to 0.0.0", () => {
|
||||
const us = UserStore.getInstance();
|
||||
|
||||
expect(us.lastSeenAppVersion).toBe("0.0.0");
|
||||
expect(userStore.lastSeenAppVersion).toBe("0.0.0");
|
||||
});
|
||||
|
||||
it.only("skips clusters for adding to kube-sync with files under extension_data/", () => {
|
||||
const us = UserStore.getInstance();
|
||||
|
||||
expect(us.syncKubeconfigEntries.has("tmp/extension_data/foo/bar")).toBe(false);
|
||||
expect(us.syncKubeconfigEntries.has("some/other/path")).toBe(true);
|
||||
expect(userStore.syncKubeconfigEntries.has("some-directory-for-user-data/extension_data/foo/bar")).toBe(false);
|
||||
expect(userStore.syncKubeconfigEntries.has("some/other/path")).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* Copyright (c) 2021 OpenLens Authors
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
import { getInjectable, lifecycleEnum } from "@ogre-tools/injectable";
|
||||
import { appEventBus } from "./event-bus";
|
||||
|
||||
const appEventBusInjectable = getInjectable({
|
||||
instantiate: () => appEventBus,
|
||||
lifecycle: lifecycleEnum.singleton,
|
||||
});
|
||||
|
||||
export default appEventBusInjectable;
|
||||
@@ -19,7 +19,7 @@
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { EventEmitter } from "./event-emitter";
|
||||
import { EventEmitter } from "../event-emitter";
|
||||
|
||||
export type AppEvent = {
|
||||
name: string;
|
||||
@@ -1,127 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) 2021 OpenLens Authors
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { app, ipcMain, ipcRenderer } from "electron";
|
||||
import { observable, when } from "mobx";
|
||||
import path from "path";
|
||||
import logger from "./logger";
|
||||
import { fromEntries, toJS } from "./utils";
|
||||
import { isWindows } from "./vars";
|
||||
|
||||
export type PathName = Parameters<typeof app["getPath"]>[0];
|
||||
|
||||
const pathNames: PathName[] = [
|
||||
"home",
|
||||
"appData",
|
||||
"userData",
|
||||
"cache",
|
||||
"temp",
|
||||
"exe",
|
||||
"module",
|
||||
"desktop",
|
||||
"documents",
|
||||
"downloads",
|
||||
"music",
|
||||
"pictures",
|
||||
"videos",
|
||||
"logs",
|
||||
"crashDumps",
|
||||
];
|
||||
|
||||
if (isWindows) {
|
||||
pathNames.push("recent");
|
||||
}
|
||||
|
||||
export class AppPaths {
|
||||
private static paths = observable.box<Record<PathName, string> | undefined>();
|
||||
private static readonly ipcChannel = "get-app-paths";
|
||||
|
||||
/**
|
||||
* Initializes the local copy of the paths from electron.
|
||||
*/
|
||||
static async init(): Promise<void> {
|
||||
logger.info(`[APP-PATHS]: initializing`);
|
||||
|
||||
if (AppPaths.paths.get()) {
|
||||
return void logger.error("[APP-PATHS]: init called more than once");
|
||||
}
|
||||
|
||||
if (ipcMain) {
|
||||
AppPaths.initMain();
|
||||
} else {
|
||||
await AppPaths.initRenderer();
|
||||
}
|
||||
}
|
||||
|
||||
private static initMain(): void {
|
||||
if (process.env.CICD) {
|
||||
app.setPath("appData", process.env.CICD);
|
||||
}
|
||||
|
||||
app.setPath("userData", path.join(app.getPath("appData"), app.getName()));
|
||||
|
||||
const getPath = (pathName: PathName) => {
|
||||
try {
|
||||
return app.getPath(pathName);
|
||||
} catch {
|
||||
logger.debug(`[APP-PATHS] No path found for ${pathName}`);
|
||||
|
||||
return "";
|
||||
}
|
||||
};
|
||||
|
||||
AppPaths.paths.set(fromEntries(pathNames.map(pathName => [pathName, getPath(pathName)] as const).filter(([, path]) => path)));
|
||||
ipcMain.handle(AppPaths.ipcChannel, () => toJS(AppPaths.paths.get()));
|
||||
}
|
||||
|
||||
private static async initRenderer(): Promise<void> {
|
||||
const paths = await ipcRenderer.invoke(AppPaths.ipcChannel);
|
||||
|
||||
if (!paths || typeof paths !== "object") {
|
||||
throw Object.assign(new Error("[APP-PATHS]: ipc handler returned unexpected data"), { data: paths });
|
||||
}
|
||||
|
||||
AppPaths.paths.set(paths);
|
||||
}
|
||||
|
||||
/**
|
||||
* An alternative to `app.getPath()` for use in renderer and common.
|
||||
* This function throws if called before initialization.
|
||||
* @param name The name of the path field
|
||||
*/
|
||||
static get(name: PathName): string {
|
||||
if (!AppPaths.paths.get()) {
|
||||
throw new Error("AppPaths.init() has not been called");
|
||||
}
|
||||
|
||||
return AppPaths.paths.get()[name];
|
||||
}
|
||||
|
||||
/**
|
||||
* An async version of `AppPaths.get()` which waits for `AppPaths.init()` to
|
||||
* be called before returning
|
||||
*/
|
||||
static async getAsync(name: PathName): Promise<string> {
|
||||
await when(() => Boolean(AppPaths.paths.get()));
|
||||
|
||||
return AppPaths.paths.get()[name];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* Copyright (c) 2021 OpenLens Authors
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
import { getInjectionToken } from "@ogre-tools/injectable";
|
||||
import type { PathName } from "./app-path-names";
|
||||
import { createChannel } from "../ipc-channel/create-channel/create-channel";
|
||||
|
||||
export type AppPaths = Record<PathName, string>;
|
||||
|
||||
export const appPathsInjectionToken = getInjectionToken<AppPaths>();
|
||||
|
||||
export const appPathsIpcChannel = createChannel<AppPaths>("app-paths");
|
||||
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* Copyright (c) 2021 OpenLens Authors
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
import type { app as electronApp } from "electron";
|
||||
|
||||
export type PathName = Parameters<typeof electronApp["getPath"]>[0];
|
||||
|
||||
export const pathNames: PathName[] = [
|
||||
"home",
|
||||
"appData",
|
||||
"userData",
|
||||
"cache",
|
||||
"temp",
|
||||
"exe",
|
||||
"module",
|
||||
"desktop",
|
||||
"documents",
|
||||
"downloads",
|
||||
"music",
|
||||
"pictures",
|
||||
"videos",
|
||||
"logs",
|
||||
"crashDumps",
|
||||
"recent",
|
||||
];
|
||||
@@ -0,0 +1,159 @@
|
||||
/**
|
||||
* Copyright (c) 2021 OpenLens Authors
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
import type { DependencyInjectionContainer } from "@ogre-tools/injectable";
|
||||
import { AppPaths, appPathsInjectionToken } from "./app-path-injection-token";
|
||||
import getElectronAppPathInjectable from "../../main/app-paths/get-electron-app-path/get-electron-app-path.injectable";
|
||||
import { getDisForUnitTesting } from "../../test-utils/get-dis-for-unit-testing";
|
||||
import type { PathName } from "./app-path-names";
|
||||
import setElectronAppPathInjectable from "../../main/app-paths/set-electron-app-path/set-electron-app-path.injectable";
|
||||
import appNameInjectable from "../../main/app-paths/app-name/app-name.injectable";
|
||||
import directoryForIntegrationTestingInjectable from "../../main/app-paths/directory-for-integration-testing/directory-for-integration-testing.injectable";
|
||||
|
||||
describe("app-paths", () => {
|
||||
let mainDi: DependencyInjectionContainer;
|
||||
let rendererDi: DependencyInjectionContainer;
|
||||
let runSetups: () => Promise<void[]>;
|
||||
|
||||
beforeEach(() => {
|
||||
const dis = getDisForUnitTesting({ doGeneralOverrides: true });
|
||||
|
||||
mainDi = dis.mainDi;
|
||||
rendererDi = dis.rendererDi;
|
||||
runSetups = dis.runSetups;
|
||||
|
||||
const defaultAppPathsStub: AppPaths = {
|
||||
appData: "some-app-data",
|
||||
cache: "some-cache",
|
||||
crashDumps: "some-crash-dumps",
|
||||
desktop: "some-desktop",
|
||||
documents: "some-documents",
|
||||
downloads: "some-downloads",
|
||||
exe: "some-exe",
|
||||
home: "some-home-path",
|
||||
logs: "some-logs",
|
||||
module: "some-module",
|
||||
music: "some-music",
|
||||
pictures: "some-pictures",
|
||||
recent: "some-recent",
|
||||
temp: "some-temp",
|
||||
videos: "some-videos",
|
||||
userData: "some-irrelevant",
|
||||
};
|
||||
|
||||
mainDi.override(
|
||||
getElectronAppPathInjectable,
|
||||
() =>
|
||||
(key: PathName): string | null =>
|
||||
defaultAppPathsStub[key],
|
||||
);
|
||||
|
||||
mainDi.override(
|
||||
setElectronAppPathInjectable,
|
||||
() =>
|
||||
(key: PathName, path: string): void => {
|
||||
defaultAppPathsStub[key] = path;
|
||||
},
|
||||
);
|
||||
|
||||
mainDi.override(appNameInjectable, () => "some-app-name");
|
||||
});
|
||||
|
||||
describe("normally", () => {
|
||||
beforeEach(async () => {
|
||||
await runSetups();
|
||||
});
|
||||
|
||||
it("given in renderer, when injecting app paths, returns application specific app paths", () => {
|
||||
const actual = rendererDi.inject(appPathsInjectionToken);
|
||||
|
||||
expect(actual).toEqual({
|
||||
appData: "some-app-data",
|
||||
cache: "some-cache",
|
||||
crashDumps: "some-crash-dumps",
|
||||
desktop: "some-desktop",
|
||||
documents: "some-documents",
|
||||
downloads: "some-downloads",
|
||||
exe: "some-exe",
|
||||
home: "some-home-path",
|
||||
logs: "some-logs",
|
||||
module: "some-module",
|
||||
music: "some-music",
|
||||
pictures: "some-pictures",
|
||||
recent: "some-recent",
|
||||
temp: "some-temp",
|
||||
videos: "some-videos",
|
||||
userData: "some-app-data/some-app-name",
|
||||
});
|
||||
});
|
||||
|
||||
it("given in main, when injecting app paths, returns application specific app paths", () => {
|
||||
const actual = mainDi.inject(appPathsInjectionToken);
|
||||
|
||||
expect(actual).toEqual({
|
||||
appData: "some-app-data",
|
||||
cache: "some-cache",
|
||||
crashDumps: "some-crash-dumps",
|
||||
desktop: "some-desktop",
|
||||
documents: "some-documents",
|
||||
downloads: "some-downloads",
|
||||
exe: "some-exe",
|
||||
home: "some-home-path",
|
||||
logs: "some-logs",
|
||||
module: "some-module",
|
||||
music: "some-music",
|
||||
pictures: "some-pictures",
|
||||
recent: "some-recent",
|
||||
temp: "some-temp",
|
||||
videos: "some-videos",
|
||||
userData: "some-app-data/some-app-name",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("when running integration tests", () => {
|
||||
beforeEach(async () => {
|
||||
mainDi.override(
|
||||
directoryForIntegrationTestingInjectable,
|
||||
() => "some-integration-testing-app-data",
|
||||
);
|
||||
|
||||
await runSetups();
|
||||
});
|
||||
|
||||
it("given in renderer, when injecting path for app data, has integration specific app data path", () => {
|
||||
const { appData, userData } = rendererDi.inject(appPathsInjectionToken);
|
||||
|
||||
expect({ appData, userData }).toEqual({
|
||||
appData: "some-integration-testing-app-data",
|
||||
userData: "some-integration-testing-app-data/some-app-name",
|
||||
});
|
||||
});
|
||||
|
||||
it("given in main, when injecting path for app data, has integration specific app data path", () => {
|
||||
const { appData, userData } = rendererDi.inject(appPathsInjectionToken);
|
||||
|
||||
expect({ appData, userData }).toEqual({
|
||||
appData: "some-integration-testing-app-data",
|
||||
userData: "some-integration-testing-app-data/some-app-name",
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
+9
-10
@@ -18,16 +18,15 @@
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { getInjectable, lifecycleEnum } from "@ogre-tools/injectable";
|
||||
import path from "path";
|
||||
import * as uuid from "uuid";
|
||||
import { AppPaths } from "../app-paths";
|
||||
import type { ClusterId } from "../cluster-types";
|
||||
import directoryForUserDataInjectable from "../directory-for-user-data/directory-for-user-data.injectable";
|
||||
|
||||
export function storedKubeConfigFolder(): string {
|
||||
return path.resolve(AppPaths.get("userData"), "kubeconfigs");
|
||||
}
|
||||
const directoryForBinariesInjectable = getInjectable({
|
||||
instantiate: (di) =>
|
||||
path.join(di.inject(directoryForUserDataInjectable), "binaries"),
|
||||
|
||||
export function getCustomKubeConfigPath(clusterId: ClusterId = uuid.v4()): string {
|
||||
return path.resolve(storedKubeConfigFolder(), clusterId);
|
||||
}
|
||||
lifecycle: lifecycleEnum.singleton,
|
||||
});
|
||||
|
||||
export default directoryForBinariesInjectable;
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* Copyright (c) 2021 OpenLens Authors
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
import { getInjectable, lifecycleEnum } from "@ogre-tools/injectable";
|
||||
import { appPathsInjectionToken } from "../app-path-injection-token";
|
||||
|
||||
const directoryForDownloadsInjectable = getInjectable({
|
||||
instantiate: (di) => di.inject(appPathsInjectionToken).downloads,
|
||||
lifecycle: lifecycleEnum.singleton,
|
||||
});
|
||||
|
||||
export default directoryForDownloadsInjectable;
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* Copyright (c) 2021 OpenLens Authors
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
import { getInjectable, lifecycleEnum } from "@ogre-tools/injectable";
|
||||
import { appPathsInjectionToken } from "../app-path-injection-token";
|
||||
|
||||
const directoryForExesInjectable = getInjectable({
|
||||
instantiate: (di) => di.inject(appPathsInjectionToken).exe,
|
||||
lifecycle: lifecycleEnum.singleton,
|
||||
});
|
||||
|
||||
export default directoryForExesInjectable;
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* Copyright (c) 2021 OpenLens Authors
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
import { getInjectable, lifecycleEnum } from "@ogre-tools/injectable";
|
||||
import directoryForUserDataInjectable from "../directory-for-user-data/directory-for-user-data.injectable";
|
||||
import path from "path";
|
||||
|
||||
const directoryForKubeConfigsInjectable = getInjectable({
|
||||
instantiate: (di) =>
|
||||
path.resolve(di.inject(directoryForUserDataInjectable), "kubeconfigs"),
|
||||
|
||||
lifecycle: lifecycleEnum.singleton,
|
||||
});
|
||||
|
||||
export default directoryForKubeConfigsInjectable;
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* Copyright (c) 2021 OpenLens Authors
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
import { getInjectable, lifecycleEnum } from "@ogre-tools/injectable";
|
||||
import { appPathsInjectionToken } from "../app-path-injection-token";
|
||||
|
||||
const directoryForTempInjectable = getInjectable({
|
||||
instantiate: (di) => di.inject(appPathsInjectionToken).temp,
|
||||
lifecycle: lifecycleEnum.singleton,
|
||||
});
|
||||
|
||||
export default directoryForTempInjectable;
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* Copyright (c) 2021 OpenLens Authors
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
import { getInjectable, lifecycleEnum } from "@ogre-tools/injectable";
|
||||
import { appPathsInjectionToken } from "../app-path-injection-token";
|
||||
|
||||
const directoryForUserDataInjectable = getInjectable({
|
||||
instantiate: (di) => di.inject(appPathsInjectionToken).userData,
|
||||
lifecycle: lifecycleEnum.singleton,
|
||||
});
|
||||
|
||||
export default directoryForUserDataInjectable;
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* Copyright (c) 2021 OpenLens Authors
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
import { getInjectable, lifecycleEnum } from "@ogre-tools/injectable";
|
||||
import path from "path";
|
||||
import directoryForKubeConfigsInjectable from "../directory-for-kube-configs/directory-for-kube-configs.injectable";
|
||||
|
||||
const getCustomKubeConfigDirectoryInjectable = getInjectable({
|
||||
instantiate: (di) => (directoryName: string) => {
|
||||
const directoryForKubeConfigs = di.inject(directoryForKubeConfigsInjectable);
|
||||
|
||||
return path.resolve(
|
||||
directoryForKubeConfigs,
|
||||
directoryName,
|
||||
);
|
||||
},
|
||||
|
||||
lifecycle: lifecycleEnum.singleton,
|
||||
});
|
||||
|
||||
export default getCustomKubeConfigDirectoryInjectable;
|
||||
@@ -30,7 +30,9 @@ import { broadcastMessage, ipcMainOn, ipcRendererOn } from "./ipc";
|
||||
import isEqual from "lodash/isEqual";
|
||||
import { isTestEnv } from "./vars";
|
||||
import { kebabCase } from "lodash";
|
||||
import { AppPaths } from "./app-paths";
|
||||
import { getLegacyGlobalDiForExtensionApi } from "../extensions/as-legacy-global-function-for-extension-api/legacy-global-di-for-extension-api";
|
||||
import directoryForUserDataInjectable
|
||||
from "./app-paths/directory-for-user-data/directory-for-user-data.injectable";
|
||||
|
||||
export interface BaseStoreParams<T> extends ConfOptions<T> {
|
||||
syncOptions?: {
|
||||
@@ -102,7 +104,9 @@ export abstract class BaseStore<T> extends Singleton {
|
||||
}
|
||||
|
||||
protected cwd() {
|
||||
return AppPaths.get("userData");
|
||||
const di = getLegacyGlobalDiForExtensionApi();
|
||||
|
||||
return di.inject(directoryForUserDataInjectable);
|
||||
}
|
||||
|
||||
protected saveToFile(model: T) {
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
import { catalogCategoryRegistry } from "../catalog/catalog-category-registry";
|
||||
import { CatalogEntity, CatalogEntityActionContext, CatalogEntityContextMenuContext, CatalogEntityMetadata, CatalogEntityStatus } from "../catalog";
|
||||
import { clusterActivateHandler, clusterDisconnectHandler } from "../cluster-ipc";
|
||||
import { ClusterStore } from "../cluster-store";
|
||||
import { ClusterStore } from "../cluster-store/cluster-store";
|
||||
import { broadcastMessage, requestMain } from "../ipc";
|
||||
import { CatalogCategory, CatalogCategorySpec } from "../catalog";
|
||||
import { app } from "electron";
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* Copyright (c) 2021 OpenLens Authors
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
import { getInjectable, lifecycleEnum } from "@ogre-tools/injectable";
|
||||
import { ClusterStore } from "./cluster-store";
|
||||
import { createClusterInjectionToken } from "../cluster/create-cluster-injection-token";
|
||||
|
||||
const clusterStoreInjectable = getInjectable({
|
||||
instantiate: (di) =>
|
||||
ClusterStore.createInstance({
|
||||
createCluster: di.inject(createClusterInjectionToken),
|
||||
}),
|
||||
|
||||
lifecycle: lifecycleEnum.singleton,
|
||||
});
|
||||
|
||||
export default clusterStoreInjectable;
|
||||
@@ -18,17 +18,18 @@
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
|
||||
import { ipcMain, ipcRenderer, webFrame } from "electron";
|
||||
import { action, comparer, computed, makeObservable, observable, reaction } from "mobx";
|
||||
import { BaseStore } from "./base-store";
|
||||
import { Cluster } from "../main/cluster";
|
||||
import migrations from "../migrations/cluster-store";
|
||||
import logger from "../main/logger";
|
||||
import { appEventBus } from "./event-bus";
|
||||
import { ipcMainHandle, requestMain } from "./ipc";
|
||||
import { disposer, toJS } from "./utils";
|
||||
import type { ClusterModel, ClusterId, ClusterState } from "./cluster-types";
|
||||
import { BaseStore } from "../base-store";
|
||||
import { Cluster } from "../cluster/cluster";
|
||||
import migrations from "../../migrations/cluster-store";
|
||||
import logger from "../../main/logger";
|
||||
import { appEventBus } from "../app-event-bus/event-bus";
|
||||
import { ipcMainHandle, requestMain } from "../ipc";
|
||||
import { disposer, toJS } from "../utils";
|
||||
import type { ClusterModel, ClusterId, ClusterState } from "../cluster-types";
|
||||
|
||||
export interface ClusterStoreModel {
|
||||
clusters?: ClusterModel[];
|
||||
@@ -36,13 +37,17 @@ export interface ClusterStoreModel {
|
||||
|
||||
const initialStates = "cluster:states";
|
||||
|
||||
interface Dependencies {
|
||||
createCluster: (model: ClusterModel) => Cluster
|
||||
}
|
||||
|
||||
export class ClusterStore extends BaseStore<ClusterStoreModel> {
|
||||
readonly displayName = "ClusterStore";
|
||||
clusters = observable.map<ClusterId, Cluster>();
|
||||
|
||||
protected disposer = disposer();
|
||||
|
||||
constructor() {
|
||||
constructor(private dependencies: Dependencies) {
|
||||
super({
|
||||
configName: "lens-cluster-store",
|
||||
accessPropertiesByDotNotation: false, // To make dots safe in cluster context names
|
||||
@@ -123,7 +128,7 @@ export class ClusterStore extends BaseStore<ClusterStoreModel> {
|
||||
|
||||
const cluster = clusterOrModel instanceof Cluster
|
||||
? clusterOrModel
|
||||
: new Cluster(clusterOrModel);
|
||||
: this.dependencies.createCluster(clusterOrModel);
|
||||
|
||||
this.clusters.set(cluster.id, cluster);
|
||||
|
||||
@@ -143,7 +148,7 @@ export class ClusterStore extends BaseStore<ClusterStoreModel> {
|
||||
if (cluster) {
|
||||
cluster.updateModel(clusterModel);
|
||||
} else {
|
||||
cluster = new Cluster(clusterModel);
|
||||
cluster = this.dependencies.createCluster(clusterModel);
|
||||
}
|
||||
newClusters.set(clusterModel.id, cluster);
|
||||
} catch (error) {
|
||||
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* Copyright (c) 2021 OpenLens Authors
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
import { getInjectable, lifecycleEnum } from "@ogre-tools/injectable";
|
||||
import { getHostedClusterId } from "../../utils";
|
||||
import clusterStoreInjectable from "../cluster-store.injectable";
|
||||
|
||||
const hostedClusterInjectable = getInjectable({
|
||||
instantiate: (di) => {
|
||||
const hostedClusterId = getHostedClusterId();
|
||||
|
||||
return di.inject(clusterStoreInjectable).getById(hostedClusterId);
|
||||
},
|
||||
|
||||
lifecycle: lifecycleEnum.singleton,
|
||||
});
|
||||
|
||||
export default hostedClusterInjectable;
|
||||
@@ -0,0 +1,731 @@
|
||||
/**
|
||||
* Copyright (c) 2021 OpenLens Authors
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { ipcMain } from "electron";
|
||||
import { action, comparer, computed, makeObservable, observable, reaction, when } from "mobx";
|
||||
import { broadcastMessage, ClusterListNamespaceForbiddenChannel } from "../ipc";
|
||||
import type { ContextHandler } from "../../main/context-handler/context-handler";
|
||||
import { AuthorizationV1Api, CoreV1Api, HttpError, KubeConfig, V1ResourceAttributes } from "@kubernetes/client-node";
|
||||
import type { Kubectl } from "../../main/kubectl/kubectl";
|
||||
import type { KubeconfigManager } from "../../main/kubeconfig-manager/kubeconfig-manager";
|
||||
import { loadConfigFromFile, loadConfigFromFileSync, validateKubeConfig } from "../kube-helpers";
|
||||
import { apiResourceRecord, apiResources, KubeApiResource, KubeResource } from "../rbac";
|
||||
import logger from "../../main/logger";
|
||||
import { VersionDetector } from "../../main/cluster-detectors/version-detector";
|
||||
import { DetectorRegistry } from "../../main/cluster-detectors/detector-registry";
|
||||
import plimit from "p-limit";
|
||||
import type { ClusterState, ClusterRefreshOptions, ClusterMetricsResourceType, ClusterId, ClusterMetadata, ClusterModel, ClusterPreferences, ClusterPrometheusPreferences, UpdateClusterModel, KubeAuthUpdate } from "../cluster-types";
|
||||
import { ClusterMetadataKey, initialNodeShellImage, ClusterStatus } from "../cluster-types";
|
||||
import { disposer, toJS } from "../utils";
|
||||
import type { Response } from "request";
|
||||
|
||||
interface Dependencies {
|
||||
directoryForKubeConfigs: string,
|
||||
createKubeconfigManager: (cluster: Cluster) => KubeconfigManager,
|
||||
createContextHandler: (cluster: Cluster) => ContextHandler,
|
||||
createKubectl: (clusterVersion: string) => Kubectl
|
||||
}
|
||||
|
||||
/**
|
||||
* Cluster
|
||||
*
|
||||
* @beta
|
||||
*/
|
||||
export class Cluster implements ClusterModel, ClusterState {
|
||||
/** Unique id for a cluster */
|
||||
public readonly id: ClusterId;
|
||||
private kubeCtl: Kubectl;
|
||||
/**
|
||||
* Context handler
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
public contextHandler: ContextHandler;
|
||||
protected proxyKubeconfigManager: KubeconfigManager;
|
||||
protected eventsDisposer = disposer();
|
||||
protected activated = false;
|
||||
private resourceAccessStatuses: Map<KubeApiResource, boolean> = new Map();
|
||||
|
||||
get whenReady() {
|
||||
return when(() => this.ready);
|
||||
}
|
||||
|
||||
/**
|
||||
* Kubeconfig context name
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
@observable contextName: string;
|
||||
/**
|
||||
* Path to kubeconfig
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
@observable kubeConfigPath: string;
|
||||
/**
|
||||
* @deprecated
|
||||
*/
|
||||
@observable workspace: string;
|
||||
/**
|
||||
* @deprecated
|
||||
*/
|
||||
@observable workspaces: string[];
|
||||
/**
|
||||
* Kubernetes API server URL
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
@observable apiUrl: string; // cluster server url
|
||||
/**
|
||||
* Is cluster online
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
@observable online = false; // describes if we can detect that cluster is online
|
||||
/**
|
||||
* Can user access cluster resources
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
@observable accessible = false; // if user is able to access cluster resources
|
||||
/**
|
||||
* Is cluster instance in usable state
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
@observable ready = false; // cluster is in usable state
|
||||
/**
|
||||
* Is cluster currently reconnecting
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
@observable reconnecting = false;
|
||||
/**
|
||||
* Is cluster disconnected. False if user has selected to connect.
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
@observable disconnected = true;
|
||||
/**
|
||||
* Does user have admin like access
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
@observable isAdmin = false;
|
||||
|
||||
/**
|
||||
* Global watch-api accessibility , e.g. "/api/v1/services?watch=1"
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
@observable isGlobalWatchEnabled = false;
|
||||
/**
|
||||
* Preferences
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
@observable preferences: ClusterPreferences = {};
|
||||
/**
|
||||
* Metadata
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
@observable metadata: ClusterMetadata = {};
|
||||
/**
|
||||
* List of allowed namespaces verified via K8S::SelfSubjectAccessReview api
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
@observable allowedNamespaces: string[] = [];
|
||||
/**
|
||||
* List of allowed resources
|
||||
*
|
||||
* @observable
|
||||
* @internal
|
||||
*/
|
||||
@observable allowedResources: string[] = [];
|
||||
/**
|
||||
* List of accessible namespaces provided by user in the Cluster Settings
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
@observable accessibleNamespaces: string[] = [];
|
||||
|
||||
/**
|
||||
* Labels for the catalog entity
|
||||
*/
|
||||
@observable labels: Record<string, string> = {};
|
||||
|
||||
/**
|
||||
* Is cluster available
|
||||
*
|
||||
* @computed
|
||||
*/
|
||||
@computed get available() {
|
||||
return this.accessible && !this.disconnected;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cluster name
|
||||
*
|
||||
* @computed
|
||||
*/
|
||||
@computed get name() {
|
||||
return this.preferences.clusterName || this.contextName;
|
||||
}
|
||||
|
||||
/**
|
||||
* The detected kubernetes distribution
|
||||
*/
|
||||
@computed get distribution(): string {
|
||||
return this.metadata[ClusterMetadataKey.DISTRIBUTION]?.toString() || "unknown";
|
||||
}
|
||||
|
||||
/**
|
||||
* The detected kubernetes version
|
||||
*/
|
||||
@computed get version(): string {
|
||||
return this.metadata[ClusterMetadataKey.VERSION]?.toString() || "unknown";
|
||||
}
|
||||
|
||||
/**
|
||||
* Prometheus preferences
|
||||
*
|
||||
* @computed
|
||||
* @internal
|
||||
*/
|
||||
@computed get prometheusPreferences(): ClusterPrometheusPreferences {
|
||||
const { prometheus, prometheusProvider } = this.preferences;
|
||||
|
||||
return toJS({ prometheus, prometheusProvider });
|
||||
}
|
||||
|
||||
/**
|
||||
* defaultNamespace preference
|
||||
*
|
||||
* @computed
|
||||
* @internal
|
||||
*/
|
||||
@computed get defaultNamespace(): string {
|
||||
return this.preferences.defaultNamespace;
|
||||
}
|
||||
|
||||
constructor(private dependencies: Dependencies, model: ClusterModel) {
|
||||
makeObservable(this);
|
||||
this.id = model.id;
|
||||
this.updateModel(model);
|
||||
|
||||
const { config } = loadConfigFromFileSync(this.kubeConfigPath);
|
||||
const validationError = validateKubeConfig(config, this.contextName);
|
||||
|
||||
if (validationError) {
|
||||
throw validationError;
|
||||
}
|
||||
|
||||
this.apiUrl = config.getCluster(config.getContextObject(this.contextName).cluster).server;
|
||||
|
||||
if (ipcMain) {
|
||||
// for the time being, until renderer gets its own cluster type
|
||||
this.contextHandler = this.dependencies.createContextHandler(this);
|
||||
this.proxyKubeconfigManager = this.dependencies.createKubeconfigManager(this);
|
||||
|
||||
logger.debug(`[CLUSTER]: Cluster init success`, {
|
||||
id: this.id,
|
||||
context: this.contextName,
|
||||
apiUrl: this.apiUrl,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update cluster data model
|
||||
*
|
||||
* @param model
|
||||
*/
|
||||
@action updateModel(model: UpdateClusterModel) {
|
||||
// Note: do not assign ID as that should never be updated
|
||||
|
||||
this.kubeConfigPath = model.kubeConfigPath;
|
||||
|
||||
if (model.workspace) {
|
||||
this.workspace = model.workspace;
|
||||
}
|
||||
|
||||
if (model.workspaces) {
|
||||
this.workspaces = model.workspaces;
|
||||
}
|
||||
|
||||
if (model.contextName) {
|
||||
this.contextName = model.contextName;
|
||||
}
|
||||
|
||||
if (model.preferences) {
|
||||
this.preferences = model.preferences;
|
||||
}
|
||||
|
||||
if (model.metadata) {
|
||||
this.metadata = model.metadata;
|
||||
}
|
||||
|
||||
if (model.accessibleNamespaces) {
|
||||
this.accessibleNamespaces = model.accessibleNamespaces;
|
||||
}
|
||||
|
||||
if (model.labels) {
|
||||
this.labels = model.labels;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
protected bindEvents() {
|
||||
logger.info(`[CLUSTER]: bind events`, this.getMeta());
|
||||
const refreshTimer = setInterval(() => !this.disconnected && this.refresh(), 30000); // every 30s
|
||||
const refreshMetadataTimer = setInterval(() => !this.disconnected && this.refreshMetadata(), 900000); // every 15 minutes
|
||||
|
||||
this.eventsDisposer.push(
|
||||
reaction(() => this.getState(), state => this.pushState(state)),
|
||||
reaction(
|
||||
() => this.prometheusPreferences,
|
||||
prefs => this.contextHandler.setupPrometheus(prefs),
|
||||
{ equals: comparer.structural },
|
||||
),
|
||||
() => clearInterval(refreshTimer),
|
||||
() => clearInterval(refreshMetadataTimer),
|
||||
reaction(() => this.defaultNamespace, () => this.recreateProxyKubeconfig()),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
protected async recreateProxyKubeconfig() {
|
||||
logger.info("[CLUSTER]: Recreating proxy kubeconfig");
|
||||
|
||||
try {
|
||||
await this.proxyKubeconfigManager.clear();
|
||||
await this.getProxyKubeconfig();
|
||||
} catch (error) {
|
||||
logger.error(`[CLUSTER]: failed to recreate proxy kubeconfig`, error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param force force activation
|
||||
* @internal
|
||||
*/
|
||||
@action
|
||||
async activate(force = false) {
|
||||
if (this.activated && !force) {
|
||||
return this.pushState();
|
||||
}
|
||||
|
||||
logger.info(`[CLUSTER]: activate`, this.getMeta());
|
||||
|
||||
if (!this.eventsDisposer.length) {
|
||||
this.bindEvents();
|
||||
}
|
||||
|
||||
if (this.disconnected || !this.accessible) {
|
||||
await this.reconnect();
|
||||
}
|
||||
|
||||
this.broadcastConnectUpdate("Refreshing connection status ...");
|
||||
await this.refreshConnectionStatus();
|
||||
|
||||
if (this.accessible) {
|
||||
this.broadcastConnectUpdate("Refreshing cluster accessibility ...");
|
||||
await this.refreshAccessibility();
|
||||
// download kubectl in background, so it's not blocking dashboard
|
||||
this.ensureKubectl()
|
||||
.catch(error => logger.warn(`[CLUSTER]: failed to download kubectl for clusterId=${this.id}`, error));
|
||||
this.broadcastConnectUpdate("Connected, waiting for view to load ...");
|
||||
}
|
||||
|
||||
this.activated = true;
|
||||
this.pushState();
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
async ensureKubectl() {
|
||||
this.kubeCtl ??= this.dependencies.createKubectl(this.version);
|
||||
|
||||
await this.kubeCtl.ensureKubectl();
|
||||
|
||||
return this.kubeCtl;
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
@action
|
||||
async reconnect() {
|
||||
logger.info(`[CLUSTER]: reconnect`, this.getMeta());
|
||||
this.contextHandler?.stopServer();
|
||||
await this.contextHandler?.ensureServer();
|
||||
this.disconnected = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
@action disconnect() {
|
||||
logger.info(`[CLUSTER]: disconnecting`, { id: this.id });
|
||||
this.eventsDisposer();
|
||||
this.contextHandler?.stopServer();
|
||||
this.disconnected = true;
|
||||
this.online = false;
|
||||
this.accessible = false;
|
||||
this.ready = false;
|
||||
this.activated = false;
|
||||
this.allowedNamespaces = [];
|
||||
this.resourceAccessStatuses.clear();
|
||||
this.pushState();
|
||||
logger.info(`[CLUSTER]: disconnected`, { id: this.id });
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
* @param opts refresh options
|
||||
*/
|
||||
@action
|
||||
async refresh(opts: ClusterRefreshOptions = {}) {
|
||||
logger.info(`[CLUSTER]: refresh`, this.getMeta());
|
||||
await this.refreshConnectionStatus();
|
||||
|
||||
if (this.accessible) {
|
||||
await this.refreshAccessibility();
|
||||
|
||||
if (opts.refreshMetadata) {
|
||||
this.refreshMetadata();
|
||||
}
|
||||
}
|
||||
this.pushState();
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
@action
|
||||
async refreshMetadata() {
|
||||
logger.info(`[CLUSTER]: refreshMetadata`, this.getMeta());
|
||||
const metadata = await DetectorRegistry.getInstance().detectForCluster(this);
|
||||
const existingMetadata = this.metadata;
|
||||
|
||||
this.metadata = Object.assign(existingMetadata, metadata);
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
private async refreshAccessibility(): Promise<void> {
|
||||
this.isAdmin = await this.isClusterAdmin();
|
||||
this.isGlobalWatchEnabled = await this.canUseWatchApi({ resource: "*" });
|
||||
this.allowedNamespaces = await this.getAllowedNamespaces();
|
||||
this.allowedResources = await this.getAllowedResources();
|
||||
this.ready = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
@action
|
||||
async refreshConnectionStatus() {
|
||||
const connectionStatus = await this.getConnectionStatus();
|
||||
|
||||
this.online = connectionStatus > ClusterStatus.Offline;
|
||||
this.accessible = connectionStatus == ClusterStatus.AccessGranted;
|
||||
}
|
||||
|
||||
async getKubeconfig(): Promise<KubeConfig> {
|
||||
const { config } = await loadConfigFromFile(this.kubeConfigPath);
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
async getProxyKubeconfig(): Promise<KubeConfig> {
|
||||
const proxyKCPath = await this.getProxyKubeconfigPath();
|
||||
const { config } = await loadConfigFromFile(proxyKCPath);
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
async getProxyKubeconfigPath(): Promise<string> {
|
||||
return this.proxyKubeconfigManager.getPath();
|
||||
}
|
||||
|
||||
protected async getConnectionStatus(): Promise<ClusterStatus> {
|
||||
try {
|
||||
const versionDetector = new VersionDetector(this);
|
||||
const versionData = await versionDetector.detect();
|
||||
|
||||
this.metadata.version = versionData.value;
|
||||
|
||||
return ClusterStatus.AccessGranted;
|
||||
} catch (error) {
|
||||
logger.error(`[CLUSTER]: Failed to connect to "${this.contextName}": ${error}`);
|
||||
|
||||
if (error.statusCode) {
|
||||
if (error.statusCode >= 400 && error.statusCode < 500) {
|
||||
this.broadcastConnectUpdate("Invalid credentials", true);
|
||||
|
||||
return ClusterStatus.AccessDenied;
|
||||
}
|
||||
|
||||
this.broadcastConnectUpdate(error.error || error.message, true);
|
||||
|
||||
return ClusterStatus.Offline;
|
||||
}
|
||||
|
||||
if (error.failed === true) {
|
||||
if (error.timedOut === true) {
|
||||
this.broadcastConnectUpdate("Connection timed out", true);
|
||||
|
||||
return ClusterStatus.Offline;
|
||||
}
|
||||
|
||||
this.broadcastConnectUpdate("Failed to fetch credentials", true);
|
||||
|
||||
return ClusterStatus.AccessDenied;
|
||||
}
|
||||
|
||||
this.broadcastConnectUpdate(error.message, true);
|
||||
|
||||
return ClusterStatus.Offline;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
* @param resourceAttributes resource attributes
|
||||
*/
|
||||
async canI(resourceAttributes: V1ResourceAttributes): Promise<boolean> {
|
||||
const authApi = (await this.getProxyKubeconfig()).makeApiClient(AuthorizationV1Api);
|
||||
|
||||
try {
|
||||
const accessReview = await authApi.createSelfSubjectAccessReview({
|
||||
apiVersion: "authorization.k8s.io/v1",
|
||||
kind: "SelfSubjectAccessReview",
|
||||
spec: { resourceAttributes },
|
||||
});
|
||||
|
||||
return accessReview.body.status.allowed;
|
||||
} catch (error) {
|
||||
logger.error(`failed to request selfSubjectAccessReview: ${error}`);
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
async isClusterAdmin(): Promise<boolean> {
|
||||
return this.canI({
|
||||
namespace: "kube-system",
|
||||
resource: "*",
|
||||
verb: "create",
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
async canUseWatchApi(customizeResource: V1ResourceAttributes = {}): Promise<boolean> {
|
||||
return this.canI({
|
||||
verb: "watch",
|
||||
resource: "*",
|
||||
...customizeResource,
|
||||
});
|
||||
}
|
||||
|
||||
toJSON(): ClusterModel {
|
||||
return toJS({
|
||||
id: this.id,
|
||||
contextName: this.contextName,
|
||||
kubeConfigPath: this.kubeConfigPath,
|
||||
workspace: this.workspace,
|
||||
workspaces: this.workspaces,
|
||||
preferences: this.preferences,
|
||||
metadata: this.metadata,
|
||||
accessibleNamespaces: this.accessibleNamespaces,
|
||||
labels: this.labels,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Serializable cluster-state used for sync btw main <-> renderer
|
||||
*/
|
||||
getState(): ClusterState {
|
||||
return toJS({
|
||||
apiUrl: this.apiUrl,
|
||||
online: this.online,
|
||||
ready: this.ready,
|
||||
disconnected: this.disconnected,
|
||||
accessible: this.accessible,
|
||||
isAdmin: this.isAdmin,
|
||||
allowedNamespaces: this.allowedNamespaces,
|
||||
allowedResources: this.allowedResources,
|
||||
isGlobalWatchEnabled: this.isGlobalWatchEnabled,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
* @param state cluster state
|
||||
*/
|
||||
@action setState(state: ClusterState) {
|
||||
Object.assign(this, state);
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
* @param state cluster state
|
||||
*/
|
||||
pushState(state = this.getState()) {
|
||||
logger.silly(`[CLUSTER]: push-state`, state);
|
||||
broadcastMessage("cluster:state", this.id, state);
|
||||
}
|
||||
|
||||
// get cluster system meta, e.g. use in "logger"
|
||||
getMeta() {
|
||||
return {
|
||||
id: this.id,
|
||||
name: this.contextName,
|
||||
ready: this.ready,
|
||||
online: this.online,
|
||||
accessible: this.accessible,
|
||||
disconnected: this.disconnected,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* broadcast an authentication update concerning this cluster
|
||||
* @internal
|
||||
*/
|
||||
broadcastConnectUpdate(message: string, isError = false): void {
|
||||
const update: KubeAuthUpdate = { message, isError };
|
||||
|
||||
logger.debug(`[CLUSTER]: broadcasting connection update`, { ...update, meta: this.getMeta() });
|
||||
broadcastMessage(`cluster:${this.id}:connection-update`, update);
|
||||
}
|
||||
|
||||
protected async getAllowedNamespaces() {
|
||||
if (this.accessibleNamespaces.length) {
|
||||
return this.accessibleNamespaces;
|
||||
}
|
||||
|
||||
const api = (await this.getProxyKubeconfig()).makeApiClient(CoreV1Api);
|
||||
|
||||
try {
|
||||
const { body: { items }} = await api.listNamespace();
|
||||
const namespaces = items.map(ns => ns.metadata.name);
|
||||
|
||||
return namespaces;
|
||||
} catch (error) {
|
||||
const ctx = (await this.getProxyKubeconfig()).getContextObject(this.contextName);
|
||||
const namespaceList = [ctx.namespace].filter(Boolean);
|
||||
|
||||
if (namespaceList.length === 0 && error instanceof HttpError && error.statusCode === 403) {
|
||||
const { response } = error as HttpError & { response: Response };
|
||||
|
||||
logger.info("[CLUSTER]: listing namespaces is forbidden, broadcasting", { clusterId: this.id, error: response.body });
|
||||
broadcastMessage(ClusterListNamespaceForbiddenChannel, this.id);
|
||||
}
|
||||
|
||||
return namespaceList;
|
||||
}
|
||||
}
|
||||
|
||||
protected async getAllowedResources() {
|
||||
try {
|
||||
if (!this.allowedNamespaces.length) {
|
||||
return [];
|
||||
}
|
||||
const resources = apiResources.filter((resource) => this.resourceAccessStatuses.get(resource) === undefined);
|
||||
const apiLimit = plimit(5); // 5 concurrent api requests
|
||||
const requests = [];
|
||||
|
||||
for (const apiResource of resources) {
|
||||
requests.push(apiLimit(async () => {
|
||||
for (const namespace of this.allowedNamespaces.slice(0, 10)) {
|
||||
if (!this.resourceAccessStatuses.get(apiResource)) {
|
||||
const result = await this.canI({
|
||||
resource: apiResource.apiName,
|
||||
group: apiResource.group,
|
||||
verb: "list",
|
||||
namespace,
|
||||
});
|
||||
|
||||
this.resourceAccessStatuses.set(apiResource, result);
|
||||
}
|
||||
}
|
||||
}));
|
||||
}
|
||||
await Promise.all(requests);
|
||||
|
||||
return apiResources
|
||||
.filter((resource) => this.resourceAccessStatuses.get(resource))
|
||||
.map(apiResource => apiResource.apiName);
|
||||
} catch (error) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
isAllowedResource(kind: string): boolean {
|
||||
if ((kind as KubeResource) in apiResourceRecord) {
|
||||
return this.allowedResources.includes(kind);
|
||||
}
|
||||
|
||||
const apiResource = apiResources.find(resource => resource.kind === kind);
|
||||
|
||||
if (apiResource) {
|
||||
return this.allowedResources.includes(apiResource.apiName);
|
||||
}
|
||||
|
||||
return true; // allowed by default for other resources
|
||||
}
|
||||
|
||||
isMetricHidden(resource: ClusterMetricsResourceType): boolean {
|
||||
return Boolean(this.preferences.hiddenMetrics?.includes(resource));
|
||||
}
|
||||
|
||||
get nodeShellImage(): string {
|
||||
return this.preferences?.nodeShellImage || initialNodeShellImage;
|
||||
}
|
||||
|
||||
get imagePullSecret(): string | undefined {
|
||||
return this.preferences?.imagePullSecret;
|
||||
}
|
||||
|
||||
isInLocalKubeconfig() {
|
||||
return this.kubeConfigPath.startsWith(this.dependencies.directoryForKubeConfigs);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* Copyright (c) 2021 OpenLens Authors
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
import { getInjectionToken } from "@ogre-tools/injectable";
|
||||
import type { ClusterModel } from "../cluster-types";
|
||||
import type { Cluster } from "./cluster";
|
||||
|
||||
export const createClusterInjectionToken =
|
||||
getInjectionToken<(model: ClusterModel) => Cluster>();
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* Copyright (c) 2021 OpenLens Authors
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
import { getInjectable, lifecycleEnum } from "@ogre-tools/injectable";
|
||||
import path from "path";
|
||||
import directoryForUserDataInjectable from "../app-paths/directory-for-user-data/directory-for-user-data.injectable";
|
||||
|
||||
const directoryForLensLocalStorageInjectable = getInjectable({
|
||||
instantiate: (di) =>
|
||||
path.resolve(
|
||||
di.inject(directoryForUserDataInjectable),
|
||||
"lens-local-storage",
|
||||
),
|
||||
|
||||
lifecycle: lifecycleEnum.singleton,
|
||||
});
|
||||
|
||||
export default directoryForLensLocalStorageInjectable;
|
||||
@@ -45,7 +45,7 @@ export class EventEmitter<D extends [...any[]]> {
|
||||
this.listeners.length = 0;
|
||||
}
|
||||
|
||||
emit(...data: D) {
|
||||
emit = (...data: D) => {
|
||||
for (const [callback, { once }] of this.listeners) {
|
||||
if (once) {
|
||||
this.removeListener(callback);
|
||||
@@ -55,5 +55,5 @@ export class EventEmitter<D extends [...any[]]> {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* Copyright (c) 2021 OpenLens Authors
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
import { getInjectable, lifecycleEnum } from "@ogre-tools/injectable";
|
||||
import fse from "fs-extra";
|
||||
|
||||
const fsInjectable = getInjectable({
|
||||
instantiate: () => fse,
|
||||
causesSideEffects: true,
|
||||
lifecycle: lifecycleEnum.singleton,
|
||||
});
|
||||
|
||||
export default fsInjectable;
|
||||
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* Copyright (c) 2021 OpenLens Authors
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
import { readJsonFile } from "./read-json-file";
|
||||
import { getInjectable, lifecycleEnum } from "@ogre-tools/injectable";
|
||||
import fsInjectable from "../fs.injectable";
|
||||
|
||||
const readJsonFileInjectable = getInjectable({
|
||||
instantiate: (di) => readJsonFile({
|
||||
fs: di.inject(fsInjectable),
|
||||
}),
|
||||
|
||||
lifecycle: lifecycleEnum.singleton,
|
||||
});
|
||||
|
||||
export default readJsonFileInjectable;
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* Copyright (c) 2021 OpenLens Authors
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
import type { JsonObject } from "type-fest";
|
||||
|
||||
/**
|
||||
* Copyright (c) 2021 OpenLens Authors
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
interface Dependencies {
|
||||
fs: {
|
||||
readJson: (filePath: string) => Promise<JsonObject>;
|
||||
};
|
||||
}
|
||||
|
||||
export const readJsonFile =
|
||||
({ fs }: Dependencies) =>
|
||||
(filePath: string) =>
|
||||
fs.readJson(filePath);
|
||||
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* Copyright (c) 2021 OpenLens Authors
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
import { getInjectable, lifecycleEnum } from "@ogre-tools/injectable";
|
||||
import { writeJsonFile } from "./write-json-file";
|
||||
import fsInjectable from "../fs.injectable";
|
||||
|
||||
const writeJsonFileInjectable = getInjectable({
|
||||
instantiate: (di) => writeJsonFile({ fs: di.inject(fsInjectable) }),
|
||||
lifecycle: lifecycleEnum.singleton,
|
||||
});
|
||||
|
||||
export default writeJsonFileInjectable;
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* Copyright (c) 2021 OpenLens Authors
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
import path from "path";
|
||||
import type { JsonObject } from "type-fest";
|
||||
|
||||
interface Dependencies {
|
||||
fs: {
|
||||
ensureDir: (
|
||||
directoryName: string,
|
||||
options: { mode: number }
|
||||
) => Promise<void>;
|
||||
|
||||
writeJson: (
|
||||
filePath: string,
|
||||
contentObject: JsonObject,
|
||||
options: { spaces: number }
|
||||
) => Promise<void>;
|
||||
};
|
||||
}
|
||||
|
||||
export const writeJsonFile =
|
||||
({ fs }: Dependencies) =>
|
||||
async (filePath: string, contentObject: JsonObject) => {
|
||||
const directoryName = path.dirname(filePath);
|
||||
|
||||
await fs.ensureDir(directoryName, { mode: 0o755 });
|
||||
|
||||
await fs.writeJson(filePath, contentObject, { spaces: 2 });
|
||||
};
|
||||
Vendored
+24
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* Copyright (c) 2021 OpenLens Authors
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
export interface Channel<TInstance> {
|
||||
name: string;
|
||||
_template: TInstance;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* Copyright (c) 2021 OpenLens Authors
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
import type { Channel } from "../channel";
|
||||
|
||||
export const createChannel = <TInstance>(name: string): Channel<TInstance> => ({
|
||||
name,
|
||||
_template: null,
|
||||
});
|
||||
@@ -19,7 +19,7 @@
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import type { Cluster } from "../../main/cluster";
|
||||
import type { Cluster } from "../cluster/cluster";
|
||||
|
||||
export interface ClusterContext {
|
||||
cluster?: Cluster;
|
||||
|
||||
@@ -23,7 +23,7 @@ import { JsonApi } from "./json-api";
|
||||
import { KubeJsonApi } from "./kube-json-api";
|
||||
import { apiKubePrefix, apiPrefix, isDebugging, isDevelopment } from "../../common/vars";
|
||||
import { isClusterPageContext } from "../utils/cluster-id-url-parsing";
|
||||
import { appEventBus } from "../event-bus";
|
||||
import { appEventBus } from "../app-event-bus/event-bus";
|
||||
|
||||
let apiBase: JsonApi;
|
||||
let apiKube: KubeJsonApi;
|
||||
|
||||
@@ -30,7 +30,7 @@ import { apiBase, apiKube } from "./index";
|
||||
import { createKubeApiURL, parseKubeApi } from "./kube-api-parse";
|
||||
import { KubeObjectConstructor, KubeObject, KubeStatus } from "./kube-object";
|
||||
import byline from "byline";
|
||||
import type { IKubeWatchEvent } from "./kube-watch-api";
|
||||
import type { IKubeWatchEvent } from "./kube-watch-event";
|
||||
import { KubeJsonApi, KubeJsonApiData } from "./kube-json-api";
|
||||
import { noop } from "../utils";
|
||||
import type { RequestInit } from "node-fetch";
|
||||
|
||||
@@ -24,7 +24,7 @@ import type { ClusterContext } from "./cluster-context";
|
||||
import { action, computed, makeObservable, observable, reaction, when } from "mobx";
|
||||
import { autoBind, noop, rejectPromiseBy } from "../utils";
|
||||
import { KubeObject, KubeStatus } from "./kube-object";
|
||||
import type { IKubeWatchEvent } from "./kube-watch-api";
|
||||
import type { IKubeWatchEvent } from "./kube-watch-event";
|
||||
import { ItemStore } from "../item.store";
|
||||
import { ensureObjectSelfLink, IKubeApiQueryParams, KubeApi } from "./kube-api";
|
||||
import { parseKubeApi } from "./kube-api-parse";
|
||||
@@ -323,14 +323,14 @@ export abstract class KubeObjectStore<T extends KubeObject> extends ItemStore<T>
|
||||
return this.api.create(params, data);
|
||||
}
|
||||
|
||||
async create(params: { name: string; namespace?: string }, data?: Partial<T>): Promise<T> {
|
||||
create = async (params: { name: string; namespace?: string }, data?: Partial<T>): Promise<T> => {
|
||||
const newItem = await this.createItem(params, data);
|
||||
const items = this.sortItems([...this.items, newItem]);
|
||||
|
||||
this.items.replace(items);
|
||||
|
||||
return newItem;
|
||||
}
|
||||
};
|
||||
|
||||
private postUpdate(rawItem: KubeJsonApiData): T {
|
||||
const newItem = new this.api.objectConstructor(rawItem);
|
||||
|
||||
@@ -1,210 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) 2021 OpenLens Authors
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
// Kubernetes watch-api client
|
||||
// API: https://developer.mozilla.org/en-US/docs/Web/API/Streams_API/Using_readable_streams
|
||||
|
||||
import type { KubeObjectStore } from "./kube-object.store";
|
||||
import type { ClusterContext } from "./cluster-context";
|
||||
|
||||
import { comparer, reaction } from "mobx";
|
||||
import { disposer, Disposer, noop } from "../utils";
|
||||
import type { KubeJsonApiData } from "./kube-json-api";
|
||||
import type { KubeObject } from "./kube-object";
|
||||
import AbortController from "abort-controller";
|
||||
import { once } from "lodash";
|
||||
import logger from "../logger";
|
||||
|
||||
class WrappedAbortController extends AbortController {
|
||||
constructor(protected parent: AbortController) {
|
||||
super();
|
||||
|
||||
parent.signal.addEventListener("abort", () => {
|
||||
this.abort();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export interface IKubeWatchEvent<T extends KubeJsonApiData> {
|
||||
type: "ADDED" | "MODIFIED" | "DELETED" | "ERROR";
|
||||
object?: T;
|
||||
}
|
||||
|
||||
export interface KubeWatchSubscribeStoreOptions {
|
||||
/**
|
||||
* The namespaces to watch
|
||||
* @default all selected namespaces
|
||||
*/
|
||||
namespaces?: string[];
|
||||
|
||||
/**
|
||||
* A function that is called when listing fails. If set then blocks errors
|
||||
* being rejected with
|
||||
*/
|
||||
onLoadFailure?: (err: any) => void;
|
||||
}
|
||||
|
||||
export interface IKubeWatchLog {
|
||||
message: string | string[] | Error;
|
||||
meta?: object;
|
||||
cssStyle?: string;
|
||||
}
|
||||
|
||||
interface SubscribeStoreParams {
|
||||
store: KubeObjectStore<KubeObject>;
|
||||
parent: AbortController;
|
||||
watchChanges: boolean;
|
||||
namespaces: string[];
|
||||
onLoadFailure?: (err: any) => void;
|
||||
}
|
||||
|
||||
class WatchCount {
|
||||
#data = new Map<KubeObjectStore<KubeObject>, number>();
|
||||
|
||||
public inc(store: KubeObjectStore<KubeObject>): number {
|
||||
if (!this.#data.has(store)) {
|
||||
this.#data.set(store, 0);
|
||||
}
|
||||
|
||||
const newCount = this.#data.get(store) + 1;
|
||||
|
||||
logger.info(`[KUBE-WATCH-API]: inc() count for ${store.api.objectConstructor.apiBase} is now ${newCount}`);
|
||||
this.#data.set(store, newCount);
|
||||
|
||||
return newCount;
|
||||
}
|
||||
|
||||
public dec(store: KubeObjectStore<KubeObject>): number {
|
||||
if (!this.#data.has(store)) {
|
||||
throw new Error(`Cannot dec count for store that has never been inc: ${store.api.objectConstructor.kind}`);
|
||||
}
|
||||
|
||||
const newCount = this.#data.get(store) - 1;
|
||||
|
||||
if (newCount < 0) {
|
||||
throw new Error(`Cannot dec count more times than it has been inc: ${store.api.objectConstructor.kind}`);
|
||||
}
|
||||
|
||||
logger.debug(`[KUBE-WATCH-API]: dec() count for ${store.api.objectConstructor.apiBase} is now ${newCount}`);
|
||||
this.#data.set(store, newCount);
|
||||
|
||||
return newCount;
|
||||
}
|
||||
}
|
||||
|
||||
export class KubeWatchApi {
|
||||
static context: ClusterContext = null;
|
||||
|
||||
#watch = new WatchCount();
|
||||
|
||||
private subscribeStore({ store, parent, watchChanges, namespaces, onLoadFailure }: SubscribeStoreParams): Disposer {
|
||||
if (this.#watch.inc(store) > 1) {
|
||||
// don't load or subscribe to a store more than once
|
||||
return () => this.#watch.dec(store);
|
||||
}
|
||||
|
||||
let childController = new WrappedAbortController(parent);
|
||||
const unsubscribe = disposer();
|
||||
|
||||
const loadThenSubscribe = async (namespaces: string[]) => {
|
||||
try {
|
||||
await store.loadAll({ namespaces, reqInit: { signal: childController.signal }, onLoadFailure });
|
||||
unsubscribe.push(store.subscribe({ onLoadFailure, abortController: childController }));
|
||||
} catch (error) {
|
||||
if (!(error instanceof DOMException)) {
|
||||
this.log(Object.assign(new Error("Loading stores has failed"), { cause: error }), {
|
||||
meta: { store, namespaces },
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* We don't want to wait because we want to start reacting to namespace
|
||||
* selection changes ASAP
|
||||
*/
|
||||
loadThenSubscribe(namespaces).catch(noop);
|
||||
|
||||
const cancelReloading = watchChanges
|
||||
? reaction(
|
||||
// Note: must slice because reaction won't fire if it isn't there
|
||||
() => [KubeWatchApi.context.contextNamespaces.slice(), KubeWatchApi.context.hasSelectedAll] as const,
|
||||
([namespaces, curSelectedAll], [prevNamespaces, prevSelectedAll]) => {
|
||||
if (curSelectedAll && prevSelectedAll) {
|
||||
const action = namespaces.length > prevNamespaces.length ? "created" : "deleted";
|
||||
|
||||
return console.debug(`[KUBE-WATCH-API]: Not changing watch for ${store.api.apiBase} because a new namespace was ${action} but all namespaces are selected`);
|
||||
}
|
||||
|
||||
console.log(`[KUBE-WATCH-API]: changing watch ${store.api.apiBase}`, namespaces);
|
||||
childController.abort();
|
||||
unsubscribe();
|
||||
childController = new WrappedAbortController(parent);
|
||||
loadThenSubscribe(namespaces).catch(noop);
|
||||
},
|
||||
{
|
||||
equals: comparer.shallow,
|
||||
},
|
||||
)
|
||||
: noop; // don't watch namespaces if namespaces were provided
|
||||
|
||||
return () => {
|
||||
if (this.#watch.dec(store) === 0) {
|
||||
// only stop the subcribe if this is the last one
|
||||
cancelReloading();
|
||||
childController.abort();
|
||||
unsubscribe();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
subscribeStores(stores: KubeObjectStore<KubeObject>[], { namespaces, onLoadFailure }: KubeWatchSubscribeStoreOptions = {}): Disposer {
|
||||
const parent = new AbortController();
|
||||
const unsubscribe = disposer(
|
||||
...stores.map(store => this.subscribeStore({
|
||||
store,
|
||||
parent,
|
||||
watchChanges: !namespaces && store.api.isNamespaced,
|
||||
namespaces: namespaces ?? KubeWatchApi.context?.contextNamespaces ?? [],
|
||||
onLoadFailure,
|
||||
})),
|
||||
);
|
||||
|
||||
// unsubscribe
|
||||
return once(() => {
|
||||
parent.abort();
|
||||
unsubscribe();
|
||||
});
|
||||
}
|
||||
|
||||
protected log(message: any, meta: any) {
|
||||
const log = message instanceof Error
|
||||
? console.error
|
||||
: console.debug;
|
||||
|
||||
log("[KUBE-WATCH-API]:", message, {
|
||||
time: new Date().toLocaleString(),
|
||||
...meta,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export const kubeWatchApi = new KubeWatchApi();
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* Copyright (c) 2021 OpenLens Authors
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import type { KubeJsonApiData } from "./kube-json-api";
|
||||
|
||||
export interface IKubeWatchEvent<T extends KubeJsonApiData> {
|
||||
type: "ADDED" | "MODIFIED" | "DELETED" | "ERROR";
|
||||
object?: T;
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ import logger from "../../main/logger";
|
||||
import { app } from "electron";
|
||||
import { requestMain } from "../ipc";
|
||||
import { clusterKubectlApplyAllHandler, clusterKubectlDeleteAllHandler } from "../cluster-ipc";
|
||||
import { ClusterStore } from "../cluster-store";
|
||||
import { ClusterStore } from "../cluster-store/cluster-store";
|
||||
import yaml from "js-yaml";
|
||||
import { productName } from "../vars";
|
||||
|
||||
|
||||
@@ -1,178 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) 2021 OpenLens Authors
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { action, computed, observable, reaction, makeObservable } from "mobx";
|
||||
import { dockStore } from "../renderer/components/dock/dock.store";
|
||||
import { boundMethod } from "../renderer/utils";
|
||||
|
||||
export class SearchStore {
|
||||
/**
|
||||
* An utility methods escaping user string to safely pass it into new Regex(variable)
|
||||
* @param value Unescaped string
|
||||
*/
|
||||
public static escapeRegex(value?: string): string {
|
||||
return value ? value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&") : "";
|
||||
}
|
||||
|
||||
/**
|
||||
* Text in the search input
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
@observable searchQuery = "";
|
||||
|
||||
/**
|
||||
* Array with line numbers, eg [0, 0, 10, 21, 21, 40...]
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
@observable occurrences: number[] = [];
|
||||
|
||||
/**
|
||||
* Index within the occurrences array. Showing where is activeOverlay currently located
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
@observable activeOverlayIndex = -1;
|
||||
|
||||
constructor() {
|
||||
makeObservable(this);
|
||||
reaction(() => dockStore.selectedTabId, () => {
|
||||
searchStore.reset();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets default activeOverlayIndex
|
||||
* @param text An array of any textual data (logs, for example)
|
||||
* @param query Search query from input
|
||||
*/
|
||||
@action
|
||||
public onSearch(text?: string[] | null, query = this.searchQuery): void {
|
||||
this.searchQuery = query;
|
||||
|
||||
if (!query) {
|
||||
return this.reset();
|
||||
}
|
||||
|
||||
this.occurrences = this.findOccurrences(text ?? [], query);
|
||||
|
||||
if (!this.occurrences.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
// If new highlighted keyword in exact same place as previous one, then no changing in active overlay
|
||||
if (this.occurrences[this.activeOverlayIndex] === undefined) {
|
||||
this.activeOverlayIndex = this.getNextOverlay(true);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Does searching within text array, create a list of search keyword occurrences.
|
||||
* Each keyword "occurrence" is saved as index of the line where keyword was found
|
||||
* @param lines An array of any textual data (logs, for example)
|
||||
* @param query Search query from input
|
||||
* @returns Array of line indexes [0, 0, 14, 17, 17, 17, 20...]
|
||||
*/
|
||||
private findOccurrences(lines: string[], query?: string): number[] {
|
||||
const regex = new RegExp(SearchStore.escapeRegex(query), "gi");
|
||||
|
||||
return lines
|
||||
.flatMap((line, index) => Array.from(line.matchAll(regex), () => index));
|
||||
}
|
||||
|
||||
/**
|
||||
* Getting next overlay index within the occurrences array
|
||||
* @param loopOver Allows to jump from last element to first
|
||||
* @returns next overlay index
|
||||
*/
|
||||
private getNextOverlay(loopOver = false): number {
|
||||
const next = this.activeOverlayIndex + 1;
|
||||
|
||||
if (next > this.occurrences.length - 1) {
|
||||
return loopOver ? 0 : this.activeOverlayIndex;
|
||||
}
|
||||
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
* Getting previous overlay index within the occurrences array of occurrences
|
||||
* @param loopOver Allows to jump from first element to last one
|
||||
* @returns previous overlay index
|
||||
*/
|
||||
private getPrevOverlay(loopOver = false): number {
|
||||
const prev = this.activeOverlayIndex - 1;
|
||||
|
||||
if (prev < 0) {
|
||||
return loopOver ? this.occurrences.length - 1 : this.activeOverlayIndex;
|
||||
}
|
||||
|
||||
return prev;
|
||||
}
|
||||
|
||||
@boundMethod
|
||||
public setNextOverlayActive(): void {
|
||||
this.activeOverlayIndex = this.getNextOverlay(true);
|
||||
}
|
||||
|
||||
@boundMethod
|
||||
public setPrevOverlayActive(): void {
|
||||
this.activeOverlayIndex = this.getPrevOverlay(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets line index of where active overlay is located
|
||||
* @returns A line index within the text/logs array
|
||||
*/
|
||||
@computed get activeOverlayLine(): number {
|
||||
return this.occurrences[this.activeOverlayIndex];
|
||||
}
|
||||
|
||||
@computed get activeFind(): number {
|
||||
return this.activeOverlayIndex + 1;
|
||||
}
|
||||
|
||||
@computed get totalFinds(): number {
|
||||
return this.occurrences.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if overlay is active (to highlight it with orange background usually)
|
||||
* @param line Index of the line where overlay is located
|
||||
* @param occurrence Number of the overlay within one line
|
||||
*/
|
||||
@boundMethod
|
||||
public isActiveOverlay(line: number, occurrence: number): boolean {
|
||||
const firstLineIndex = this.occurrences.findIndex(item => item === line);
|
||||
|
||||
return firstLineIndex + occurrence === this.activeOverlayIndex;
|
||||
}
|
||||
|
||||
@action
|
||||
private reset(): void {
|
||||
this.searchQuery = "";
|
||||
this.activeOverlayIndex = -1;
|
||||
this.occurrences = [];
|
||||
}
|
||||
}
|
||||
|
||||
export const searchStore = new SearchStore;
|
||||
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* Copyright (c) 2021 OpenLens Authors
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to
|
||||
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||
* the Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
import { getInjectable, lifecycleEnum } from "@ogre-tools/injectable";
|
||||
import { UserStore } from "./user-store";
|
||||
|
||||
const userStoreInjectable = getInjectable({
|
||||
instantiate: () => UserStore.createInstance(),
|
||||
|
||||
lifecycle: lifecycleEnum.singleton,
|
||||
});
|
||||
|
||||
export default userStoreInjectable;
|
||||
@@ -26,12 +26,10 @@ import { BaseStore } from "../base-store";
|
||||
import migrations, { fileNameMigration } from "../../migrations/user-store";
|
||||
import { getAppVersion } from "../utils/app-version";
|
||||
import { kubeConfigDefaultPath } from "../kube-helpers";
|
||||
import { appEventBus } from "../event-bus";
|
||||
import path from "path";
|
||||
import { appEventBus } from "../app-event-bus/event-bus";
|
||||
import { ObservableToggleSet, toJS } from "../../renderer/utils";
|
||||
import { DESCRIPTORS, EditorConfiguration, ExtensionRegistry, KubeconfigSyncValue, UserPreferencesModel } from "./preferences-helpers";
|
||||
import logger from "../../main/logger";
|
||||
import { AppPaths } from "../app-paths";
|
||||
|
||||
export interface UserStoreModel {
|
||||
lastSeenAppVersion: string;
|
||||
@@ -233,11 +231,3 @@ export class UserStore extends BaseStore<UserStoreModel> /* implements UserStore
|
||||
return toJS(model);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Getting default directory to download kubectl binaries
|
||||
* @returns string
|
||||
*/
|
||||
export function getDefaultKubectlDownloadPath(): string {
|
||||
return path.join(AppPaths.get("userData"), "binaries");
|
||||
}
|
||||
@@ -19,7 +19,7 @@
|
||||
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { ClusterStore } from "../cluster-store";
|
||||
import { ClusterStore } from "../cluster-store/cluster-store";
|
||||
import type { KubeResource } from "../rbac";
|
||||
import { getHostedClusterId } from "./cluster-id-url-parsing";
|
||||
|
||||
|
||||
@@ -43,7 +43,6 @@ export * from "./extended-map";
|
||||
export * from "./formatDuration";
|
||||
export * from "./getRandId";
|
||||
export * from "./hash-set";
|
||||
export * from "./local-kubeconfig";
|
||||
export * from "./n-fircate";
|
||||
export * from "./objects";
|
||||
export * from "./openExternal";
|
||||
|
||||
Reference in new issue
Block a user