mirror of
https://github.com/lensapp/lens.git
synced 2025-05-20 05:10:56 +00:00
Merge branch 'master' into fix/ignore-clusters-with-corrupted-kubeconfig
This commit is contained in:
commit
607ebb599b
383 files changed
+15646
-3180
No files matched your search
@@ -2,7 +2,7 @@ import fs from "fs";
|
||||
import mockFs from "mock-fs";
|
||||
import yaml from "js-yaml";
|
||||
import { Cluster } from "../../main/cluster";
|
||||
import { ClusterStore } from "../cluster-store";
|
||||
import { ClusterStore, getClusterIdFromHost } from "../cluster-store";
|
||||
import { workspaceStore } from "../workspace-store";
|
||||
|
||||
const testDataIcon = fs.readFileSync("test-data/cluster-store-migration-icon.png");
|
||||
@@ -541,3 +541,27 @@ describe("pre 3.6.0-beta.1 config with an existing cluster", () => {
|
||||
expect(icon.startsWith("data:;base64,")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getClusterIdFromHost", () => {
|
||||
const clusterFakeId = "fe540901-0bd6-4f6c-b472-bce1559d7c4a";
|
||||
|
||||
it("should return undefined for non cluster frame hosts", () => {
|
||||
expect(getClusterIdFromHost("localhost:45345")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("should return ClusterId for cluster frame hosts", () => {
|
||||
expect(getClusterIdFromHost(`${clusterFakeId}.localhost:59110`)).toBe(clusterFakeId);
|
||||
});
|
||||
|
||||
it("should return ClusterId for cluster frame hosts with additional subdomains", () => {
|
||||
expect(getClusterIdFromHost(`abc.${clusterFakeId}.localhost:59110`)).toBe(clusterFakeId);
|
||||
expect(getClusterIdFromHost(`abc.def.${clusterFakeId}.localhost:59110`)).toBe(clusterFakeId);
|
||||
expect(getClusterIdFromHost(`abc.def.ghi.${clusterFakeId}.localhost:59110`)).toBe(clusterFakeId);
|
||||
expect(getClusterIdFromHost(`abc.def.ghi.jkl.${clusterFakeId}.localhost:59110`)).toBe(clusterFakeId);
|
||||
expect(getClusterIdFromHost(`abc.def.ghi.jkl.mno.${clusterFakeId}.localhost:59110`)).toBe(clusterFakeId);
|
||||
expect(getClusterIdFromHost(`abc.def.ghi.jkl.mno.pqr.${clusterFakeId}.localhost:59110`)).toBe(clusterFakeId);
|
||||
expect(getClusterIdFromHost(`abc.def.ghi.jkl.mno.pqr.stu.${clusterFakeId}.localhost:59110`)).toBe(clusterFakeId);
|
||||
expect(getClusterIdFromHost(`abc.def.ghi.jkl.mno.pqr.stu.vwx.${clusterFakeId}.localhost:59110`)).toBe(clusterFakeId);
|
||||
expect(getClusterIdFromHost(`abc.def.ghi.jkl.mno.pqr.stu.vwx.yz.${clusterFakeId}.localhost:59110`)).toBe(clusterFakeId);
|
||||
});
|
||||
});
|
||||
@@ -77,4 +77,4 @@ describe("search store tests", () => {
|
||||
searchStore.onSearch(logs, "Starting");
|
||||
expect(searchStore.totalFinds).toBe(2);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -101,4 +101,4 @@ describe("user store tests", () => {
|
||||
expect(us.lastSeenAppVersion).toBe("0.0.0");
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -36,6 +36,13 @@ describe("workspace store tests", () => {
|
||||
expect(ws.getById(WorkspaceStore.defaultId)).not.toBe(null);
|
||||
});
|
||||
|
||||
it("default workspace should be enabled", () => {
|
||||
const ws = WorkspaceStore.getInstance<WorkspaceStore>();
|
||||
|
||||
expect(ws.workspaces.size).toBe(1);
|
||||
expect(ws.getById(WorkspaceStore.defaultId).enabled).toBe(true);
|
||||
});
|
||||
|
||||
it("cannot remove the default workspace", () => {
|
||||
const ws = WorkspaceStore.getInstance<WorkspaceStore>();
|
||||
|
||||
|
||||
@@ -354,10 +354,11 @@ export class ClusterStore extends BaseStore<ClusterStoreModel> {
|
||||
|
||||
export const clusterStore = ClusterStore.getInstance<ClusterStore>();
|
||||
|
||||
export function getClusterIdFromHost(hostname: string): ClusterId {
|
||||
const subDomains = hostname.split(":")[0].split(".");
|
||||
export function getClusterIdFromHost(host: string): ClusterId | undefined {
|
||||
// e.g host == "%clusterId.localhost:45345"
|
||||
const subDomains = host.split(":")[0].split(".");
|
||||
|
||||
return subDomains.slice(-2)[0]; // e.g host == "%clusterId.localhost:45345"
|
||||
return subDomains.slice(-2, -1)[0]; // ClusterId or undefined
|
||||
}
|
||||
|
||||
export function getClusterFrameUrl(clusterId: ClusterId) {
|
||||
@@ -365,7 +366,7 @@ export function getClusterFrameUrl(clusterId: ClusterId) {
|
||||
}
|
||||
|
||||
export function getHostedClusterId() {
|
||||
return getClusterIdFromHost(location.hostname);
|
||||
return getClusterIdFromHost(location.host);
|
||||
}
|
||||
|
||||
export function getHostedCluster(): Cluster {
|
||||
|
||||
@@ -10,4 +10,4 @@ export class ExecValidationNotFoundError extends Error {
|
||||
this.name = this.constructor.name;
|
||||
Error.captureStackTrace(this, this.constructor);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
import { EventEmitter } from "events";
|
||||
import { onCorrect, onceCorrect } from "../type-enforced-ipc";
|
||||
|
||||
describe("type enforced ipc tests", () => {
|
||||
describe("onCorrect tests", () => {
|
||||
it("should call the handler if the args are valid", () => {
|
||||
let called = false;
|
||||
const source = new EventEmitter();
|
||||
const listener = () => called = true;
|
||||
const verifier = (args: unknown[]): args is [] => true;
|
||||
const channel = "foobar";
|
||||
|
||||
onCorrect({ source, listener, verifier, channel });
|
||||
|
||||
source.emit(channel);
|
||||
expect(called).toBe(true);
|
||||
});
|
||||
|
||||
it("should not call the handler if the args are not valid", () => {
|
||||
let called = false;
|
||||
const source = new EventEmitter();
|
||||
const listener = () => called = true;
|
||||
const verifier = (args: unknown[]): args is [] => false;
|
||||
const channel = "foobar";
|
||||
|
||||
onCorrect({ source, listener, verifier, channel });
|
||||
|
||||
source.emit(channel);
|
||||
expect(called).toBe(false);
|
||||
});
|
||||
|
||||
it("should call the handler twice if the args are valid on two emits", () => {
|
||||
let called = 0;
|
||||
const source = new EventEmitter();
|
||||
const listener = () => called += 1;
|
||||
const verifier = (args: unknown[]): args is [] => true;
|
||||
const channel = "foobar";
|
||||
|
||||
onCorrect({ source, listener, verifier, channel });
|
||||
|
||||
source.emit(channel);
|
||||
source.emit(channel);
|
||||
expect(called).toBe(2);
|
||||
});
|
||||
|
||||
it("should call the handler twice if the args are [valid, invalid, valid]", () => {
|
||||
let called = 0;
|
||||
const source = new EventEmitter();
|
||||
const listener = () => called += 1;
|
||||
const results = [true, false, true];
|
||||
const verifier = (args: unknown[]): args is [] => results.pop();
|
||||
const channel = "foobar";
|
||||
|
||||
onCorrect({ source, listener, verifier, channel });
|
||||
|
||||
source.emit(channel);
|
||||
source.emit(channel);
|
||||
source.emit(channel);
|
||||
expect(called).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("onceCorrect tests", () => {
|
||||
it("should call the handler if the args are valid", () => {
|
||||
let called = false;
|
||||
const source = new EventEmitter();
|
||||
const listener = () => called = true;
|
||||
const verifier = (args: unknown[]): args is [] => true;
|
||||
const channel = "foobar";
|
||||
|
||||
onceCorrect({ source, listener, verifier, channel });
|
||||
|
||||
source.emit(channel);
|
||||
expect(called).toBe(true);
|
||||
});
|
||||
|
||||
it("should not call the handler if the args are not valid", () => {
|
||||
let called = false;
|
||||
const source = new EventEmitter();
|
||||
const listener = () => called = true;
|
||||
const verifier = (args: unknown[]): args is [] => false;
|
||||
const channel = "foobar";
|
||||
|
||||
onceCorrect({ source, listener, verifier, channel });
|
||||
|
||||
source.emit(channel);
|
||||
expect(called).toBe(false);
|
||||
});
|
||||
|
||||
it("should call the handler only once even if args are valid multiple times", () => {
|
||||
let called = 0;
|
||||
const source = new EventEmitter();
|
||||
const listener = () => called += 1;
|
||||
const verifier = (args: unknown[]): args is [] => true;
|
||||
const channel = "foobar";
|
||||
|
||||
onceCorrect({ source, listener, verifier, channel });
|
||||
|
||||
source.emit(channel);
|
||||
source.emit(channel);
|
||||
expect(called).toBe(1);
|
||||
});
|
||||
|
||||
it("should call the handler on only the first valid set of args", () => {
|
||||
let called = "";
|
||||
let verifierCalled = 0;
|
||||
const source = new EventEmitter();
|
||||
const listener = (info: any, arg: string) => called = arg;
|
||||
const verifier = (args: unknown[]): args is [string] => (++verifierCalled) % 3 === 0;
|
||||
const channel = "foobar";
|
||||
|
||||
onceCorrect({ source, listener, verifier, channel });
|
||||
|
||||
source.emit(channel, {}, "a");
|
||||
source.emit(channel, {}, "b");
|
||||
source.emit(channel, {}, "c");
|
||||
source.emit(channel, {}, "d");
|
||||
source.emit(channel, {}, "e");
|
||||
source.emit(channel, {}, "f");
|
||||
source.emit(channel, {}, "g");
|
||||
source.emit(channel, {}, "h");
|
||||
source.emit(channel, {}, "i");
|
||||
expect(called).toBe("c");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,3 @@
|
||||
export * from "./ipc";
|
||||
export * from "./update-available";
|
||||
export * from "./type-enforced-ipc";
|
||||
@@ -3,10 +3,13 @@
|
||||
// https://www.electronjs.org/docs/api/ipc-renderer
|
||||
|
||||
import { ipcMain, ipcRenderer, webContents, remote } from "electron";
|
||||
import logger from "../main/logger";
|
||||
import { ClusterFrameInfo, clusterFrameMap } from "./cluster-frames";
|
||||
import { toJS } from "mobx";
|
||||
import logger from "../../main/logger";
|
||||
import { ClusterFrameInfo, clusterFrameMap } from "../cluster-frames";
|
||||
|
||||
export function handleRequest(channel: string, listener: (...args: any[]) => any) {
|
||||
const subFramesChannel = "ipc:get-sub-frames";
|
||||
|
||||
export function handleRequest(channel: string, listener: (event: Electron.IpcMainInvokeEvent, ...args: any[]) => any) {
|
||||
ipcMain.handle(channel, listener);
|
||||
}
|
||||
|
||||
@@ -14,38 +17,39 @@ export async function requestMain(channel: string, ...args: any[]) {
|
||||
return ipcRenderer.invoke(channel, ...args);
|
||||
}
|
||||
|
||||
async function getSubFrames(): Promise<ClusterFrameInfo[]> {
|
||||
const subFrames: ClusterFrameInfo[] = [];
|
||||
|
||||
clusterFrameMap.forEach(frameInfo => {
|
||||
subFrames.push(frameInfo);
|
||||
});
|
||||
|
||||
return subFrames;
|
||||
function getSubFrames(): ClusterFrameInfo[] {
|
||||
return toJS(Array.from(clusterFrameMap.values()), { recurseEverything: true });
|
||||
}
|
||||
|
||||
export function broadcastMessage(channel: string, ...args: any[]) {
|
||||
export async function broadcastMessage(channel: string, ...args: any[]) {
|
||||
const views = (webContents || remote?.webContents)?.getAllWebContents();
|
||||
|
||||
if (!views) return;
|
||||
|
||||
views.forEach(webContent => {
|
||||
const type = webContent.getType();
|
||||
|
||||
logger.silly(`[IPC]: broadcasting "${channel}" to ${type}=${webContent.id}`, { args });
|
||||
webContent.send(channel, ...args);
|
||||
getSubFrames().then((frames) => {
|
||||
frames.map((frameInfo) => {
|
||||
webContent.sendToFrame([frameInfo.processId, frameInfo.frameId], channel, ...args);
|
||||
});
|
||||
}).catch((e) => e);
|
||||
});
|
||||
|
||||
if (ipcRenderer) {
|
||||
ipcRenderer.send(channel, ...args);
|
||||
} else {
|
||||
ipcMain.emit(channel, ...args);
|
||||
}
|
||||
|
||||
for (const view of views) {
|
||||
const type = view.getType();
|
||||
|
||||
logger.silly(`[IPC]: broadcasting "${channel}" to ${type}=${view.id}`, { args });
|
||||
view.send(channel, ...args);
|
||||
|
||||
try {
|
||||
const subFrames: ClusterFrameInfo[] = ipcRenderer
|
||||
? await requestMain(subFramesChannel)
|
||||
: getSubFrames();
|
||||
|
||||
for (const frameInfo of subFrames) {
|
||||
view.sendToFrame([frameInfo.processId, frameInfo.frameId], channel, ...args);
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error("[IPC]: failed to send IPC message", { error });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function subscribeToBroadcast(channel: string, listener: (...args: any[]) => any) {
|
||||
@@ -73,3 +77,9 @@ export function unsubscribeAllFromBroadcast(channel: string) {
|
||||
ipcMain.removeAllListeners(channel);
|
||||
}
|
||||
}
|
||||
|
||||
export function bindBroadcastHandlers() {
|
||||
handleRequest(subFramesChannel, () => {
|
||||
return getSubFrames();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { EventEmitter } from "events";
|
||||
import logger from "../../main/logger";
|
||||
|
||||
export type HandlerEvent<EM extends EventEmitter> = Parameters<Parameters<EM["on"]>[1]>[0];
|
||||
export type ListVerifier<T extends any[]> = (args: unknown[]) => args is T;
|
||||
export type Rest<T> = T extends [any, ...infer R] ? R : [];
|
||||
|
||||
/**
|
||||
* Adds a listener to `source` that waits for the first IPC message with the correct
|
||||
* argument data is sent.
|
||||
* @param channel The channel to be listened on
|
||||
* @param listener The function for the channel to be called if the args of the correct type
|
||||
* @param verifier The function to be called to verify that the args are the correct type
|
||||
*/
|
||||
export function onceCorrect<
|
||||
EM extends EventEmitter,
|
||||
L extends (event: HandlerEvent<EM>, ...args: any[]) => any
|
||||
>({
|
||||
source,
|
||||
channel,
|
||||
listener,
|
||||
verifier,
|
||||
}: {
|
||||
source: EM,
|
||||
channel: string | symbol,
|
||||
listener: L,
|
||||
verifier: ListVerifier<Rest<Parameters<L>>>,
|
||||
}): void {
|
||||
function handler(event: HandlerEvent<EM>, ...args: unknown[]): void {
|
||||
if (verifier(args)) {
|
||||
source.removeListener(channel, handler); // remove immediately
|
||||
|
||||
(async () => (listener(event, ...args)))() // might return a promise, or throw, or reject
|
||||
.catch((error: any) => logger.error("[IPC]: channel once handler threw error", { channel, error }));
|
||||
} else {
|
||||
logger.error("[IPC]: channel was emitted with invalid data", { channel, args });
|
||||
}
|
||||
}
|
||||
|
||||
source.on(channel, handler);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a listener to `source` that checks to verify the arguments before calling the handler.
|
||||
* @param channel The channel to be listened on
|
||||
* @param listener The function for the channel to be called if the args of the correct type
|
||||
* @param verifier The function to be called to verify that the args are the correct type
|
||||
*/
|
||||
export function onCorrect<
|
||||
EM extends EventEmitter,
|
||||
L extends (event: HandlerEvent<EM>, ...args: any[]) => any
|
||||
>({
|
||||
source,
|
||||
channel,
|
||||
listener,
|
||||
verifier,
|
||||
}: {
|
||||
source: EM,
|
||||
channel: string | symbol,
|
||||
listener: L,
|
||||
verifier: ListVerifier<Rest<Parameters<L>>>,
|
||||
}): void {
|
||||
source.on(channel, (event, ...args: unknown[]) => {
|
||||
if (verifier(args)) {
|
||||
(async () => (listener(event, ...args)))() // might return a promise, or throw, or reject
|
||||
.catch(error => logger.error("[IPC]: channel on handler threw error", { channel, error }));
|
||||
} else {
|
||||
logger.error("[IPC]: channel was emitted with invalid data", { channel, args });
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { UpdateInfo } from "electron-updater";
|
||||
|
||||
export const UpdateAvailableChannel = "update-available";
|
||||
export const AutoUpdateLogPrefix = "[UPDATE-CHECKER]";
|
||||
|
||||
/**
|
||||
* [<back-channel>, <update-info>]
|
||||
*/
|
||||
export type UpdateAvailableFromMain = [string, UpdateInfo];
|
||||
|
||||
export function areArgsUpdateAvailableFromMain(args: unknown[]): args is UpdateAvailableFromMain {
|
||||
if (args.length !== 2) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (typeof args[0] !== "string") {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (typeof args[1] !== "object" || args[1] === null) {
|
||||
// TODO: improve this checking
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
export type BackchannelArg = {
|
||||
doUpdate: false;
|
||||
} | {
|
||||
doUpdate: true;
|
||||
now: boolean;
|
||||
};
|
||||
|
||||
export type UpdateAvailableToBackchannel = [BackchannelArg];
|
||||
|
||||
export function areArgsUpdateAvailableToBackchannel(args: unknown[]): args is UpdateAvailableToBackchannel {
|
||||
if (args.length !== 1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (typeof args[0] !== "object" || args[0] === null) {
|
||||
// TODO: improve this checking
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -10,4 +10,4 @@ import { PrometheusProviderRegistry } from "../main/prometheus/provider-registry
|
||||
PrometheusProviderRegistry.registerProvider(provider.id, provider);
|
||||
});
|
||||
|
||||
export const prometheusProviders = PrometheusProviderRegistry.getProviders();
|
||||
export const prometheusProviders = PrometheusProviderRegistry.getProviders();
|
||||
+28
-26
@@ -1,42 +1,44 @@
|
||||
import { getHostedCluster } from "./cluster-store";
|
||||
|
||||
export type KubeResource =
|
||||
"namespaces" | "nodes" | "events" | "resourcequotas" | "services" |
|
||||
"namespaces" | "nodes" | "events" | "resourcequotas" | "services" | "limitranges" |
|
||||
"secrets" | "configmaps" | "ingresses" | "networkpolicies" | "persistentvolumeclaims" | "persistentvolumes" | "storageclasses" |
|
||||
"pods" | "daemonsets" | "deployments" | "statefulsets" | "replicasets" | "jobs" | "cronjobs" |
|
||||
"endpoints" | "customresourcedefinitions" | "horizontalpodautoscalers" | "podsecuritypolicies" | "poddisruptionbudgets";
|
||||
|
||||
export interface KubeApiResource {
|
||||
resource: KubeResource; // valid resource name
|
||||
kind: string; // resource type (e.g. "Namespace")
|
||||
apiName: KubeResource; // valid api resource name (e.g. "namespaces")
|
||||
group?: string; // api-group
|
||||
}
|
||||
|
||||
// TODO: auto-populate all resources dynamically (see: kubectl api-resources -o=wide -v=7)
|
||||
export const apiResources: KubeApiResource[] = [
|
||||
{ resource: "configmaps" },
|
||||
{ resource: "cronjobs", group: "batch" },
|
||||
{ resource: "customresourcedefinitions", group: "apiextensions.k8s.io" },
|
||||
{ resource: "daemonsets", group: "apps" },
|
||||
{ resource: "deployments", group: "apps" },
|
||||
{ resource: "endpoints" },
|
||||
{ resource: "events" },
|
||||
{ resource: "horizontalpodautoscalers" },
|
||||
{ resource: "ingresses", group: "networking.k8s.io" },
|
||||
{ resource: "jobs", group: "batch" },
|
||||
{ resource: "namespaces" },
|
||||
{ resource: "networkpolicies", group: "networking.k8s.io" },
|
||||
{ resource: "nodes" },
|
||||
{ resource: "persistentvolumes" },
|
||||
{ resource: "persistentvolumeclaims" },
|
||||
{ resource: "pods" },
|
||||
{ resource: "poddisruptionbudgets" },
|
||||
{ resource: "podsecuritypolicies" },
|
||||
{ resource: "resourcequotas" },
|
||||
{ resource: "replicasets", group: "apps" },
|
||||
{ resource: "secrets" },
|
||||
{ resource: "services" },
|
||||
{ resource: "statefulsets", group: "apps" },
|
||||
{ resource: "storageclasses", group: "storage.k8s.io" },
|
||||
{ kind: "ConfigMap", apiName: "configmaps" },
|
||||
{ kind: "CronJob", apiName: "cronjobs", group: "batch" },
|
||||
{ kind: "CustomResourceDefinition", apiName: "customresourcedefinitions", group: "apiextensions.k8s.io" },
|
||||
{ kind: "DaemonSet", apiName: "daemonsets", group: "apps" },
|
||||
{ kind: "Deployment", apiName: "deployments", group: "apps" },
|
||||
{ kind: "Endpoint", apiName: "endpoints" },
|
||||
{ kind: "Event", apiName: "events" },
|
||||
{ kind: "HorizontalPodAutoscaler", apiName: "horizontalpodautoscalers" },
|
||||
{ kind: "Ingress", apiName: "ingresses", group: "networking.k8s.io" },
|
||||
{ kind: "Job", apiName: "jobs", group: "batch" },
|
||||
{ kind: "Namespace", apiName: "namespaces" },
|
||||
{ kind: "LimitRange", apiName: "limitranges" },
|
||||
{ kind: "NetworkPolicy", apiName: "networkpolicies", group: "networking.k8s.io" },
|
||||
{ kind: "Node", apiName: "nodes" },
|
||||
{ kind: "PersistentVolume", apiName: "persistentvolumes" },
|
||||
{ kind: "PersistentVolumeClaim", apiName: "persistentvolumeclaims" },
|
||||
{ kind: "Pod", apiName: "pods" },
|
||||
{ kind: "PodDisruptionBudget", apiName: "poddisruptionbudgets" },
|
||||
{ kind: "PodSecurityPolicy", apiName: "podsecuritypolicies" },
|
||||
{ kind: "ResourceQuota", apiName: "resourcequotas" },
|
||||
{ kind: "ReplicaSet", apiName: "replicasets", group: "apps" },
|
||||
{ kind: "Secret", apiName: "secrets" },
|
||||
{ kind: "Service", apiName: "services" },
|
||||
{ kind: "StatefulSet", apiName: "statefulsets", group: "apps" },
|
||||
{ kind: "StorageClass", apiName: "storageclasses", group: "storage.k8s.io" },
|
||||
];
|
||||
|
||||
export function isAllowedResource(resources: KubeResource | KubeResource[]) {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { action, computed, observable } from "mobx";
|
||||
import { action, computed, observable,reaction } from "mobx";
|
||||
import { dockStore } from "../renderer/components/dock/dock.store";
|
||||
import { autobind } from "../renderer/utils";
|
||||
|
||||
export class SearchStore {
|
||||
@@ -6,6 +7,12 @@ export class SearchStore {
|
||||
@observable occurrences: number[] = []; // Array with line numbers, eg [0, 0, 10, 21, 21, 40...]
|
||||
@observable activeOverlayIndex = -1; // Index withing the occurences array. Showing where is activeOverlay currently located
|
||||
|
||||
constructor() {
|
||||
reaction(() => dockStore.selectedTabId, () => {
|
||||
searchStore.reset();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets default activeOverlayIndex
|
||||
* @param text An array of any textual data (logs, for example)
|
||||
@@ -133,4 +140,4 @@ export class SearchStore {
|
||||
}
|
||||
}
|
||||
|
||||
export const searchStore = new SearchStore;
|
||||
export const searchStore = new SearchStore;
|
||||
@@ -28,6 +28,7 @@ export interface UserPreferences {
|
||||
downloadBinariesPath?: string;
|
||||
kubectlBinariesPath?: string;
|
||||
openAtLogin?: boolean;
|
||||
hiddenTableColumns?: Record<string, string[]>
|
||||
}
|
||||
|
||||
export class UserStore extends BaseStore<UserStoreModel> {
|
||||
@@ -54,6 +55,7 @@ export class UserStore extends BaseStore<UserStoreModel> {
|
||||
downloadMirror: "default",
|
||||
downloadKubectlBinaries: true, // Download kubectl binaries matching cluster version
|
||||
openAtLogin: false,
|
||||
hiddenTableColumns: {},
|
||||
};
|
||||
|
||||
protected async handleOnLoad() {
|
||||
@@ -82,6 +84,15 @@ export class UserStore extends BaseStore<UserStoreModel> {
|
||||
return semver.gt(getAppVersion(), this.lastSeenAppVersion);
|
||||
}
|
||||
|
||||
@action
|
||||
setHiddenTableColumns(tableId: string, names: Set<string> | string[]) {
|
||||
this.preferences.hiddenTableColumns[tableId] = Array.from(names);
|
||||
}
|
||||
|
||||
getHiddenTableColumns(tableId: string): Set<string> {
|
||||
return new Set(this.preferences.hiddenTableColumns[tableId]);
|
||||
}
|
||||
|
||||
@action
|
||||
resetKubeConfigPath() {
|
||||
this.kubeConfigPath = kubeConfigDefaultPath;
|
||||
|
||||
@@ -28,4 +28,4 @@ describe("split array on element tests", () => {
|
||||
test("ten elements, in end array", () => {
|
||||
expect(splitArray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 9)).toStrictEqual([[0, 1, 2, 3, 4, 5, 6, 7, 8], [], true]);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,4 @@
|
||||
import requestPromise from "request-promise-native";
|
||||
import packageInfo from "../../../package.json";
|
||||
|
||||
export function getAppVersion(): string {
|
||||
@@ -11,3 +12,13 @@ export function getBundledKubectlVersion(): string {
|
||||
export function getBundledExtensions(): string[] {
|
||||
return packageInfo.lens?.extensions || [];
|
||||
}
|
||||
|
||||
export async function getAppVersionFromProxyServer(proxyPort: number): Promise<string> {
|
||||
const response = await requestPromise({
|
||||
method: "GET",
|
||||
uri: `http://localhost:${proxyPort}/version`,
|
||||
resolveWithFullResponse: true
|
||||
});
|
||||
|
||||
return JSON.parse(response.body).version;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Return a promise that will be resolved after at least `timeout` ms have
|
||||
* passed
|
||||
* @param timeout The number of milliseconds before resolving
|
||||
*/
|
||||
export function delay(timeout = 1000): Promise<void> {
|
||||
return new Promise(resolve => setTimeout(resolve, timeout));
|
||||
}
|
||||
@@ -7,6 +7,7 @@ export * from "./autobind";
|
||||
export * from "./base64";
|
||||
export * from "./camelCase";
|
||||
export * from "./cloneJson";
|
||||
export * from "./delay";
|
||||
export * from "./debouncePromise";
|
||||
export * from "./defineGlobal";
|
||||
export * from "./getRandId";
|
||||
@@ -17,3 +18,4 @@ export * from "./openExternal";
|
||||
export * from "./downloadFile";
|
||||
export * from "./escapeRegExp";
|
||||
export * from "./tar";
|
||||
export * from "./delay";
|
||||
@@ -26,4 +26,4 @@ class Singleton {
|
||||
}
|
||||
|
||||
export { Singleton };
|
||||
export default Singleton;
|
||||
export default Singleton;
|
||||
@@ -58,14 +58,7 @@ export class Workspace implements WorkspaceModel, WorkspaceState {
|
||||
* @observable
|
||||
*/
|
||||
@observable ownerRef?: string;
|
||||
/**
|
||||
* Is workspace enabled
|
||||
*
|
||||
* Workspaces that don't have ownerRef will be enabled by default. Workspaces with ownerRef need to explicitly enable a workspace.
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
@observable enabled: boolean;
|
||||
|
||||
/**
|
||||
* Last active cluster id
|
||||
*
|
||||
@@ -73,6 +66,9 @@ export class Workspace implements WorkspaceModel, WorkspaceState {
|
||||
*/
|
||||
@observable lastActiveClusterId?: ClusterId;
|
||||
|
||||
|
||||
@observable private _enabled: boolean;
|
||||
|
||||
constructor(data: WorkspaceModel) {
|
||||
Object.assign(this, data);
|
||||
|
||||
@@ -83,6 +79,21 @@ export class Workspace implements WorkspaceModel, WorkspaceState {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Is workspace enabled
|
||||
*
|
||||
* Workspaces that don't have ownerRef will be enabled by default. Workspaces with ownerRef need to explicitly enable a workspace.
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
get enabled(): boolean {
|
||||
return !this.isManaged || this._enabled;
|
||||
}
|
||||
|
||||
set enabled(enabled: boolean) {
|
||||
this._enabled = enabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is workspace managed by an extension
|
||||
*/
|
||||
@@ -134,10 +145,18 @@ export class WorkspaceStore extends BaseStore<WorkspaceStoreModel> {
|
||||
static readonly defaultId: WorkspaceId = "default";
|
||||
private static stateRequestChannel = "workspace:states";
|
||||
|
||||
@observable currentWorkspaceId = WorkspaceStore.defaultId;
|
||||
@observable workspaces = observable.map<WorkspaceId, Workspace>();
|
||||
|
||||
private constructor() {
|
||||
super({
|
||||
configName: "lens-workspace-store",
|
||||
});
|
||||
|
||||
this.workspaces.set(WorkspaceStore.defaultId, new Workspace({
|
||||
id: WorkspaceStore.defaultId,
|
||||
name: "default"
|
||||
}));
|
||||
}
|
||||
|
||||
async load() {
|
||||
@@ -186,15 +205,6 @@ export class WorkspaceStore extends BaseStore<WorkspaceStoreModel> {
|
||||
ipcRenderer.removeAllListeners("workspace:state");
|
||||
}
|
||||
|
||||
@observable currentWorkspaceId = WorkspaceStore.defaultId;
|
||||
|
||||
@observable workspaces = observable.map<WorkspaceId, Workspace>({
|
||||
[WorkspaceStore.defaultId]: new Workspace({
|
||||
id: WorkspaceStore.defaultId,
|
||||
name: "default"
|
||||
})
|
||||
});
|
||||
|
||||
@computed get currentWorkspace(): Workspace {
|
||||
return this.getById(this.currentWorkspaceId);
|
||||
}
|
||||
|
||||
@@ -1 +1 @@
|
||||
export * from "./registrations";
|
||||
export * from "./registrations";
|
||||
@@ -5,4 +5,4 @@ export type { KubeObjectMenuRegistration, KubeObjectMenuComponents } from "../re
|
||||
export type { KubeObjectStatusRegistration } from "../registries/kube-object-status-registry";
|
||||
export type { PageRegistration, RegisteredPage, PageParams, PageComponentProps, PageComponents, PageTarget } from "../registries/page-registry";
|
||||
export type { PageMenuRegistration, ClusterPageMenuRegistration, PageMenuComponents } from "../registries/page-menu-registry";
|
||||
export type { StatusBarRegistration } from "../registries/status-bar-registry";
|
||||
export type { StatusBarRegistration } from "../registries/status-bar-registry";
|
||||
@@ -2,6 +2,7 @@ import type { AppPreferenceRegistration, ClusterFeatureRegistration, ClusterPage
|
||||
import type { Cluster } from "../main/cluster";
|
||||
import { LensExtension } from "./lens-extension";
|
||||
import { getExtensionPageUrl } from "./registries/page-registry";
|
||||
import { CommandRegistration } from "./registries/command-registry";
|
||||
|
||||
export class LensRendererExtension extends LensExtension {
|
||||
globalPages: PageRegistration[] = [];
|
||||
@@ -14,6 +15,7 @@ export class LensRendererExtension extends LensExtension {
|
||||
statusBarItems: StatusBarRegistration[] = [];
|
||||
kubeObjectDetailItems: KubeObjectDetailRegistration[] = [];
|
||||
kubeObjectMenuItems: KubeObjectMenuRegistration[] = [];
|
||||
commands: CommandRegistration[] = [];
|
||||
|
||||
async navigate<P extends object>(pageId?: string, params?: P) {
|
||||
const { navigate } = await import("../renderer/navigation");
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
// Extensions API -> Commands
|
||||
|
||||
import type { Cluster } from "../../main/cluster";
|
||||
import type { Workspace } from "../../common/workspace-store";
|
||||
import { BaseRegistry } from "./base-registry";
|
||||
import { action } from "mobx";
|
||||
import { LensExtension } from "../lens-extension";
|
||||
|
||||
export type CommandContext = {
|
||||
cluster?: Cluster;
|
||||
workspace?: Workspace;
|
||||
};
|
||||
|
||||
export interface CommandRegistration {
|
||||
id: string;
|
||||
title: string;
|
||||
scope: "cluster" | "global";
|
||||
action: (context: CommandContext) => void;
|
||||
isActive?: (context: CommandContext) => boolean;
|
||||
}
|
||||
|
||||
export class CommandRegistry extends BaseRegistry<CommandRegistration> {
|
||||
@action
|
||||
add(items: CommandRegistration | CommandRegistration[], extension?: LensExtension) {
|
||||
const itemArray = [items].flat();
|
||||
|
||||
const newIds = itemArray.map((item) => item.id);
|
||||
const currentIds = this.getItems().map((item) => item.id);
|
||||
|
||||
const filteredIds = newIds.filter((id) => !currentIds.includes(id));
|
||||
const filteredItems = itemArray.filter((item) => filteredIds.includes(item.id));
|
||||
|
||||
return super.add(filteredItems, extension);
|
||||
}
|
||||
}
|
||||
|
||||
export const commandRegistry = new CommandRegistry();
|
||||
@@ -3,7 +3,18 @@
|
||||
import React from "react";
|
||||
import { BaseRegistry } from "./base-registry";
|
||||
|
||||
export interface StatusBarRegistration {
|
||||
interface StatusBarComponents {
|
||||
Item?: React.ComponentType;
|
||||
}
|
||||
|
||||
interface StatusBarRegistrationV2 {
|
||||
components?: StatusBarComponents; // has to be optional for backwards compatability
|
||||
}
|
||||
|
||||
export interface StatusBarRegistration extends StatusBarRegistrationV2 {
|
||||
/**
|
||||
* @deprecated use components.Item instead
|
||||
*/
|
||||
item?: React.ReactNode;
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,9 @@ export * from "../../renderer/components/select";
|
||||
export * from "../../renderer/components/slider";
|
||||
export * from "../../renderer/components/input/input";
|
||||
|
||||
// command-overlay
|
||||
export { CommandOverlay } from "../../renderer/components/command-palette";
|
||||
|
||||
// other components
|
||||
export * from "../../renderer/components/icon";
|
||||
export * from "../../renderer/components/tooltip";
|
||||
@@ -38,4 +41,4 @@ export * from "../../renderer/components/+events/kube-event-details";
|
||||
// specific exports
|
||||
export * from "../../renderer/components/status-brick";
|
||||
export { terminalStore, createTerminalTab } from "../../renderer/components/dock/terminal.store";
|
||||
export { createPodLogsTab } from "../../renderer/components/dock/pod-logs.store";
|
||||
export { logTabStore } from "../../renderer/components/dock/log-tab.store";
|
||||
@@ -14,6 +14,7 @@ export { ConfigMap, configMapApi } from "../../renderer/api/endpoints";
|
||||
export { Secret, secretsApi, ISecretRef } from "../../renderer/api/endpoints";
|
||||
export { ReplicaSet, replicaSetApi } from "../../renderer/api/endpoints";
|
||||
export { ResourceQuota, resourceQuotaApi } from "../../renderer/api/endpoints";
|
||||
export { LimitRange, limitRangeApi } from "../../renderer/api/endpoints";
|
||||
export { HorizontalPodAutoscaler, hpaApi } from "../../renderer/api/endpoints";
|
||||
export { PodDisruptionBudget, pdbApi } from "../../renderer/api/endpoints";
|
||||
export { Service, serviceApi } from "../../renderer/api/endpoints";
|
||||
@@ -46,6 +47,7 @@ export type { ConfigMapsStore } from "../../renderer/components/+config-maps/con
|
||||
export type { SecretsStore } from "../../renderer/components/+config-secrets/secrets.store";
|
||||
export type { ReplicaSetStore } from "../../renderer/components/+workloads-replicasets/replicasets.store";
|
||||
export type { ResourceQuotasStore } from "../../renderer/components/+config-resource-quotas/resource-quotas.store";
|
||||
export type { LimitRangesStore } from "../../renderer/components/+config-limit-ranges/limit-ranges.store";
|
||||
export type { HPAStore } from "../../renderer/components/+config-autoscalers/hpa.store";
|
||||
export type { PodDisruptionBudgetsStore } from "../../renderer/components/+config-pod-disruption-budgets/pod-disruption-budgets.store";
|
||||
export type { ServiceStore } from "../../renderer/components/+network-services/services.store";
|
||||
|
||||
@@ -8,4 +8,4 @@ export enum KubeObjectStatusLevel {
|
||||
INFO = 1,
|
||||
WARNING = 2,
|
||||
CRITICAL = 3
|
||||
}
|
||||
}
|
||||
@@ -2,4 +2,4 @@ import { themeStore } from "../../renderer/theme.store";
|
||||
|
||||
export function getActiveTheme() {
|
||||
return themeStore.activeTheme;
|
||||
}
|
||||
}
|
||||
@@ -126,6 +126,7 @@ describe("create clusters", () => {
|
||||
};
|
||||
|
||||
jest.spyOn(Cluster.prototype, "isClusterAdmin").mockReturnValue(Promise.resolve(true));
|
||||
jest.spyOn(Cluster.prototype, "canUseWatchApi").mockReturnValue(Promise.resolve(true));
|
||||
jest.spyOn(Cluster.prototype, "canI")
|
||||
.mockImplementation((attr: V1ResourceAttributes): Promise<boolean> => {
|
||||
expect(attr.namespace).toBe("default");
|
||||
|
||||
+86
-10
@@ -1,20 +1,96 @@
|
||||
import { autoUpdater } from "electron-updater";
|
||||
import { autoUpdater, UpdateInfo } from "electron-updater";
|
||||
import logger from "./logger";
|
||||
import { isDevelopment, isTestEnv } from "../common/vars";
|
||||
import { delay } from "../common/utils";
|
||||
import { areArgsUpdateAvailableToBackchannel, AutoUpdateLogPrefix, broadcastMessage, onceCorrect, UpdateAvailableChannel, UpdateAvailableToBackchannel } from "../common/ipc";
|
||||
import { ipcMain } from "electron";
|
||||
|
||||
export class AppUpdater {
|
||||
static readonly defaultUpdateIntervalMs = 1000 * 60 * 60 * 24; // once a day
|
||||
let installVersion: null | string = null;
|
||||
|
||||
static checkForUpdates() {
|
||||
return autoUpdater.checkForUpdatesAndNotify();
|
||||
function handleAutoUpdateBackChannel(event: Electron.IpcMainEvent, ...[arg]: UpdateAvailableToBackchannel) {
|
||||
if (arg.doUpdate) {
|
||||
if (arg.now) {
|
||||
logger.info(`${AutoUpdateLogPrefix}: User chose to update now`);
|
||||
autoUpdater.on("update-downloaded", () => autoUpdater.quitAndInstall());
|
||||
autoUpdater.downloadUpdate().catch(error => logger.error(`${AutoUpdateLogPrefix}: Failed to download or install update`, { error }));
|
||||
} else {
|
||||
logger.info(`${AutoUpdateLogPrefix}: User chose to update on quit`);
|
||||
autoUpdater.autoInstallOnAppQuit = true;
|
||||
autoUpdater.downloadUpdate()
|
||||
.catch(error => logger.error(`${AutoUpdateLogPrefix}: Failed to download update`, { error }));
|
||||
}
|
||||
} else {
|
||||
logger.info(`${AutoUpdateLogPrefix}: User chose not to update`);
|
||||
}
|
||||
}
|
||||
|
||||
constructor(protected updateInterval = AppUpdater.defaultUpdateIntervalMs) {
|
||||
autoUpdater.logger = logger;
|
||||
/**
|
||||
* starts the automatic update checking
|
||||
* @param interval milliseconds between interval to check on, defaults to 24h
|
||||
*/
|
||||
export function startUpdateChecking(interval = 1000 * 60 * 60 * 24): void {
|
||||
if (isDevelopment || isTestEnv) {
|
||||
return;
|
||||
}
|
||||
|
||||
public start() {
|
||||
setInterval(AppUpdater.checkForUpdates, this.updateInterval);
|
||||
autoUpdater.logger = logger;
|
||||
autoUpdater.autoDownload = false;
|
||||
autoUpdater.autoInstallOnAppQuit = false;
|
||||
|
||||
return AppUpdater.checkForUpdates();
|
||||
autoUpdater
|
||||
.on("update-available", (args: UpdateInfo) => {
|
||||
if (autoUpdater.autoInstallOnAppQuit) {
|
||||
// a previous auto-update loop was completed with YES+LATER, check if same version
|
||||
if (installVersion === args.version) {
|
||||
// same version, don't broadcast
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This should be always set to false here because it is the reasonable
|
||||
* default. Namely, if a don't auto update to a version that the user
|
||||
* didn't ask for.
|
||||
*/
|
||||
autoUpdater.autoInstallOnAppQuit = false;
|
||||
installVersion = args.version;
|
||||
|
||||
try {
|
||||
const backchannel = `auto-update:${args.version}`;
|
||||
|
||||
ipcMain.removeAllListeners(backchannel); // only one handler should be present
|
||||
|
||||
// make sure that the handler is in place before broadcasting (prevent race-condition)
|
||||
onceCorrect({
|
||||
source: ipcMain,
|
||||
channel: backchannel,
|
||||
listener: handleAutoUpdateBackChannel,
|
||||
verifier: areArgsUpdateAvailableToBackchannel,
|
||||
});
|
||||
logger.info(`${AutoUpdateLogPrefix}: broadcasting update available`, { backchannel, version: args.version });
|
||||
broadcastMessage(UpdateAvailableChannel, backchannel, args);
|
||||
} catch (error) {
|
||||
logger.error(`${AutoUpdateLogPrefix}: broadcasting failed`, { error });
|
||||
installVersion = undefined;
|
||||
}
|
||||
});
|
||||
|
||||
async function helper() {
|
||||
while (true) {
|
||||
await checkForUpdates();
|
||||
await delay(interval);
|
||||
}
|
||||
}
|
||||
|
||||
helper();
|
||||
}
|
||||
|
||||
export async function checkForUpdates(): Promise<void> {
|
||||
try {
|
||||
logger.info(`📡 Checking for app updates`);
|
||||
|
||||
await autoUpdater.checkForUpdates();
|
||||
} catch (error) {
|
||||
logger.error(`${AutoUpdateLogPrefix}: failed with an error`, { error: String(error) });
|
||||
}
|
||||
}
|
||||
@@ -31,4 +31,4 @@ export class BaseClusterDetector {
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -23,4 +23,4 @@ export class ClusterIdDetector extends BaseClusterDetector {
|
||||
|
||||
return response.metadata.uid;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -48,4 +48,4 @@ detectorRegistry.add(ClusterIdDetector);
|
||||
detectorRegistry.add(LastSeenDetector);
|
||||
detectorRegistry.add(VersionDetector);
|
||||
detectorRegistry.add(DistributionDetector);
|
||||
detectorRegistry.add(NodesCountDetector);
|
||||
detectorRegistry.add(NodesCountDetector);
|
||||
@@ -11,4 +11,4 @@ export class LastSeenDetector extends BaseClusterDetector {
|
||||
|
||||
return { value: new Date().toJSON(), accuracy: 100 };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,4 +16,4 @@ export class NodesCountDetector extends BaseClusterDetector {
|
||||
|
||||
return response.items.length;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,4 +16,4 @@ export class VersionDetector extends BaseClusterDetector {
|
||||
|
||||
return response.gitVersion;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import "../common/cluster-ipc";
|
||||
import type http from "http";
|
||||
import { ipcMain } from "electron";
|
||||
import { autorun } from "mobx";
|
||||
import { autorun, reaction } from "mobx";
|
||||
import { clusterStore, getClusterIdFromHost } from "../common/cluster-store";
|
||||
import { Cluster } from "./cluster";
|
||||
import logger from "./logger";
|
||||
@@ -12,14 +12,14 @@ export class ClusterManager extends Singleton {
|
||||
constructor(public readonly port: number) {
|
||||
super();
|
||||
// auto-init clusters
|
||||
autorun(() => {
|
||||
clusterStore.enabledClustersList.forEach(cluster => {
|
||||
if (!cluster.initialized) {
|
||||
reaction(() => clusterStore.enabledClustersList, (clusters) => {
|
||||
clusters.forEach((cluster) => {
|
||||
if (!cluster.initialized && !cluster.initializing) {
|
||||
logger.info(`[CLUSTER-MANAGER]: init cluster`, cluster.getMeta());
|
||||
cluster.init(port);
|
||||
}
|
||||
});
|
||||
});
|
||||
}, { fireImmediately: true });
|
||||
|
||||
// auto-stop removed clusters
|
||||
autorun(() => {
|
||||
|
||||
+73
-18
@@ -48,6 +48,7 @@ export interface ClusterState {
|
||||
isAdmin: boolean;
|
||||
allowedNamespaces: string[]
|
||||
allowedResources: string[]
|
||||
isGlobalWatchEnabled: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -85,6 +86,13 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
whenInitialized = when(() => this.initialized);
|
||||
whenReady = when(() => this.ready);
|
||||
|
||||
/**
|
||||
* Is cluster object initializinng on-going
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
@observable initializing = false;
|
||||
|
||||
/**
|
||||
* Is cluster object initialized
|
||||
*
|
||||
@@ -171,6 +179,12 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
*/
|
||||
@observable isAdmin = false;
|
||||
|
||||
/**
|
||||
* Global watch-api accessibility , e.g. "/api/v1/services?watch=1"
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
@observable isGlobalWatchEnabled = false;
|
||||
/**
|
||||
* Preferences
|
||||
*
|
||||
@@ -184,7 +198,7 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
*/
|
||||
@observable metadata: ClusterMetadata = {};
|
||||
/**
|
||||
* List of allowed namespaces
|
||||
* List of allowed namespaces verified via K8S::SelfSubjectAccessReview api
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
@@ -197,7 +211,7 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
*/
|
||||
@observable allowedResources: string[] = [];
|
||||
/**
|
||||
* List of accessible namespaces
|
||||
* List of accessible namespaces provided by user in the Cluster Settings
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
@@ -218,7 +232,7 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
* @computed
|
||||
*/
|
||||
@computed get name() {
|
||||
return this.preferences.clusterName || this.contextName;
|
||||
return this.preferences.clusterName || this.contextName;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -279,8 +293,10 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
* @param port port where internal auth proxy is listening
|
||||
* @internal
|
||||
*/
|
||||
@action async init(port: number) {
|
||||
@action
|
||||
async init(port: number) {
|
||||
try {
|
||||
this.initializing = true;
|
||||
this.contextHandler = new ContextHandler(this);
|
||||
this.kubeconfigManager = await KubeconfigManager.create(this, this.contextHandler, port);
|
||||
this.kubeProxyUrl = `http://localhost:${port}${apiKubePrefix}`;
|
||||
@@ -295,6 +311,8 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
id: this.id,
|
||||
error: err,
|
||||
});
|
||||
} finally {
|
||||
this.initializing = false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -331,7 +349,8 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
* @param force force activation
|
||||
* @internal
|
||||
*/
|
||||
@action async activate(force = false) {
|
||||
@action
|
||||
async activate(force = false) {
|
||||
if (this.activated && !force) {
|
||||
return this.pushState();
|
||||
}
|
||||
@@ -348,9 +367,7 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
await this.refreshConnectionStatus();
|
||||
|
||||
if (this.accessible) {
|
||||
await this.refreshAllowedResources();
|
||||
this.isAdmin = await this.isClusterAdmin();
|
||||
this.ready = true;
|
||||
await this.refreshAccessibility();
|
||||
this.ensureKubectl();
|
||||
}
|
||||
this.activated = true;
|
||||
@@ -370,7 +387,8 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
@action async reconnect() {
|
||||
@action
|
||||
async reconnect() {
|
||||
logger.info(`[CLUSTER]: reconnect`, this.getMeta());
|
||||
this.contextHandler?.stopServer();
|
||||
await this.contextHandler?.ensureServer();
|
||||
@@ -389,6 +407,7 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
this.accessible = false;
|
||||
this.ready = false;
|
||||
this.activated = false;
|
||||
this.allowedNamespaces = [];
|
||||
this.resourceAccessStatuses.clear();
|
||||
this.pushState();
|
||||
}
|
||||
@@ -397,19 +416,18 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
* @internal
|
||||
* @param opts refresh options
|
||||
*/
|
||||
@action async refresh(opts: ClusterRefreshOptions = {}) {
|
||||
@action
|
||||
async refresh(opts: ClusterRefreshOptions = {}) {
|
||||
logger.info(`[CLUSTER]: refresh`, this.getMeta());
|
||||
await this.whenInitialized;
|
||||
await this.refreshConnectionStatus();
|
||||
|
||||
if (this.accessible) {
|
||||
this.isAdmin = await this.isClusterAdmin();
|
||||
await this.refreshAllowedResources();
|
||||
await this.refreshAccessibility();
|
||||
|
||||
if (opts.refreshMetadata) {
|
||||
this.refreshMetadata();
|
||||
}
|
||||
this.ready = true;
|
||||
}
|
||||
this.pushState();
|
||||
}
|
||||
@@ -417,7 +435,8 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
@action async refreshMetadata() {
|
||||
@action
|
||||
async refreshMetadata() {
|
||||
logger.info(`[CLUSTER]: refreshMetadata`, this.getMeta());
|
||||
const metadata = await detectorRegistry.detectForCluster(this);
|
||||
const existingMetadata = this.metadata;
|
||||
@@ -428,7 +447,20 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
@action async refreshConnectionStatus() {
|
||||
private async refreshAccessibility(): Promise<void> {
|
||||
this.isAdmin = await this.isClusterAdmin();
|
||||
this.isGlobalWatchEnabled = await this.canUseWatchApi({ resource: "*" });
|
||||
|
||||
await this.refreshAllowedResources();
|
||||
|
||||
this.ready = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
@action
|
||||
async refreshConnectionStatus() {
|
||||
const connectionStatus = await this.getConnectionStatus();
|
||||
|
||||
this.online = connectionStatus > ClusterStatus.Offline;
|
||||
@@ -438,7 +470,8 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
@action async refreshAllowedResources() {
|
||||
@action
|
||||
async refreshAllowedResources() {
|
||||
this.allowedNamespaces = await this.getAllowedNamespaces();
|
||||
this.allowedResources = await this.getAllowedResources();
|
||||
}
|
||||
@@ -561,6 +594,17 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
async canUseWatchApi(customizeResource: V1ResourceAttributes = {}): Promise<boolean> {
|
||||
return this.canI({
|
||||
verb: "watch",
|
||||
resource: "*",
|
||||
...customizeResource,
|
||||
});
|
||||
}
|
||||
|
||||
toJSON(): ClusterModel {
|
||||
const model: ClusterModel = {
|
||||
id: this.id,
|
||||
@@ -594,6 +638,7 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
isAdmin: this.isAdmin,
|
||||
allowedNamespaces: this.allowedNamespaces,
|
||||
allowedResources: this.allowedResources,
|
||||
isGlobalWatchEnabled: this.isGlobalWatchEnabled,
|
||||
};
|
||||
|
||||
return toJS(state, {
|
||||
@@ -665,7 +710,7 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
for (const namespace of this.allowedNamespaces.slice(0, 10)) {
|
||||
if (!this.resourceAccessStatuses.get(apiResource)) {
|
||||
const result = await this.canI({
|
||||
resource: apiResource.resource,
|
||||
resource: apiResource.apiName,
|
||||
group: apiResource.group,
|
||||
verb: "list",
|
||||
namespace
|
||||
@@ -680,9 +725,19 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
|
||||
return apiResources
|
||||
.filter((resource) => this.resourceAccessStatuses.get(resource))
|
||||
.map(apiResource => apiResource.resource);
|
||||
.map(apiResource => apiResource.apiName);
|
||||
} catch (error) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
isAllowedResource(kind: string): boolean {
|
||||
const apiResource = apiResources.find(resource => resource.kind === kind || resource.apiName === kind);
|
||||
|
||||
if (apiResource) {
|
||||
return this.allowedResources.includes(apiResource.apiName);
|
||||
}
|
||||
|
||||
return true; // allowed by default for other resources
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
import logger from "./logger";
|
||||
|
||||
/**
|
||||
* Installs Electron developer tools in the development build.
|
||||
* The dependency is not bundled to the production build.
|
||||
*/
|
||||
export const installDeveloperTools = async () => {
|
||||
if (process.env.NODE_ENV === "development") {
|
||||
logger.info("🤓 Installing developer tools");
|
||||
const { default: devToolsInstaller, REACT_DEVELOPER_TOOLS } = await import("electron-devtools-installer");
|
||||
|
||||
return devToolsInstaller([REACT_DEVELOPER_TOOLS]);
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
import { HelmRepo, HelmRepoManager } from "../helm-repo-manager";
|
||||
|
||||
export class HelmChartManager {
|
||||
private cache: any = {};
|
||||
private repo: HelmRepo;
|
||||
|
||||
constructor(repo: HelmRepo){
|
||||
this.cache = HelmRepoManager.cache;
|
||||
this.repo = repo;
|
||||
}
|
||||
|
||||
public async charts(): Promise<any> {
|
||||
switch (this.repo.name) {
|
||||
case "stable":
|
||||
return Promise.resolve({
|
||||
"apm-server": [
|
||||
{
|
||||
apiVersion: "3.0.0",
|
||||
name: "apm-server",
|
||||
version: "2.1.7",
|
||||
repo: "stable",
|
||||
digest: "test"
|
||||
},
|
||||
{
|
||||
apiVersion: "3.0.0",
|
||||
name: "apm-server",
|
||||
version: "2.1.6",
|
||||
repo: "stable",
|
||||
digest: "test"
|
||||
}
|
||||
],
|
||||
"redis": [
|
||||
{
|
||||
apiVersion: "3.0.0",
|
||||
name: "apm-server",
|
||||
version: "1.0.0",
|
||||
repo: "stable",
|
||||
digest: "test"
|
||||
},
|
||||
{
|
||||
apiVersion: "3.0.0",
|
||||
name: "apm-server",
|
||||
version: "0.0.9",
|
||||
repo: "stable",
|
||||
digest: "test"
|
||||
}
|
||||
]
|
||||
});
|
||||
case "experiment":
|
||||
return Promise.resolve({
|
||||
"fairwind": [
|
||||
{
|
||||
apiVersion: "3.0.0",
|
||||
name: "fairwind",
|
||||
version: "0.0.1",
|
||||
repo: "experiment",
|
||||
digest: "test"
|
||||
},
|
||||
{
|
||||
apiVersion: "3.0.0",
|
||||
name: "fairwind",
|
||||
version: "0.0.2",
|
||||
repo: "experiment",
|
||||
digest: "test",
|
||||
deprecated: true
|
||||
}
|
||||
]
|
||||
});
|
||||
case "bitnami":
|
||||
return Promise.resolve({
|
||||
"hotdog": [
|
||||
{
|
||||
apiVersion: "3.0.0",
|
||||
name: "hotdog",
|
||||
version: "1.0.1",
|
||||
repo: "bitnami",
|
||||
digest: "test"
|
||||
},
|
||||
{
|
||||
apiVersion: "3.0.0",
|
||||
name: "hotdog",
|
||||
version: "1.0.2",
|
||||
repo: "bitnami",
|
||||
digest: "test",
|
||||
}
|
||||
],
|
||||
"pretzel": [
|
||||
{
|
||||
apiVersion: "3.0.0",
|
||||
name: "pretzel",
|
||||
version: "1.0",
|
||||
repo: "bitnami",
|
||||
digest: "test",
|
||||
},
|
||||
{
|
||||
apiVersion: "3.0.0",
|
||||
name: "pretzel",
|
||||
version: "1.0.1",
|
||||
repo: "bitnami",
|
||||
digest: "test"
|
||||
}
|
||||
]
|
||||
});
|
||||
default:
|
||||
return Promise.resolve({});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import { helmService } from "../helm-service";
|
||||
import { repoManager } from "../helm-repo-manager";
|
||||
|
||||
jest.spyOn(repoManager, "init").mockImplementation();
|
||||
|
||||
jest.mock("../helm-chart-manager");
|
||||
|
||||
describe("Helm Service tests", () => {
|
||||
test("list charts without deprecated ones", async () => {
|
||||
jest.spyOn(repoManager, "repositories").mockImplementation(async () => {
|
||||
return [
|
||||
{ name: "stable", url: "stableurl" },
|
||||
{ name: "experiment", url: "experimenturl" }
|
||||
];
|
||||
});
|
||||
|
||||
const charts = await helmService.listCharts();
|
||||
|
||||
expect(charts).toEqual({
|
||||
stable: {
|
||||
"apm-server": [
|
||||
{
|
||||
apiVersion: "3.0.0",
|
||||
name: "apm-server",
|
||||
version: "2.1.7",
|
||||
repo: "stable",
|
||||
digest: "test"
|
||||
},
|
||||
{
|
||||
apiVersion: "3.0.0",
|
||||
name: "apm-server",
|
||||
version: "2.1.6",
|
||||
repo: "stable",
|
||||
digest: "test"
|
||||
}
|
||||
],
|
||||
"redis": [
|
||||
{
|
||||
apiVersion: "3.0.0",
|
||||
name: "apm-server",
|
||||
version: "1.0.0",
|
||||
repo: "stable",
|
||||
digest: "test"
|
||||
},
|
||||
{
|
||||
apiVersion: "3.0.0",
|
||||
name: "apm-server",
|
||||
version: "0.0.9",
|
||||
repo: "stable",
|
||||
digest: "test"
|
||||
}
|
||||
]
|
||||
},
|
||||
experiment: {}
|
||||
});
|
||||
});
|
||||
|
||||
test("list charts sorted by version in descending order", async () => {
|
||||
jest.spyOn(repoManager, "repositories").mockImplementation(async () => {
|
||||
return [
|
||||
{ name: "bitnami", url: "bitnamiurl" }
|
||||
];
|
||||
});
|
||||
|
||||
const charts = await helmService.listCharts();
|
||||
|
||||
expect(charts).toEqual({
|
||||
bitnami: {
|
||||
"hotdog": [
|
||||
{
|
||||
apiVersion: "3.0.0",
|
||||
name: "hotdog",
|
||||
version: "1.0.2",
|
||||
repo: "bitnami",
|
||||
digest: "test",
|
||||
},
|
||||
{
|
||||
apiVersion: "3.0.0",
|
||||
name: "hotdog",
|
||||
version: "1.0.1",
|
||||
repo: "bitnami",
|
||||
digest: "test"
|
||||
},
|
||||
],
|
||||
"pretzel": [
|
||||
{
|
||||
apiVersion: "3.0.0",
|
||||
name: "pretzel",
|
||||
version: "1.0.1",
|
||||
repo: "bitnami",
|
||||
digest: "test",
|
||||
},
|
||||
{
|
||||
apiVersion: "3.0.0",
|
||||
name: "pretzel",
|
||||
version: "1.0",
|
||||
repo: "bitnami",
|
||||
digest: "test"
|
||||
}
|
||||
]
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -4,9 +4,10 @@ import { HelmRepo, HelmRepoManager } from "./helm-repo-manager";
|
||||
import logger from "../logger";
|
||||
import { promiseExec } from "../promise-exec";
|
||||
import { helmCli } from "./helm-cli";
|
||||
import type { RepoHelmChartList } from "../../renderer/api/endpoints/helm-charts.api";
|
||||
|
||||
type CachedYaml = {
|
||||
entries: any; // todo: types
|
||||
entries: RepoHelmChartList
|
||||
};
|
||||
|
||||
export class HelmChartManager {
|
||||
@@ -24,15 +25,15 @@ export class HelmChartManager {
|
||||
return charts[name];
|
||||
}
|
||||
|
||||
public async charts(): Promise<any> {
|
||||
public async charts(): Promise<RepoHelmChartList> {
|
||||
try {
|
||||
const cachedYaml = await this.cachedYaml();
|
||||
|
||||
return cachedYaml["entries"];
|
||||
} catch(error) {
|
||||
logger.error(error);
|
||||
logger.error("HELM-CHART-MANAGER]: failed to list charts", { error });
|
||||
|
||||
return [];
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import semver from "semver";
|
||||
import { Cluster } from "../cluster";
|
||||
import logger from "../logger";
|
||||
import { repoManager } from "./helm-repo-manager";
|
||||
import { HelmChartManager } from "./helm-chart-manager";
|
||||
import { releaseManager } from "./helm-release-manager";
|
||||
import { HelmChartList, RepoHelmChartList } from "../../renderer/api/endpoints/helm-charts.api";
|
||||
|
||||
class HelmService {
|
||||
public async installChart(cluster: Cluster, data: { chart: string; values: {}; name: string; namespace: string; version: string }) {
|
||||
@@ -10,7 +12,7 @@ class HelmService {
|
||||
}
|
||||
|
||||
public async listCharts() {
|
||||
const charts: any = {};
|
||||
const charts: HelmChartList = {};
|
||||
|
||||
await repoManager.init();
|
||||
const repositories = await repoManager.repositories();
|
||||
@@ -18,14 +20,10 @@ class HelmService {
|
||||
for (const repo of repositories) {
|
||||
charts[repo.name] = {};
|
||||
const manager = new HelmChartManager(repo);
|
||||
let entries = await manager.charts();
|
||||
const sortedCharts = this.sortChartsByVersion(await manager.charts());
|
||||
const enabledCharts = this.excludeDeprecatedChartGroups(sortedCharts);
|
||||
|
||||
entries = this.excludeDeprecated(entries);
|
||||
|
||||
for (const key in entries) {
|
||||
entries[key] = entries[key][0];
|
||||
}
|
||||
charts[repo.name] = entries;
|
||||
charts[repo.name] = enabledCharts;
|
||||
}
|
||||
|
||||
return charts;
|
||||
@@ -96,20 +94,30 @@ class HelmService {
|
||||
return { message: output };
|
||||
}
|
||||
|
||||
protected excludeDeprecated(entries: any) {
|
||||
for (const key in entries) {
|
||||
entries[key] = entries[key].filter((entry: any) => {
|
||||
if (Array.isArray(entry)) {
|
||||
return entry[0]["deprecated"] != true;
|
||||
}
|
||||
private excludeDeprecatedChartGroups(chartGroups: RepoHelmChartList) {
|
||||
const groups = new Map(Object.entries(chartGroups));
|
||||
|
||||
return entry["deprecated"] != true;
|
||||
for (const [chartName, charts] of groups) {
|
||||
if (charts[0].deprecated) {
|
||||
groups.delete(chartName);
|
||||
}
|
||||
}
|
||||
|
||||
return Object.fromEntries(groups);
|
||||
}
|
||||
|
||||
private sortChartsByVersion(chartGroups: RepoHelmChartList) {
|
||||
for (const key in chartGroups) {
|
||||
chartGroups[key] = chartGroups[key].sort((first, second) => {
|
||||
const firstVersion = semver.coerce(first.version || 0);
|
||||
const secondVersion = semver.coerce(second.version || 0);
|
||||
|
||||
return semver.compare(secondVersion, firstVersion);
|
||||
});
|
||||
}
|
||||
|
||||
return entries;
|
||||
return chartGroups;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export const helmService = new HelmService();
|
||||
+41
-8
@@ -4,13 +4,12 @@ import "../common/system-ca";
|
||||
import "../common/prometheus-providers";
|
||||
import * as Mobx from "mobx";
|
||||
import * as LensExtensions from "../extensions/core-api";
|
||||
import { app, dialog, powerMonitor } from "electron";
|
||||
import { app, autoUpdater, dialog, powerMonitor } from "electron";
|
||||
import { appName } from "../common/vars";
|
||||
import path from "path";
|
||||
import { LensProxy } from "./lens-proxy";
|
||||
import { WindowManager } from "./window-manager";
|
||||
import { ClusterManager } from "./cluster-manager";
|
||||
import { AppUpdater } from "./app-updater";
|
||||
import { shellSync } from "./shell-sync";
|
||||
import { getFreePort } from "./port";
|
||||
import { mangleProxyEnv } from "./proxy-env";
|
||||
@@ -26,6 +25,9 @@ import { InstalledExtension, extensionDiscovery } from "../extensions/extension-
|
||||
import type { LensExtensionId } from "../extensions/lens-extension";
|
||||
import { installDeveloperTools } from "./developer-tools";
|
||||
import { filesystemProvisionerStore } from "./extension-filesystem";
|
||||
import { getAppVersion, getAppVersionFromProxyServer } from "../common/utils";
|
||||
import { bindBroadcastHandlers } from "../common/ipc";
|
||||
import { startUpdateChecking } from "./app-updater";
|
||||
|
||||
const workingDir = path.join(app.getPath("appData"), appName);
|
||||
let proxyPort: number;
|
||||
@@ -61,20 +63,20 @@ if (process.env.LENS_DISABLE_GPU) {
|
||||
|
||||
app.on("ready", async () => {
|
||||
logger.info(`🚀 Starting Lens from "${workingDir}"`);
|
||||
logger.info("🐚 Syncing shell environment");
|
||||
await shellSync();
|
||||
|
||||
bindBroadcastHandlers();
|
||||
|
||||
powerMonitor.on("shutdown", () => {
|
||||
app.exit();
|
||||
});
|
||||
|
||||
const updater = new AppUpdater();
|
||||
|
||||
updater.start();
|
||||
|
||||
registerFileProtocol("static", __static);
|
||||
|
||||
await installDeveloperTools();
|
||||
|
||||
logger.info("💾 Loading stores");
|
||||
// preload
|
||||
await Promise.all([
|
||||
userStore.load(),
|
||||
@@ -86,6 +88,7 @@ app.on("ready", async () => {
|
||||
|
||||
// find free port
|
||||
try {
|
||||
logger.info("🔑 Getting free port for LensProxy server");
|
||||
proxyPort = await getFreePort();
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
@@ -98,6 +101,7 @@ app.on("ready", async () => {
|
||||
|
||||
// run proxy
|
||||
try {
|
||||
logger.info("🔌 Starting LensProxy");
|
||||
// eslint-disable-next-line unused-imports/no-unused-vars-ts
|
||||
proxyServer = LensProxy.create(proxyPort, clusterManager);
|
||||
} catch (error) {
|
||||
@@ -106,9 +110,27 @@ app.on("ready", async () => {
|
||||
app.exit();
|
||||
}
|
||||
|
||||
// test proxy connection
|
||||
try {
|
||||
logger.info("🔎 Testing LensProxy connection ...");
|
||||
const versionFromProxy = await getAppVersionFromProxyServer(proxyPort);
|
||||
|
||||
if (getAppVersion() !== versionFromProxy) {
|
||||
logger.error(`Proxy server responded with invalid response`);
|
||||
}
|
||||
logger.info("⚡ LensProxy connection OK");
|
||||
} catch (error) {
|
||||
logger.error("Checking proxy server connection failed", error);
|
||||
}
|
||||
|
||||
extensionLoader.init();
|
||||
extensionDiscovery.init();
|
||||
|
||||
logger.info("🖥️ Starting WindowManager");
|
||||
windowManager = WindowManager.getInstance<WindowManager>(proxyPort);
|
||||
windowManager.whenLoaded.then(() => startUpdateChecking());
|
||||
|
||||
logger.info("🧩 Initializing extensions");
|
||||
|
||||
// call after windowManager to see splash earlier
|
||||
try {
|
||||
@@ -145,14 +167,25 @@ app.on("activate", (event, hasVisibleWindows) => {
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* This variable should is used so that `autoUpdater.installAndQuit()` works
|
||||
*/
|
||||
let blockQuit = true;
|
||||
|
||||
autoUpdater.on("before-quit-for-update", () => blockQuit = false);
|
||||
|
||||
// Quit app on Cmd+Q (MacOS)
|
||||
app.on("will-quit", (event) => {
|
||||
logger.info("APP:QUIT");
|
||||
appEventBus.emit({name: "app", action: "close"});
|
||||
event.preventDefault(); // prevent app's default shutdown (e.g. required for telemetry, etc.)
|
||||
|
||||
clusterManager?.stop(); // close cluster connections
|
||||
|
||||
return; // skip exit to make tray work, to quit go to app's global menu or tray's menu
|
||||
if (blockQuit) {
|
||||
event.preventDefault(); // prevent app's default shutdown (e.g. required for telemetry, etc.)
|
||||
|
||||
return; // skip exit to make tray work, to quit go to app's global menu or tray's menu
|
||||
}
|
||||
});
|
||||
|
||||
// Extensions-api runtime exports
|
||||
|
||||
+4
-4
@@ -23,10 +23,10 @@ const kubectlMap: Map<string, string> = new Map([
|
||||
["1.14", "1.14.10"],
|
||||
["1.15", "1.15.11"],
|
||||
["1.16", "1.16.15"],
|
||||
["1.17", bundledVersion],
|
||||
["1.18", "1.18.14"],
|
||||
["1.19", "1.19.5"],
|
||||
["1.20", "1.20.0"]
|
||||
["1.17", "1.17.17"],
|
||||
["1.18", bundledVersion],
|
||||
["1.19", "1.19.7"],
|
||||
["1.20", "1.20.2"]
|
||||
]);
|
||||
const packageMirrors: Map<string, string> = new Map([
|
||||
["default", "https://storage.googleapis.com/kubernetes-release/release"],
|
||||
|
||||
@@ -29,7 +29,7 @@ export class LensProxy {
|
||||
|
||||
listen(port = this.port): this {
|
||||
this.proxyServer = this.buildCustomProxy().listen(port);
|
||||
logger.info(`LensProxy server has started at ${this.origin}`);
|
||||
logger.info(`[LENS-PROXY]: Proxy server has started at ${this.origin}`);
|
||||
|
||||
return this;
|
||||
}
|
||||
@@ -194,7 +194,8 @@ export class LensProxy {
|
||||
|
||||
if (proxyTarget) {
|
||||
// allow to fetch apis in "clusterId.localhost:port" from "localhost:port"
|
||||
res.setHeader("Access-Control-Allow-Origin", this.origin);
|
||||
// this should be safe because we have already validated cluster uuid
|
||||
res.setHeader("Access-Control-Allow-Origin", "*");
|
||||
|
||||
return proxy.web(req, res, proxyTarget);
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ import { extensionsURL } from "../renderer/components/+extensions/extensions.rou
|
||||
import { menuRegistry } from "../extensions/registries/menu-registry";
|
||||
import logger from "./logger";
|
||||
import { exitApp } from "./exit-app";
|
||||
import { broadcastMessage } from "../common/ipc";
|
||||
|
||||
export type MenuTopId = "mac" | "file" | "edit" | "view" | "help";
|
||||
|
||||
@@ -173,6 +174,14 @@ export function buildMenu(windowManager: WindowManager) {
|
||||
const viewMenu: MenuItemConstructorOptions = {
|
||||
label: "View",
|
||||
submenu: [
|
||||
{
|
||||
label: "Command Palette...",
|
||||
accelerator: "Shift+CmdOrCtrl+P",
|
||||
click() {
|
||||
broadcastMessage("command-palette:open");
|
||||
}
|
||||
},
|
||||
{ type: "separator" },
|
||||
{
|
||||
label: "Back",
|
||||
accelerator: "CmdOrCtrl+[",
|
||||
|
||||
+2
-4
@@ -5,7 +5,7 @@ import path from "path";
|
||||
import { readFile } from "fs-extra";
|
||||
import { Cluster } from "./cluster";
|
||||
import { apiPrefix, appName, publicPath, isDevelopment, webpackDevServerPort } from "../common/vars";
|
||||
import { helmRoute, kubeconfigRoute, metricsRoute, portForwardRoute, resourceApplierRoute, watchRoute } from "./routes";
|
||||
import { helmRoute, kubeconfigRoute, metricsRoute, portForwardRoute, resourceApplierRoute, versionRoute } from "./routes";
|
||||
import logger from "./logger";
|
||||
|
||||
export interface RouterRequestOpts {
|
||||
@@ -143,11 +143,9 @@ export class Router {
|
||||
this.handleStaticFile(params.path, response, req);
|
||||
});
|
||||
|
||||
this.router.add({ method: "get", path: "/version"}, versionRoute.getVersion.bind(versionRoute));
|
||||
this.router.add({ method: "get", path: `${apiPrefix}/kubeconfig/service-account/{namespace}/{account}` }, kubeconfigRoute.routeServiceAccountRoute.bind(kubeconfigRoute));
|
||||
|
||||
// Watch API
|
||||
this.router.add({ method: "get", path: `${apiPrefix}/watch` }, watchRoute.routeWatch.bind(watchRoute));
|
||||
|
||||
// Metrics API
|
||||
this.router.add({ method: "post", path: `${apiPrefix}/metrics` }, metricsRoute.routeMetrics.bind(metricsRoute));
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
export * from "./kubeconfig-route";
|
||||
export * from "./metrics-route";
|
||||
export * from "./port-forward-route";
|
||||
export * from "./watch-route";
|
||||
export * from "./helm-route";
|
||||
export * from "./resource-applier-route";
|
||||
export * from "./version-route";
|
||||
@@ -0,0 +1,13 @@
|
||||
import { LensApiRequest } from "../router";
|
||||
import { LensApi } from "../lens-api";
|
||||
import { getAppVersion } from "../../common/utils";
|
||||
|
||||
class VersionRoute extends LensApi {
|
||||
public async getVersion(request: LensApiRequest) {
|
||||
const { response } = request;
|
||||
|
||||
this.respondJson(response, { version: getAppVersion()}, 200);
|
||||
}
|
||||
}
|
||||
|
||||
export const versionRoute = new VersionRoute();
|
||||
@@ -1,115 +0,0 @@
|
||||
import { LensApiRequest } from "../router";
|
||||
import { LensApi } from "../lens-api";
|
||||
import { Watch, KubeConfig } from "@kubernetes/client-node";
|
||||
import { ServerResponse } from "http";
|
||||
import { Request } from "request";
|
||||
import logger from "../logger";
|
||||
|
||||
class ApiWatcher {
|
||||
private apiUrl: string;
|
||||
private response: ServerResponse;
|
||||
private watchRequest: Request;
|
||||
private watch: Watch;
|
||||
private processor: NodeJS.Timeout;
|
||||
private eventBuffer: any[] = [];
|
||||
|
||||
constructor(apiUrl: string, kubeConfig: KubeConfig, response: ServerResponse) {
|
||||
this.apiUrl = apiUrl;
|
||||
this.watch = new Watch(kubeConfig);
|
||||
this.response = response;
|
||||
}
|
||||
|
||||
public async start() {
|
||||
if (this.processor) {
|
||||
clearInterval(this.processor);
|
||||
}
|
||||
this.processor = setInterval(() => {
|
||||
const events = this.eventBuffer.splice(0);
|
||||
|
||||
events.map(event => this.sendEvent(event));
|
||||
this.response.flushHeaders();
|
||||
}, 50);
|
||||
this.watchRequest = await this.watch.watch(this.apiUrl, {}, this.watchHandler.bind(this), this.doneHandler.bind(this));
|
||||
}
|
||||
|
||||
public stop() {
|
||||
if (!this.watchRequest) { return; }
|
||||
|
||||
if (this.processor) {
|
||||
clearInterval(this.processor);
|
||||
}
|
||||
logger.debug(`Stopping watcher for api: ${this.apiUrl}`);
|
||||
|
||||
try {
|
||||
this.watchRequest.abort();
|
||||
this.sendEvent({
|
||||
type: "STREAM_END",
|
||||
url: this.apiUrl,
|
||||
status: 410,
|
||||
});
|
||||
logger.debug("watch aborted");
|
||||
} catch (error) {
|
||||
logger.error(`Watch abort errored:${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
private watchHandler(phase: string, obj: any) {
|
||||
this.eventBuffer.push({
|
||||
type: phase,
|
||||
object: obj
|
||||
});
|
||||
}
|
||||
|
||||
private doneHandler(error: Error) {
|
||||
if (error) logger.warn(`watch ended: ${error.toString()}`);
|
||||
this.watchRequest.abort();
|
||||
}
|
||||
|
||||
private sendEvent(evt: any) {
|
||||
// convert to "text/event-stream" format
|
||||
this.response.write(`data: ${JSON.stringify(evt)}\n\n`);
|
||||
}
|
||||
}
|
||||
|
||||
class WatchRoute extends LensApi {
|
||||
|
||||
public async routeWatch(request: LensApiRequest) {
|
||||
const { response, cluster} = request;
|
||||
const apis: string[] = request.query.getAll("api");
|
||||
const watchers: ApiWatcher[] = [];
|
||||
|
||||
if (!apis.length) {
|
||||
this.respondJson(response, {
|
||||
message: "Empty request. Query params 'api' are not provided.",
|
||||
example: "?api=/api/v1/pods&api=/api/v1/nodes",
|
||||
}, 400);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
response.setHeader("Content-Type", "text/event-stream");
|
||||
response.setHeader("Cache-Control", "no-cache");
|
||||
response.setHeader("Connection", "keep-alive");
|
||||
logger.debug(`watch using kubeconfig:${JSON.stringify(cluster.getProxyKubeconfig(), null, 2)}`);
|
||||
|
||||
apis.forEach(apiUrl => {
|
||||
const watcher = new ApiWatcher(apiUrl, cluster.getProxyKubeconfig(), response);
|
||||
|
||||
watcher.start();
|
||||
watchers.push(watcher);
|
||||
});
|
||||
|
||||
request.raw.req.on("close", () => {
|
||||
logger.debug("Watch request closed");
|
||||
watchers.map(watcher => watcher.stop());
|
||||
});
|
||||
|
||||
request.raw.req.on("end", () => {
|
||||
logger.debug("Watch request ended");
|
||||
watchers.map(watcher => watcher.stop());
|
||||
});
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
export const watchRoute = new WatchRoute();
|
||||
@@ -108,7 +108,7 @@ export class ShellSession extends EventEmitter {
|
||||
|
||||
if(isWindows) {
|
||||
env["SystemRoot"] = process.env.SystemRoot;
|
||||
env["PTYSHELL"] = "powershell.exe";
|
||||
env["PTYSHELL"] = process.env.SHELL || "powershell.exe";
|
||||
env["PATH"] = pathStr;
|
||||
} else if(typeof(process.env.SHELL) != "undefined") {
|
||||
env["PTYSHELL"] = process.env.SHELL;
|
||||
|
||||
+12
-21
@@ -1,9 +1,9 @@
|
||||
import path from "path";
|
||||
import packageInfo from "../../package.json";
|
||||
import { dialog, Menu, NativeImage, Tray } from "electron";
|
||||
import { Menu, NativeImage, Tray } from "electron";
|
||||
import { autorun } from "mobx";
|
||||
import { showAbout } from "./menu";
|
||||
import { AppUpdater } from "./app-updater";
|
||||
import { checkForUpdates } from "./app-updater";
|
||||
import { WindowManager } from "./window-manager";
|
||||
import { clusterStore } from "../common/cluster-store";
|
||||
import { workspaceStore } from "../common/workspace-store";
|
||||
@@ -62,16 +62,6 @@ function buildTray(icon: string | NativeImage, menu: Menu, windowManager: Window
|
||||
|
||||
function createTrayMenu(windowManager: WindowManager): Menu {
|
||||
return Menu.buildFromTemplate([
|
||||
{
|
||||
label: "About Lens",
|
||||
async click() {
|
||||
// note: argument[1] (browserWindow) not available when app is not focused / hidden
|
||||
const browserWindow = await windowManager.ensureMainWindow();
|
||||
|
||||
showAbout(browserWindow);
|
||||
},
|
||||
},
|
||||
{ type: "separator" },
|
||||
{
|
||||
label: "Open Lens",
|
||||
async click() {
|
||||
@@ -112,16 +102,17 @@ function createTrayMenu(windowManager: WindowManager): Menu {
|
||||
{
|
||||
label: "Check for updates",
|
||||
async click() {
|
||||
const result = await AppUpdater.checkForUpdates();
|
||||
await checkForUpdates();
|
||||
await windowManager.ensureMainWindow();
|
||||
},
|
||||
},
|
||||
{
|
||||
label: "About Lens",
|
||||
async click() {
|
||||
// note: argument[1] (browserWindow) not available when app is not focused / hidden
|
||||
const browserWindow = await windowManager.ensureMainWindow();
|
||||
|
||||
if (!result) {
|
||||
const browserWindow = await windowManager.ensureMainWindow();
|
||||
|
||||
dialog.showMessageBoxSync(browserWindow, {
|
||||
message: "No updates available",
|
||||
type: "info",
|
||||
});
|
||||
}
|
||||
showAbout(browserWindow);
|
||||
},
|
||||
},
|
||||
{ type: "separator" },
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { ClusterId } from "../common/cluster-store";
|
||||
import { observable } from "mobx";
|
||||
import { observable, when } from "mobx";
|
||||
import { app, BrowserWindow, dialog, shell, webContents } from "electron";
|
||||
import windowStateKeeper from "electron-window-state";
|
||||
import { appEventBus } from "../common/event-bus";
|
||||
@@ -8,6 +8,7 @@ import { initMenu } from "./menu";
|
||||
import { initTray } from "./tray";
|
||||
import { Singleton } from "../common/utils";
|
||||
import { ClusterFrameInfo, clusterFrameMap } from "../common/cluster-frames";
|
||||
import logger from "./logger";
|
||||
|
||||
export class WindowManager extends Singleton {
|
||||
protected mainWindow: BrowserWindow;
|
||||
@@ -15,6 +16,9 @@ export class WindowManager extends Singleton {
|
||||
protected windowState: windowStateKeeper.State;
|
||||
protected disposers: Record<string, Function> = {};
|
||||
|
||||
@observable mainViewInitiallyLoaded = false;
|
||||
whenLoaded = when(() => this.mainViewInitiallyLoaded);
|
||||
|
||||
@observable activeClusterId: ClusterId;
|
||||
|
||||
constructor(protected proxyPort: number) {
|
||||
@@ -81,16 +85,26 @@ export class WindowManager extends Singleton {
|
||||
this.splashWindow = null;
|
||||
app.dock?.hide(); // hide icon in dock (mac-os)
|
||||
});
|
||||
|
||||
this.mainWindow.webContents.on("did-fail-load", (_event, code, desc) => {
|
||||
logger.error(`[WINDOW-MANAGER]: Failed to load Main window`, { code, desc });
|
||||
});
|
||||
|
||||
this.mainWindow.webContents.on("did-finish-load", () => {
|
||||
logger.info("[WINDOW-MANAGER]: Main window loaded");
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
if (showSplash) await this.showSplash();
|
||||
logger.info(`[WINDOW-MANAGER]: Loading Main window from url: ${this.mainUrl} ...`);
|
||||
await this.mainWindow.loadURL(this.mainUrl);
|
||||
this.mainWindow.show();
|
||||
this.splashWindow?.close();
|
||||
setTimeout(() => {
|
||||
appEventBus.emit({ name: "app", action: "start" });
|
||||
}, 1000);
|
||||
this.mainViewInitiallyLoaded = true;
|
||||
} catch (err) {
|
||||
dialog.showErrorBox("ERROR!", err.toString());
|
||||
}
|
||||
|
||||
@@ -18,4 +18,4 @@ export default {
|
||||
...version270Beta1,
|
||||
...version360Beta1,
|
||||
...snap
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,40 @@
|
||||
import { ingressStore } from "../../components/+network-ingresses/ingress.store";
|
||||
import { apiManager } from "../api-manager";
|
||||
import { KubeApi } from "../kube-api";
|
||||
|
||||
class TestApi extends KubeApi {
|
||||
|
||||
protected async checkPreferredVersion() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
describe("ApiManager", () => {
|
||||
describe("registerApi", () => {
|
||||
it("re-register store if apiBase changed", async () => {
|
||||
const apiBase = "apis/v1/foo";
|
||||
const fallbackApiBase = "/apis/extensions/v1beta1/foo";
|
||||
const kubeApi = new TestApi({
|
||||
apiBase,
|
||||
fallbackApiBases: [fallbackApiBase],
|
||||
checkPreferredVersion: true,
|
||||
});
|
||||
|
||||
apiManager.registerApi(apiBase, kubeApi);
|
||||
|
||||
// Define to use test api for ingress store
|
||||
Object.defineProperty(ingressStore, "api", { value: kubeApi });
|
||||
apiManager.registerStore(ingressStore, [kubeApi]);
|
||||
|
||||
// Test that store is returned with original apiBase
|
||||
expect(apiManager.getStore(kubeApi)).toBe(ingressStore);
|
||||
|
||||
// Change apiBase similar as checkPreferredVersion does
|
||||
Object.defineProperty(kubeApi, "apiBase", { value: fallbackApiBase });
|
||||
apiManager.registerApi(fallbackApiBase, kubeApi);
|
||||
|
||||
// Test that store is returned with new apiBase
|
||||
expect(apiManager.getStore(kubeApi)).toBe(ingressStore);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -79,4 +79,4 @@ describe("KubeApi", () => {
|
||||
expect(kubeApi.apiPrefix).toEqual("/apis");
|
||||
expect(kubeApi.apiGroup).toEqual("extensions");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -2,16 +2,16 @@ import type { KubeObjectStore } from "../kube-object.store";
|
||||
|
||||
import { action, observable } from "mobx";
|
||||
import { autobind } from "../utils";
|
||||
import { KubeApi } from "./kube-api";
|
||||
import { KubeApi, parseKubeApi } from "./kube-api";
|
||||
|
||||
@autobind()
|
||||
export class ApiManager {
|
||||
private apis = observable.map<string, KubeApi>();
|
||||
private stores = observable.map<KubeApi, KubeObjectStore>();
|
||||
private stores = observable.map<string, KubeObjectStore>();
|
||||
|
||||
getApi(pathOrCallback: string | ((api: KubeApi) => boolean)) {
|
||||
if (typeof pathOrCallback === "string") {
|
||||
return this.apis.get(pathOrCallback) || this.apis.get(KubeApi.parseApi(pathOrCallback).apiBase);
|
||||
return this.apis.get(pathOrCallback) || this.apis.get(parseKubeApi(pathOrCallback).apiBase);
|
||||
}
|
||||
|
||||
return Array.from(this.apis.values()).find(pathOrCallback ?? (() => true));
|
||||
@@ -23,6 +23,12 @@ export class ApiManager {
|
||||
|
||||
registerApi(apiBase: string, api: KubeApi) {
|
||||
if (!this.apis.has(apiBase)) {
|
||||
this.stores.forEach((store) => {
|
||||
if(store.api === api) {
|
||||
this.stores.set(apiBase, store);
|
||||
}
|
||||
});
|
||||
|
||||
this.apis.set(apiBase, api);
|
||||
}
|
||||
}
|
||||
@@ -46,12 +52,12 @@ export class ApiManager {
|
||||
@action
|
||||
registerStore(store: KubeObjectStore, apis: KubeApi[] = [store.api]) {
|
||||
apis.forEach(api => {
|
||||
this.stores.set(api, store);
|
||||
this.stores.set(api.apiBase, store);
|
||||
});
|
||||
}
|
||||
|
||||
getStore<S extends KubeObjectStore>(api: string | KubeApi): S {
|
||||
return this.stores.get(this.resolveApi(api)) as S;
|
||||
return this.stores.get(this.resolveApi(api)?.apiBase) as S;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ export class KubeEvent extends KubeObject {
|
||||
firstTimestamp: string;
|
||||
lastTimestamp: string;
|
||||
count: number;
|
||||
type: string;
|
||||
type: "Normal" | "Warning" | string;
|
||||
eventTime: null;
|
||||
reportingComponent: string;
|
||||
reportingInstance: string;
|
||||
|
||||
@@ -3,11 +3,8 @@ import { apiBase } from "../index";
|
||||
import { stringify } from "querystring";
|
||||
import { autobind } from "../../utils";
|
||||
|
||||
interface IHelmChartList {
|
||||
[repo: string]: {
|
||||
[name: string]: HelmChart;
|
||||
};
|
||||
}
|
||||
export type RepoHelmChartList = Record<string, HelmChart[]>;
|
||||
export type HelmChartList = Record<string, RepoHelmChartList>;
|
||||
|
||||
export interface IHelmChartDetails {
|
||||
readme: string;
|
||||
@@ -22,12 +19,12 @@ const endpoint = compile(`/v2/charts/:repo?/:name?`) as (params?: {
|
||||
export const helmChartsApi = {
|
||||
list() {
|
||||
return apiBase
|
||||
.get<IHelmChartList>(endpoint())
|
||||
.get<HelmChartList>(endpoint())
|
||||
.then(data => {
|
||||
return Object
|
||||
.values(data)
|
||||
.reduce((allCharts, repoCharts) => allCharts.concat(Object.values(repoCharts)), [])
|
||||
.map(HelmChart.create);
|
||||
.map(([chart]) => HelmChart.create(chart));
|
||||
});
|
||||
},
|
||||
|
||||
@@ -86,7 +83,7 @@ export class HelmChart {
|
||||
tillerVersion?: string;
|
||||
|
||||
getId() {
|
||||
return this.digest;
|
||||
return `${this.apiVersion}/${this.name}@${this.getAppVersion()}`;
|
||||
}
|
||||
|
||||
getName() {
|
||||
|
||||
@@ -57,6 +57,7 @@ export interface IReleaseRevision {
|
||||
updated: string;
|
||||
status: string;
|
||||
chart: string;
|
||||
app_version: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
@@ -197,10 +198,9 @@ export class HelmRelease implements ItemObject {
|
||||
}
|
||||
|
||||
getUpdated(humanize = true, compact = true) {
|
||||
const now = new Date().getTime();
|
||||
const updated = this.updated.replace(/\s\w*$/, ""); // 2019-11-26 10:58:09 +0300 MSK -> 2019-11-26 10:58:09 +0300 to pass into Date()
|
||||
const updatedDate = new Date(updated).getTime();
|
||||
const diff = now - updatedDate;
|
||||
const diff = Date.now() - updatedDate;
|
||||
|
||||
if (humanize) {
|
||||
return formatDuration(diff, compact);
|
||||
|
||||
@@ -14,6 +14,7 @@ export * from "./events.api";
|
||||
export * from "./hpa.api";
|
||||
export * from "./ingress.api";
|
||||
export * from "./job.api";
|
||||
export * from "./limit-range.api";
|
||||
export * from "./namespaces.api";
|
||||
export * from "./network-policy.api";
|
||||
export * from "./nodes.api";
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { KubeObject } from "../kube-object";
|
||||
import { KubeApi } from "../kube-api";
|
||||
import { autobind } from "../../utils";
|
||||
|
||||
export enum LimitType {
|
||||
CONTAINER = "Container",
|
||||
POD = "Pod",
|
||||
PVC = "PersistentVolumeClaim",
|
||||
}
|
||||
|
||||
export enum Resource {
|
||||
MEMORY = "memory",
|
||||
CPU = "cpu",
|
||||
STORAGE = "storage",
|
||||
EPHEMERAL_STORAGE = "ephemeral-storage",
|
||||
}
|
||||
|
||||
export enum LimitPart {
|
||||
MAX = "max",
|
||||
MIN = "min",
|
||||
DEFAULT = "default",
|
||||
DEFAULT_REQUEST = "defaultRequest",
|
||||
MAX_LIMIT_REQUEST_RATIO = "maxLimitRequestRatio",
|
||||
}
|
||||
|
||||
type LimitRangeParts = Partial<Record<LimitPart, Record<string, string>>>;
|
||||
|
||||
export interface LimitRangeItem extends LimitRangeParts {
|
||||
type: string
|
||||
}
|
||||
|
||||
@autobind()
|
||||
export class LimitRange extends KubeObject {
|
||||
static kind = "LimitRange";
|
||||
static namespaced = true;
|
||||
static apiBase = "/api/v1/limitranges";
|
||||
|
||||
spec: {
|
||||
limits: LimitRangeItem[];
|
||||
};
|
||||
|
||||
getContainerLimits() {
|
||||
return this.spec.limits.filter(limit => limit.type === LimitType.CONTAINER);
|
||||
}
|
||||
|
||||
getPodLimits() {
|
||||
return this.spec.limits.filter(limit => limit.type === LimitType.POD);
|
||||
}
|
||||
|
||||
getPVCLimits() {
|
||||
return this.spec.limits.filter(limit => limit.type === LimitType.PVC);
|
||||
}
|
||||
}
|
||||
|
||||
export const limitRangeApi = new KubeApi({
|
||||
objectConstructor: LimitRange,
|
||||
});
|
||||
@@ -63,10 +63,16 @@ export class PersistentVolume extends KubeObject {
|
||||
return this.status.phase || "-";
|
||||
}
|
||||
|
||||
getClaimRefName() {
|
||||
const { claimRef } = this.spec;
|
||||
getStorageClass(): string {
|
||||
return this.spec.storageClassName;
|
||||
}
|
||||
|
||||
return claimRef ? claimRef.name : "";
|
||||
getClaimRefName(): string {
|
||||
return this.spec.claimRef?.name ?? "";
|
||||
}
|
||||
|
||||
getStorageClassName() {
|
||||
return this.spec.storageClassName || "";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -104,6 +104,9 @@ export interface IPodContainer {
|
||||
configMapRef?: {
|
||||
name: string;
|
||||
};
|
||||
secretRef?: {
|
||||
name: string;
|
||||
}
|
||||
}[];
|
||||
volumeMounts?: {
|
||||
name: string;
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import { stringify } from "querystring";
|
||||
import { EventEmitter } from "../../common/event-emitter";
|
||||
import { cancelableFetch } from "../utils/cancelableFetch";
|
||||
|
||||
import { randomBytes } from "crypto";
|
||||
export interface JsonApiData {
|
||||
}
|
||||
|
||||
@@ -55,6 +55,34 @@ export class JsonApi<D = JsonApiData, P extends JsonApiParams = JsonApiParams> {
|
||||
return this.request<T>(path, params, { ...reqInit, method: "get" });
|
||||
}
|
||||
|
||||
getResponse(path: string, params?: P, init: RequestInit = {}): Promise<Response> {
|
||||
const reqPath = `${this.config.apiBase}${path}`;
|
||||
const subdomain = randomBytes(2).toString("hex");
|
||||
let reqUrl = `http://${subdomain}.${window.location.host}${reqPath}`; // hack around browser connection limits (chromium allows 6 per domain)
|
||||
const reqInit: RequestInit = { ...init };
|
||||
const { query } = params || {} as P;
|
||||
|
||||
if (!reqInit.method) {
|
||||
reqInit.method = "get";
|
||||
}
|
||||
|
||||
if (query) {
|
||||
const queryString = stringify(query);
|
||||
|
||||
reqUrl += (reqUrl.includes("?") ? "&" : "?") + queryString;
|
||||
}
|
||||
|
||||
const infoLog: JsonApiLog = {
|
||||
method: reqInit.method.toUpperCase(),
|
||||
reqUrl: reqPath,
|
||||
reqInit,
|
||||
};
|
||||
|
||||
this.writeLog({ ...infoLog });
|
||||
|
||||
return fetch(reqUrl, reqInit);
|
||||
}
|
||||
|
||||
post<T = D>(path: string, params?: P, reqInit: RequestInit = {}) {
|
||||
return this.request<T>(path, params, { ...reqInit, method: "post" });
|
||||
}
|
||||
|
||||
+108
-14
@@ -8,8 +8,10 @@ import { apiManager } from "./api-manager";
|
||||
import { apiKube } from "./index";
|
||||
import { createKubeApiURL, parseKubeApi } from "./kube-api-parse";
|
||||
import { KubeJsonApi, KubeJsonApiData, KubeJsonApiDataList } from "./kube-json-api";
|
||||
import { IKubeObjectConstructor, KubeObject } from "./kube-object";
|
||||
import { kubeWatchApi } from "./kube-watch-api";
|
||||
import { IKubeObjectConstructor, KubeObject, KubeStatus } from "./kube-object";
|
||||
import byline from "byline";
|
||||
import { IKubeWatchEvent } from "./kube-watch-api";
|
||||
import { ReadableWebToNodeStream } from "../utils/readableStream";
|
||||
|
||||
export interface IKubeApiOptions<T extends KubeObject> {
|
||||
/**
|
||||
@@ -91,15 +93,15 @@ export function ensureObjectSelfLink(api: KubeApi, object: KubeJsonApiData) {
|
||||
}
|
||||
}
|
||||
|
||||
export type KubeApiWatchCallback = (data: IKubeWatchEvent, error: any) => void;
|
||||
|
||||
export type KubeApiWatchOptions = {
|
||||
namespace: string;
|
||||
callback?: KubeApiWatchCallback;
|
||||
abortController?: AbortController
|
||||
};
|
||||
|
||||
export class KubeApi<T extends KubeObject = any> {
|
||||
static parseApi = parseKubeApi;
|
||||
|
||||
static watchAll(...apis: KubeApi[]) {
|
||||
const disposers = apis.map(api => api.watch());
|
||||
|
||||
return () => disposers.forEach(unwatch => unwatch());
|
||||
}
|
||||
|
||||
readonly kind: string;
|
||||
readonly apiBase: string;
|
||||
readonly apiPrefix: string;
|
||||
@@ -112,6 +114,7 @@ export class KubeApi<T extends KubeObject = any> {
|
||||
public objectConstructor: IKubeObjectConstructor<T>;
|
||||
protected request: KubeJsonApi;
|
||||
protected resourceVersions = new Map<string, string>();
|
||||
protected watchDisposer: () => void;
|
||||
|
||||
constructor(protected options: IKubeApiOptions<T>) {
|
||||
const {
|
||||
@@ -124,7 +127,7 @@ export class KubeApi<T extends KubeObject = any> {
|
||||
if (!options.apiBase) {
|
||||
options.apiBase = objectConstructor.apiBase;
|
||||
}
|
||||
const { apiBase, apiPrefix, apiGroup, apiVersion, resource } = KubeApi.parseApi(options.apiBase);
|
||||
const { apiBase, apiPrefix, apiGroup, apiVersion, resource } = parseKubeApi(options.apiBase);
|
||||
|
||||
this.kind = kind;
|
||||
this.isNamespaced = isNamespaced;
|
||||
@@ -157,7 +160,7 @@ export class KubeApi<T extends KubeObject = any> {
|
||||
|
||||
for (const apiUrl of apiBases) {
|
||||
// Split e.g. "/apis/extensions/v1beta1/ingresses" to parts
|
||||
const { apiPrefix, apiGroup, apiVersionWithGroup, resource } = KubeApi.parseApi(apiUrl);
|
||||
const { apiPrefix, apiGroup, apiVersionWithGroup, resource } = parseKubeApi(apiUrl);
|
||||
|
||||
// Request available resources
|
||||
try {
|
||||
@@ -269,6 +272,7 @@ export class KubeApi<T extends KubeObject = any> {
|
||||
}
|
||||
|
||||
protected parseResponse(data: KubeJsonApiData | KubeJsonApiData[] | KubeJsonApiDataList, namespace?: string): any {
|
||||
if (!data) return;
|
||||
const KubeObjectConstructor = this.objectConstructor;
|
||||
|
||||
if (KubeObject.isJsonApiData(data)) {
|
||||
@@ -365,8 +369,98 @@ export class KubeApi<T extends KubeObject = any> {
|
||||
});
|
||||
}
|
||||
|
||||
watch(): () => void {
|
||||
return kubeWatchApi.subscribe(this);
|
||||
watch(opts: KubeApiWatchOptions = { namespace: "" }): () => void {
|
||||
if (!opts.abortController) {
|
||||
opts.abortController = new AbortController();
|
||||
}
|
||||
let errorReceived = false;
|
||||
let timedRetry: NodeJS.Timeout;
|
||||
const { abortController, namespace, callback } = opts;
|
||||
|
||||
abortController.signal.addEventListener("abort", () => {
|
||||
clearTimeout(timedRetry);
|
||||
});
|
||||
|
||||
const watchUrl = this.getWatchUrl(namespace);
|
||||
const responsePromise = this.request.getResponse(watchUrl, null, {
|
||||
signal: abortController.signal
|
||||
});
|
||||
|
||||
responsePromise.then((response) => {
|
||||
if (!response.ok && !abortController.signal.aborted) {
|
||||
callback?.(null, response);
|
||||
|
||||
return;
|
||||
}
|
||||
const nodeStream = new ReadableWebToNodeStream(response.body);
|
||||
|
||||
["end", "close", "error"].forEach((eventName) => {
|
||||
nodeStream.on(eventName, () => {
|
||||
if (errorReceived) return; // kubernetes errors should be handled in a callback
|
||||
|
||||
clearTimeout(timedRetry);
|
||||
timedRetry = setTimeout(() => { // we did not get any kubernetes errors so let's retry
|
||||
if (abortController.signal.aborted) return;
|
||||
|
||||
this.watch({...opts, namespace, callback});
|
||||
}, 1000);
|
||||
});
|
||||
});
|
||||
|
||||
const stream = byline(nodeStream);
|
||||
|
||||
stream.on("data", (line) => {
|
||||
try {
|
||||
const event: IKubeWatchEvent = JSON.parse(line);
|
||||
|
||||
if (event.type === "ERROR" && event.object.kind === "Status") {
|
||||
errorReceived = true;
|
||||
callback(null, new KubeStatus(event.object as any));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
this.modifyWatchEvent(event);
|
||||
|
||||
if (callback) {
|
||||
callback(event, null);
|
||||
}
|
||||
} catch (ignore) {
|
||||
// ignore parse errors
|
||||
}
|
||||
});
|
||||
}, (error) => {
|
||||
if (error instanceof DOMException) return; // AbortController rejects, we can ignore it
|
||||
|
||||
callback?.(null, error);
|
||||
}).catch((error) => {
|
||||
callback?.(null, error);
|
||||
});
|
||||
|
||||
const disposer = () => {
|
||||
abortController.abort();
|
||||
};
|
||||
|
||||
return disposer;
|
||||
}
|
||||
|
||||
protected modifyWatchEvent(event: IKubeWatchEvent) {
|
||||
|
||||
switch (event.type) {
|
||||
case "ADDED":
|
||||
case "DELETED":
|
||||
|
||||
case "MODIFIED": {
|
||||
ensureObjectSelfLink(this, event.object);
|
||||
|
||||
const { namespace, resourceVersion } = event.object.metadata;
|
||||
|
||||
this.setResourceVersion(namespace, resourceVersion);
|
||||
this.setResourceVersion("", resourceVersion);
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ export interface KubeJsonApiData extends JsonApiData {
|
||||
resourceVersion: string;
|
||||
continue?: string;
|
||||
finalizers?: string[];
|
||||
selfLink: string;
|
||||
selfLink?: string;
|
||||
labels?: {
|
||||
[label: string]: string;
|
||||
};
|
||||
|
||||
@@ -40,6 +40,29 @@ export interface IKubeObjectMetadata {
|
||||
}[];
|
||||
}
|
||||
|
||||
export interface IKubeStatus {
|
||||
kind: string;
|
||||
apiVersion: string;
|
||||
code: number;
|
||||
message?: string;
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
export class KubeStatus {
|
||||
public readonly kind = "Status";
|
||||
public readonly apiVersion: string;
|
||||
public readonly code: number;
|
||||
public readonly message: string;
|
||||
public readonly reason: string;
|
||||
|
||||
constructor(data: IKubeStatus) {
|
||||
this.apiVersion = data.apiVersion;
|
||||
this.code = data.code;
|
||||
this.message = data.message || "";
|
||||
this.reason = data.reason || "";
|
||||
}
|
||||
}
|
||||
|
||||
export type IKubeMetaField = keyof IKubeObjectMetadata;
|
||||
|
||||
@autobind()
|
||||
@@ -99,12 +122,15 @@ export class KubeObject implements ItemObject {
|
||||
return this.metadata.namespace || undefined;
|
||||
}
|
||||
|
||||
// todo: refactor with named arguments
|
||||
getAge(humanize = true, compact = true, fromNow = false) {
|
||||
getTimeDiffFromNow(): number {
|
||||
return Date.now() - new Date(this.metadata.creationTimestamp).getTime();
|
||||
}
|
||||
|
||||
getAge(humanize = true, compact = true, fromNow = false): string | number {
|
||||
if (fromNow) {
|
||||
return moment(this.metadata.creationTimestamp).fromNow();
|
||||
return moment(this.metadata.creationTimestamp).fromNow(); // "string", getTimeDiffFromNow() cannot be used
|
||||
}
|
||||
const diff = new Date().getTime() - new Date(this.metadata.creationTimestamp).getTime();
|
||||
const diff = this.getTimeDiffFromNow();
|
||||
|
||||
if (humanize) {
|
||||
return formatDuration(diff, compact);
|
||||
|
||||
+100
-152
@@ -1,183 +1,131 @@
|
||||
// Kubernetes watch-api consumer
|
||||
// Kubernetes watch-api client
|
||||
// API: https://developer.mozilla.org/en-US/docs/Web/API/Streams_API/Using_readable_streams
|
||||
|
||||
import { computed, observable, reaction } from "mobx";
|
||||
import { stringify } from "querystring";
|
||||
import { autobind, EventEmitter } from "../utils";
|
||||
import { KubeJsonApiData } from "./kube-json-api";
|
||||
import type { KubeObjectStore } from "../kube-object.store";
|
||||
import { ensureObjectSelfLink, KubeApi } from "./kube-api";
|
||||
import { apiManager } from "./api-manager";
|
||||
import { apiPrefix, isDevelopment } from "../../common/vars";
|
||||
import { getHostedCluster } from "../../common/cluster-store";
|
||||
import type { ClusterContext } from "../components/context";
|
||||
|
||||
export interface IKubeWatchEvent<T = any> {
|
||||
type: "ADDED" | "MODIFIED" | "DELETED";
|
||||
import plimit from "p-limit";
|
||||
import { comparer, IReactionDisposer, observable, reaction, when } from "mobx";
|
||||
import { autobind, noop } from "../utils";
|
||||
import { KubeApi } from "./kube-api";
|
||||
import { KubeJsonApiData } from "./kube-json-api";
|
||||
import { isDebugging, isProduction } from "../../common/vars";
|
||||
|
||||
export interface IKubeWatchEvent<T = KubeJsonApiData> {
|
||||
type: "ADDED" | "MODIFIED" | "DELETED" | "ERROR";
|
||||
object?: T;
|
||||
}
|
||||
|
||||
export interface IKubeWatchRouteEvent {
|
||||
type: "STREAM_END";
|
||||
url: string;
|
||||
status: number;
|
||||
export interface IKubeWatchSubscribeStoreOptions {
|
||||
namespaces?: string[]; // default: all accessible namespaces
|
||||
preload?: boolean; // preload store items, default: true
|
||||
waitUntilLoaded?: boolean; // subscribe only after loading all stores, default: true
|
||||
loadOnce?: boolean; // check store.isLoaded to skip loading if done already, default: false
|
||||
}
|
||||
|
||||
export interface IKubeWatchRouteQuery {
|
||||
api: string | string[];
|
||||
export interface IKubeWatchLog {
|
||||
message: string | string[] | Error;
|
||||
meta?: object;
|
||||
cssStyle?: string;
|
||||
}
|
||||
|
||||
@autobind()
|
||||
export class KubeWatchApi {
|
||||
protected evtSource: EventSource;
|
||||
protected onData = new EventEmitter<[IKubeWatchEvent]>();
|
||||
protected subscribers = observable.map<KubeApi, number>();
|
||||
protected reconnectTimeoutMs = 5000;
|
||||
protected maxReconnectsOnError = 10;
|
||||
protected reconnectAttempts = this.maxReconnectsOnError;
|
||||
@observable context: ClusterContext = null;
|
||||
|
||||
constructor() {
|
||||
reaction(() => this.activeApis, () => this.connect(), {
|
||||
fireImmediately: true,
|
||||
delay: 500,
|
||||
});
|
||||
contextReady = when(() => Boolean(this.context));
|
||||
|
||||
isAllowedApi(api: KubeApi): boolean {
|
||||
return Boolean(this.context?.cluster.isAllowedResource(api.kind));
|
||||
}
|
||||
|
||||
@computed get activeApis() {
|
||||
return Array.from(this.subscribers.keys());
|
||||
}
|
||||
preloadStores(stores: KubeObjectStore[], opts: { namespaces?: string[], loadOnce?: boolean } = {}) {
|
||||
const limitRequests = plimit(1); // load stores one by one to allow quick skipping when fast clicking btw pages
|
||||
const preloading: Promise<any>[] = [];
|
||||
|
||||
getSubscribersCount(api: KubeApi) {
|
||||
return this.subscribers.get(api) || 0;
|
||||
}
|
||||
for (const store of stores) {
|
||||
preloading.push(limitRequests(async () => {
|
||||
if (store.isLoaded && opts.loadOnce) return; // skip
|
||||
|
||||
subscribe(...apis: KubeApi[]) {
|
||||
apis.forEach(api => {
|
||||
this.subscribers.set(api, this.getSubscribersCount(api) + 1);
|
||||
});
|
||||
|
||||
return () => apis.forEach(api => {
|
||||
const count = this.getSubscribersCount(api) - 1;
|
||||
|
||||
if (count <= 0) this.subscribers.delete(api);
|
||||
else this.subscribers.set(api, count);
|
||||
});
|
||||
}
|
||||
|
||||
protected getQuery(): Partial<IKubeWatchRouteQuery> {
|
||||
const { isAdmin, allowedNamespaces } = getHostedCluster();
|
||||
return store.loadAll({ namespaces: opts.namespaces });
|
||||
}));
|
||||
}
|
||||
|
||||
return {
|
||||
api: this.activeApis.map(api => {
|
||||
if (isAdmin) return api.getWatchUrl();
|
||||
|
||||
return allowedNamespaces.map(namespace => api.getWatchUrl(namespace));
|
||||
}).flat()
|
||||
loading: Promise.allSettled(preloading),
|
||||
cancelLoading: () => limitRequests.clearQueue(),
|
||||
};
|
||||
}
|
||||
|
||||
// todo: maybe switch to websocket to avoid often reconnects
|
||||
@autobind()
|
||||
protected connect() {
|
||||
if (this.evtSource) this.disconnect(); // close previous connection
|
||||
subscribeStores(stores: KubeObjectStore[], opts: IKubeWatchSubscribeStoreOptions = {}): () => void {
|
||||
const { preload = true, waitUntilLoaded = true, loadOnce = false, } = opts;
|
||||
const subscribingNamespaces = opts.namespaces ?? this.context?.allNamespaces ?? [];
|
||||
const unsubscribeList: Function[] = [];
|
||||
let isUnsubscribed = false;
|
||||
|
||||
if (!this.activeApis.length) {
|
||||
const load = (namespaces = subscribingNamespaces) => this.preloadStores(stores, { namespaces, loadOnce });
|
||||
let preloading = preload && load();
|
||||
let cancelReloading: IReactionDisposer = noop;
|
||||
|
||||
const subscribe = () => {
|
||||
if (isUnsubscribed) return;
|
||||
|
||||
stores.forEach((store) => {
|
||||
unsubscribeList.push(store.subscribe());
|
||||
});
|
||||
};
|
||||
|
||||
if (preloading) {
|
||||
if (waitUntilLoaded) {
|
||||
preloading.loading.then(subscribe, error => {
|
||||
this.log({
|
||||
message: new Error("Loading stores has failed"),
|
||||
meta: { stores, error, options: opts },
|
||||
});
|
||||
});
|
||||
} else {
|
||||
subscribe();
|
||||
}
|
||||
|
||||
// reload stores only for context namespaces change
|
||||
cancelReloading = reaction(() => this.context?.contextNamespaces, namespaces => {
|
||||
preloading?.cancelLoading();
|
||||
unsubscribeList.forEach(unsubscribe => unsubscribe());
|
||||
unsubscribeList.length = 0;
|
||||
preloading = load(namespaces);
|
||||
preloading.loading.then(subscribe);
|
||||
}, {
|
||||
equals: comparer.shallow,
|
||||
});
|
||||
}
|
||||
|
||||
// unsubscribe
|
||||
return () => {
|
||||
if (isUnsubscribed) return;
|
||||
isUnsubscribed = true;
|
||||
cancelReloading();
|
||||
preloading?.cancelLoading();
|
||||
unsubscribeList.forEach(unsubscribe => unsubscribe());
|
||||
unsubscribeList.length = 0;
|
||||
};
|
||||
}
|
||||
|
||||
protected log({ message, cssStyle = "", meta = {} }: IKubeWatchLog) {
|
||||
if (isProduction && !isDebugging) {
|
||||
return;
|
||||
}
|
||||
const query = this.getQuery();
|
||||
const apiUrl = `${apiPrefix}/watch?${stringify(query)}`;
|
||||
|
||||
this.evtSource = new EventSource(apiUrl);
|
||||
this.evtSource.onmessage = this.onMessage;
|
||||
this.evtSource.onerror = this.onError;
|
||||
this.writeLog("CONNECTING", query.api);
|
||||
}
|
||||
|
||||
reconnect() {
|
||||
if (!this.evtSource || this.evtSource.readyState !== EventSource.OPEN) {
|
||||
this.reconnectAttempts = this.maxReconnectsOnError;
|
||||
this.connect();
|
||||
}
|
||||
}
|
||||
|
||||
protected disconnect() {
|
||||
if (!this.evtSource) return;
|
||||
this.evtSource.close();
|
||||
this.evtSource.onmessage = null;
|
||||
this.evtSource = null;
|
||||
}
|
||||
|
||||
protected onMessage(evt: MessageEvent) {
|
||||
if (!evt.data) return;
|
||||
const data = JSON.parse(evt.data);
|
||||
|
||||
if ((data as IKubeWatchEvent).object) {
|
||||
this.onData.emit(data);
|
||||
} else {
|
||||
this.onRouteEvent(data);
|
||||
}
|
||||
}
|
||||
|
||||
protected async onRouteEvent(event: IKubeWatchRouteEvent) {
|
||||
if (event.type === "STREAM_END") {
|
||||
this.disconnect();
|
||||
const { apiBase, namespace } = KubeApi.parseApi(event.url);
|
||||
const api = apiManager.getApi(apiBase);
|
||||
|
||||
if (api) {
|
||||
try {
|
||||
await api.refreshResourceVersion({ namespace });
|
||||
this.reconnect();
|
||||
} catch (error) {
|
||||
console.error("failed to refresh resource version", error);
|
||||
|
||||
if (this.subscribers.size > 0) {
|
||||
setTimeout(() => {
|
||||
this.onRouteEvent(event);
|
||||
}, 1000);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected onError(evt: MessageEvent) {
|
||||
const { reconnectAttempts: attemptsRemain, reconnectTimeoutMs } = this;
|
||||
|
||||
if (evt.eventPhase === EventSource.CLOSED) {
|
||||
if (attemptsRemain > 0) {
|
||||
this.reconnectAttempts--;
|
||||
setTimeout(() => this.connect(), reconnectTimeoutMs);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected writeLog(...data: any[]) {
|
||||
if (isDevelopment) {
|
||||
console.log("%cKUBE-WATCH-API:", `font-weight: bold`, ...data);
|
||||
}
|
||||
}
|
||||
|
||||
addListener(store: KubeObjectStore, callback: (evt: IKubeWatchEvent) => void) {
|
||||
const listener = (evt: IKubeWatchEvent<KubeJsonApiData>) => {
|
||||
const { namespace, resourceVersion } = evt.object.metadata;
|
||||
const api = apiManager.getApiByKind(evt.object.kind, evt.object.apiVersion);
|
||||
|
||||
api.setResourceVersion(namespace, resourceVersion);
|
||||
api.setResourceVersion("", resourceVersion);
|
||||
|
||||
ensureObjectSelfLink(api, evt.object);
|
||||
|
||||
if (store == apiManager.getStore(api)) {
|
||||
callback(evt);
|
||||
}
|
||||
const logInfo = [`%c[KUBE-WATCH-API]:`, `font-weight: bold; ${cssStyle}`, message].flat().map(String);
|
||||
const logMeta = {
|
||||
time: new Date().toLocaleString(),
|
||||
...meta,
|
||||
};
|
||||
|
||||
this.onData.addListener(listener);
|
||||
|
||||
return () => this.onData.removeListener(listener);
|
||||
}
|
||||
|
||||
reset() {
|
||||
this.subscribers.clear();
|
||||
if (message instanceof Error) {
|
||||
console.error(...logInfo, logMeta);
|
||||
} else {
|
||||
console.info(...logInfo, logMeta);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import get from "lodash/get";
|
||||
import { KubeObject } from "./kube-object";
|
||||
|
||||
interface IToleration {
|
||||
export interface IToleration {
|
||||
key?: string;
|
||||
operator?: string;
|
||||
effect?: string;
|
||||
@@ -82,4 +82,4 @@ export class WorkloadKubeObject extends KubeObject {
|
||||
|
||||
return Object.keys(affinity).length;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -82,9 +82,9 @@ export class HelmChartDetails extends Component<Props> {
|
||||
<div className="intro-contents box grow">
|
||||
<div className="description flex align-center justify-space-between">
|
||||
{selectedChart.getDescription()}
|
||||
<Button primary label={`Install`} onClick={this.install} />
|
||||
<Button primary label="Install" onClick={this.install} />
|
||||
</div>
|
||||
<DrawerItem name={`Version`} className="version" onClick={stopPropagation}>
|
||||
<DrawerItem name="Version" className="version" onClick={stopPropagation}>
|
||||
<Select
|
||||
themeName="outlined"
|
||||
menuPortalTarget={null}
|
||||
@@ -93,16 +93,16 @@ export class HelmChartDetails extends Component<Props> {
|
||||
onChange={onVersionChange}
|
||||
/>
|
||||
</DrawerItem>
|
||||
<DrawerItem name={`Home`}>
|
||||
<DrawerItem name="Home">
|
||||
<a href={selectedChart.getHome()} target="_blank" rel="noreferrer">{selectedChart.getHome()}</a>
|
||||
</DrawerItem>
|
||||
<DrawerItem name={`Maintainers`} className="maintainers">
|
||||
<DrawerItem name="Maintainers" className="maintainers">
|
||||
{selectedChart.getMaintainers().map(({ name, email, url }) =>
|
||||
<a key={name} href={url || `mailto:${email}`} target="_blank" rel="noreferrer">{name}</a>
|
||||
)}
|
||||
</DrawerItem>
|
||||
{selectedChart.getKeywords().length > 0 && (
|
||||
<DrawerItem name={`Keywords`} labelsOnly>
|
||||
<DrawerItem name="Keywords" labelsOnly>
|
||||
{selectedChart.getKeywords().map(key => <Badge key={key} label={key} />)}
|
||||
</DrawerItem>
|
||||
)}
|
||||
|
||||
@@ -11,4 +11,4 @@ export interface IHelmChartsRouteParams {
|
||||
repo?: string;
|
||||
}
|
||||
|
||||
export const helmChartsURL = buildURL<IHelmChartsRouteParams>(helmChartsRoute.path);
|
||||
export const helmChartsURL = buildURL<IHelmChartsRouteParams>(helmChartsRoute.path);
|
||||
@@ -11,8 +11,11 @@ import { navigation } from "../../navigation";
|
||||
import { ItemListLayout } from "../item-object-list/item-list-layout";
|
||||
import { SearchInputUrl } from "../input";
|
||||
|
||||
enum sortBy {
|
||||
enum columnId {
|
||||
name = "name",
|
||||
description = "description",
|
||||
version = "version",
|
||||
appVersion = "app-version",
|
||||
repo = "repo",
|
||||
}
|
||||
|
||||
@@ -53,13 +56,15 @@ export class HelmCharts extends Component<Props> {
|
||||
return (
|
||||
<>
|
||||
<ItemListLayout
|
||||
isConfigurable
|
||||
tableId="helm_charts"
|
||||
className="HelmCharts"
|
||||
store={helmChartStore}
|
||||
isClusterScoped={true}
|
||||
isSelectable={false}
|
||||
sortingCallbacks={{
|
||||
[sortBy.name]: (chart: HelmChart) => chart.getName(),
|
||||
[sortBy.repo]: (chart: HelmChart) => chart.getRepository(),
|
||||
[columnId.name]: (chart: HelmChart) => chart.getName(),
|
||||
[columnId.repo]: (chart: HelmChart) => chart.getRepository(),
|
||||
}}
|
||||
searchFilters={[
|
||||
(chart: HelmChart) => chart.getName(),
|
||||
@@ -67,20 +72,16 @@ export class HelmCharts extends Component<Props> {
|
||||
(chart: HelmChart) => chart.getAppVersion(),
|
||||
(chart: HelmChart) => chart.getKeywords(),
|
||||
]}
|
||||
filterItems={[
|
||||
(items: HelmChart[]) => items.filter(item => !item.deprecated)
|
||||
]}
|
||||
customizeHeader={() => (
|
||||
<SearchInputUrl placeholder={`Search Helm Charts`} />
|
||||
<SearchInputUrl placeholder="Search Helm Charts" />
|
||||
)}
|
||||
renderTableHeader={[
|
||||
{ className: "icon" },
|
||||
{ title: "Name", className: "name", sortBy: sortBy.name },
|
||||
{ title: "Description", className: "description" },
|
||||
{ title: "Version", className: "version" },
|
||||
{ title: "App Version", className: "app-version" },
|
||||
{ title: "Repository", className: "repository", sortBy: sortBy.repo },
|
||||
|
||||
{ className: "icon", showWithColumn: columnId.name },
|
||||
{ title: "Name", className: "name", sortBy: columnId.name, id: columnId.name },
|
||||
{ title: "Description", className: "description", id: columnId.description },
|
||||
{ title: "Version", className: "version", id: columnId.version },
|
||||
{ title: "App Version", className: "app-version", id: columnId.appVersion },
|
||||
{ title: "Repository", className: "repository", sortBy: columnId.repo, id: columnId.repo },
|
||||
]}
|
||||
renderTableContents={(chart: HelmChart) => [
|
||||
<figure key="image">
|
||||
@@ -93,7 +94,8 @@ export class HelmCharts extends Component<Props> {
|
||||
chart.getDescription(),
|
||||
chart.getVersion(),
|
||||
chart.getAppVersion(),
|
||||
{ title: chart.getRepository(), className: chart.getRepository().toLowerCase() }
|
||||
{ title: chart.getRepository(), className: chart.getRepository().toLowerCase() },
|
||||
{ className: "menu" }
|
||||
]}
|
||||
detailsItem={this.selectedChart}
|
||||
onDetails={this.showDetails}
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
export * from "./helm-charts";
|
||||
export * from "./helm-charts.route";
|
||||
export * from "./helm-charts.route";
|
||||
@@ -1,2 +1,2 @@
|
||||
export * from "./releases";
|
||||
export * from "./release.route";
|
||||
export * from "./release.route";
|
||||
@@ -111,7 +111,7 @@ export class ReleaseDetails extends Component<Props> {
|
||||
|
||||
return (
|
||||
<div className="values">
|
||||
<DrawerTitle title={`Values`}/>
|
||||
<DrawerTitle title="Values"/>
|
||||
<div className="flex column gaps">
|
||||
<AceEditor
|
||||
mode="yaml"
|
||||
@@ -120,7 +120,7 @@ export class ReleaseDetails extends Component<Props> {
|
||||
/>
|
||||
<Button
|
||||
primary
|
||||
label={`Save`}
|
||||
label="Save"
|
||||
waiting={saving}
|
||||
onClick={this.updateValues}
|
||||
/>
|
||||
@@ -200,7 +200,7 @@ export class ReleaseDetails extends Component<Props> {
|
||||
<span>{release.getChart()}</span>
|
||||
<Button
|
||||
primary
|
||||
label={`Upgrade`}
|
||||
label="Upgrade"
|
||||
className="box right upgrade"
|
||||
onClick={this.upgradeVersion}
|
||||
/>
|
||||
@@ -226,9 +226,9 @@ export class ReleaseDetails extends Component<Props> {
|
||||
/>
|
||||
</DrawerItem>
|
||||
{this.renderValues()}
|
||||
<DrawerTitle title={`Notes`}/>
|
||||
<DrawerTitle title="Notes"/>
|
||||
{this.renderNotes()}
|
||||
<DrawerTitle title={`Resources`}/>
|
||||
<DrawerTitle title="Resources"/>
|
||||
{this.renderResources()}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -42,7 +42,7 @@ export class HelmReleaseMenu extends React.Component<Props> {
|
||||
<>
|
||||
{hasRollback && (
|
||||
<MenuItem onClick={this.rollback}>
|
||||
<Icon material="history" interactive={toolbar} title={`Rollback`}/>
|
||||
<Icon material="history" interactive={toolbar} title="Rollback"/>
|
||||
<span className="title">Rollback</span>
|
||||
</MenuItem>
|
||||
)}
|
||||
|
||||
@@ -77,7 +77,8 @@ export class ReleaseRollbackDialog extends React.Component<Props> {
|
||||
themeName="light"
|
||||
value={revision}
|
||||
options={revisions}
|
||||
formatOptionLabel={({ value }: SelectOption<IReleaseRevision>) => `${value.revision} - ${value.chart}`}
|
||||
formatOptionLabel={({ value }: SelectOption<IReleaseRevision>) => `${value.revision} - ${value.chart}
|
||||
- ${value.app_version}, updated: ${new Date(value.updated).toLocaleString()}`}
|
||||
onChange={({ value }: SelectOption<IReleaseRevision>) => this.revision = value}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -5,7 +5,7 @@ import { HelmRelease, helmReleasesApi, IReleaseCreatePayload, IReleaseUpdatePayl
|
||||
import { ItemStore } from "../../item.store";
|
||||
import { Secret } from "../../api/endpoints";
|
||||
import { secretsStore } from "../+config-secrets/secrets.store";
|
||||
import { getHostedCluster } from "../../../common/cluster-store";
|
||||
import { namespaceStore } from "../+namespaces/namespace.store";
|
||||
|
||||
@autobind()
|
||||
export class ReleaseStore extends ItemStore<HelmRelease> {
|
||||
@@ -33,7 +33,7 @@ export class ReleaseStore extends ItemStore<HelmRelease> {
|
||||
});
|
||||
|
||||
if (amountChanged || labelsChanged) {
|
||||
this.loadAll();
|
||||
this.loadFromContextNamespaces();
|
||||
}
|
||||
this.releaseSecrets = [...secrets];
|
||||
});
|
||||
@@ -58,26 +58,30 @@ export class ReleaseStore extends ItemStore<HelmRelease> {
|
||||
}
|
||||
|
||||
@action
|
||||
async loadAll() {
|
||||
async loadAll(namespaces: string[]) {
|
||||
this.isLoading = true;
|
||||
let items;
|
||||
|
||||
try {
|
||||
const { isAdmin, allowedNamespaces } = getHostedCluster();
|
||||
const items = await this.loadItems(namespaces);
|
||||
|
||||
items = await this.loadItems(!isAdmin ? allowedNamespaces : null);
|
||||
} finally {
|
||||
if (items) {
|
||||
items = this.sortItems(items);
|
||||
this.items.replace(items);
|
||||
}
|
||||
this.items.replace(this.sortItems(items));
|
||||
this.isLoaded = true;
|
||||
} catch (error) {
|
||||
console.error(`Loading Helm Chart releases has failed: ${error}`);
|
||||
} finally {
|
||||
this.isLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
async loadItems(namespaces?: string[]) {
|
||||
if (!namespaces) {
|
||||
async loadFromContextNamespaces(): Promise<void> {
|
||||
return this.loadAll(namespaceStore.contextNamespaces);
|
||||
}
|
||||
|
||||
async loadItems(namespaces: string[]) {
|
||||
const isLoadingAll = namespaceStore.allowedNamespaces.every(ns => namespaces.includes(ns));
|
||||
const noAccessibleNamespaces = namespaceStore.context.cluster.accessibleNamespaces.length === 0;
|
||||
|
||||
if (isLoadingAll && noAccessibleNamespaces) {
|
||||
return helmReleasesApi.list();
|
||||
} else {
|
||||
return Promise
|
||||
@@ -89,7 +93,7 @@ export class ReleaseStore extends ItemStore<HelmRelease> {
|
||||
async create(payload: IReleaseCreatePayload) {
|
||||
const response = await helmReleasesApi.create(payload);
|
||||
|
||||
if (this.isLoaded) this.loadAll();
|
||||
if (this.isLoaded) this.loadFromContextNamespaces();
|
||||
|
||||
return response;
|
||||
}
|
||||
@@ -97,7 +101,7 @@ export class ReleaseStore extends ItemStore<HelmRelease> {
|
||||
async update(name: string, namespace: string, payload: IReleaseUpdatePayload) {
|
||||
const response = await helmReleasesApi.update(name, namespace, payload);
|
||||
|
||||
if (this.isLoaded) this.loadAll();
|
||||
if (this.isLoaded) this.loadFromContextNamespaces();
|
||||
|
||||
return response;
|
||||
}
|
||||
@@ -105,7 +109,7 @@ export class ReleaseStore extends ItemStore<HelmRelease> {
|
||||
async rollback(name: string, namespace: string, revision: number) {
|
||||
const response = await helmReleasesApi.rollback(name, namespace, revision);
|
||||
|
||||
if (this.isLoaded) this.loadAll();
|
||||
if (this.isLoaded) this.loadFromContextNamespaces();
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
@@ -14,11 +14,13 @@ import { ItemListLayout } from "../item-object-list/item-list-layout";
|
||||
import { HelmReleaseMenu } from "./release-menu";
|
||||
import { secretsStore } from "../+config-secrets/secrets.store";
|
||||
|
||||
enum sortBy {
|
||||
enum columnId {
|
||||
name = "name",
|
||||
namespace = "namespace",
|
||||
revision = "revision",
|
||||
chart = "chart",
|
||||
version = "version",
|
||||
appVersion = "app-version",
|
||||
status = "status",
|
||||
updated = "update"
|
||||
}
|
||||
@@ -81,16 +83,18 @@ export class HelmReleases extends Component<Props> {
|
||||
return (
|
||||
<>
|
||||
<ItemListLayout
|
||||
isConfigurable
|
||||
tableId="helm_releases"
|
||||
className="HelmReleases"
|
||||
store={releaseStore}
|
||||
dependentStores={[secretsStore]}
|
||||
sortingCallbacks={{
|
||||
[sortBy.name]: (release: HelmRelease) => release.getName(),
|
||||
[sortBy.namespace]: (release: HelmRelease) => release.getNs(),
|
||||
[sortBy.revision]: (release: HelmRelease) => release.getRevision(),
|
||||
[sortBy.chart]: (release: HelmRelease) => release.getChart(),
|
||||
[sortBy.status]: (release: HelmRelease) => release.getStatus(),
|
||||
[sortBy.updated]: (release: HelmRelease) => release.getUpdated(false, false),
|
||||
[columnId.name]: (release: HelmRelease) => release.getName(),
|
||||
[columnId.namespace]: (release: HelmRelease) => release.getNs(),
|
||||
[columnId.revision]: (release: HelmRelease) => release.getRevision(),
|
||||
[columnId.chart]: (release: HelmRelease) => release.getChart(),
|
||||
[columnId.status]: (release: HelmRelease) => release.getStatus(),
|
||||
[columnId.updated]: (release: HelmRelease) => release.getUpdated(false, false),
|
||||
}}
|
||||
searchFilters={[
|
||||
(release: HelmRelease) => release.getName(),
|
||||
@@ -101,14 +105,14 @@ export class HelmReleases extends Component<Props> {
|
||||
]}
|
||||
renderHeaderTitle="Releases"
|
||||
renderTableHeader={[
|
||||
{ title: "Name", className: "name", sortBy: sortBy.name },
|
||||
{ title: "Namespace", className: "namespace", sortBy: sortBy.namespace },
|
||||
{ title: "Chart", className: "chart", sortBy: sortBy.chart },
|
||||
{ title: "Revision", className: "revision", sortBy: sortBy.revision },
|
||||
{ title: "Version", className: "version" },
|
||||
{ title: "App Version", className: "app-version" },
|
||||
{ title: "Status", className: "status", sortBy: sortBy.status },
|
||||
{ title: "Updated", className: "updated", sortBy: sortBy.updated },
|
||||
{ title: "Name", className: "name", sortBy: columnId.name, id: columnId.name },
|
||||
{ title: "Namespace", className: "namespace", sortBy: columnId.namespace, id: columnId.namespace },
|
||||
{ title: "Chart", className: "chart", sortBy: columnId.chart, id: columnId.chart },
|
||||
{ title: "Revision", className: "revision", sortBy: columnId.revision, id: columnId.revision },
|
||||
{ title: "Version", className: "version", id: columnId.version },
|
||||
{ title: "App Version", className: "app-version", id: columnId.appVersion },
|
||||
{ title: "Status", className: "status", sortBy: columnId.status, id: columnId.status },
|
||||
{ title: "Updated", className: "updated", sortBy: columnId.updated, id: columnId.updated },
|
||||
]}
|
||||
renderTableContents={(release: HelmRelease) => {
|
||||
const version = release.getVersion();
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { navigate } from "../../navigation";
|
||||
import { commandRegistry } from "../../../extensions/registries/command-registry";
|
||||
import { helmChartsURL } from "../+apps-helm-charts";
|
||||
import { releaseURL } from "../+apps-releases";
|
||||
|
||||
commandRegistry.add({
|
||||
id: "cluster.viewHelmCharts",
|
||||
title: "Cluster: View Helm Charts",
|
||||
scope: "cluster",
|
||||
action: () => navigate(helmChartsURL())
|
||||
});
|
||||
|
||||
commandRegistry.add({
|
||||
id: "cluster.viewHelmReleases",
|
||||
title: "Cluster: View Helm Releases",
|
||||
scope: "cluster",
|
||||
action: () => navigate(releaseURL())
|
||||
});
|
||||
@@ -1,2 +1,3 @@
|
||||
export * from "./apps";
|
||||
export * from "./apps.route";
|
||||
export * from "./apps.route";
|
||||
export * from "./apps.command";
|
||||
@@ -0,0 +1,16 @@
|
||||
import { navigate } from "../../navigation";
|
||||
import { commandRegistry } from "../../../extensions/registries/command-registry";
|
||||
import { clusterSettingsURL } from "./cluster-settings.route";
|
||||
import { clusterStore } from "../../../common/cluster-store";
|
||||
|
||||
commandRegistry.add({
|
||||
id: "cluster.viewCurrentClusterSettings",
|
||||
title: "Cluster: View Settings",
|
||||
scope: "global",
|
||||
action: () => navigate(clusterSettingsURL({
|
||||
params: {
|
||||
clusterId: clusterStore.active.id
|
||||
}
|
||||
})),
|
||||
isActive: (context) => !!context.cluster
|
||||
});
|
||||
@@ -48,4 +48,4 @@ export class ClusterHomeDirSetting extends React.Component<Props> {
|
||||
</>
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -45,4 +45,4 @@ export class ClusterNameSetting extends React.Component<Props> {
|
||||
</>
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -45,4 +45,4 @@ export class ClusterProxySetting extends React.Component<Props> {
|
||||
</>
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,5 @@
|
||||
import React from "react";
|
||||
import { observer } from "mobx-react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { workspacesURL } from "../../+workspaces";
|
||||
import { workspaceStore } from "../../../../common/workspace-store";
|
||||
import { Cluster } from "../../../../main/cluster";
|
||||
import { Select } from "../../../components/select";
|
||||
@@ -18,10 +16,7 @@ export class ClusterWorkspaceSetting extends React.Component<Props> {
|
||||
<>
|
||||
<SubTitle title="Cluster Workspace"/>
|
||||
<p>
|
||||
Define cluster{" "}
|
||||
<Link to={workspacesURL()}>
|
||||
workspace
|
||||
</Link>.
|
||||
Define cluster workspace.
|
||||
</p>
|
||||
<Select
|
||||
value={this.props.cluster.workspace}
|
||||
|
||||
@@ -25,4 +25,4 @@ export class General extends React.Component<Props> {
|
||||
<ClusterAccessibleNamespaces cluster={this.props.cluster} />
|
||||
</div>;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,2 +1,3 @@
|
||||
export * from "./cluster-settings.route";
|
||||
export * from "./cluster-settings";
|
||||
export * from "./cluster-settings.command";
|
||||
@@ -17,4 +17,4 @@ export class Removal extends React.Component<Props> {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -58,4 +58,4 @@ export class Status extends React.Component<Props> {
|
||||
</div>
|
||||
</div>;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -23,11 +23,13 @@ interface IWarning extends ItemObject {
|
||||
kind: string;
|
||||
message: string;
|
||||
selfLink: string;
|
||||
age: string | number;
|
||||
}
|
||||
|
||||
enum sortBy {
|
||||
type = "type",
|
||||
object = "object"
|
||||
object = "object",
|
||||
age = "age",
|
||||
}
|
||||
|
||||
@observer
|
||||
@@ -35,6 +37,7 @@ export class ClusterIssues extends React.Component<Props> {
|
||||
private sortCallbacks = {
|
||||
[sortBy.type]: (warning: IWarning) => warning.kind,
|
||||
[sortBy.object]: (warning: IWarning) => warning.getName(),
|
||||
[sortBy.age]: (warning: IWarning) => warning.age || "",
|
||||
};
|
||||
|
||||
@computed get warnings() {
|
||||
@@ -42,15 +45,16 @@ export class ClusterIssues extends React.Component<Props> {
|
||||
|
||||
// Node bad conditions
|
||||
nodesStore.items.forEach(node => {
|
||||
const { kind, selfLink, getId, getName } = node;
|
||||
const { kind, selfLink, getId, getName, getAge } = node;
|
||||
|
||||
node.getWarningConditions().forEach(({ message }) => {
|
||||
warnings.push({
|
||||
kind,
|
||||
age: getAge(),
|
||||
getId,
|
||||
getName,
|
||||
selfLink,
|
||||
kind,
|
||||
message,
|
||||
selfLink,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -59,12 +63,13 @@ export class ClusterIssues extends React.Component<Props> {
|
||||
const events = eventStore.getWarnings();
|
||||
|
||||
events.forEach(error => {
|
||||
const { message, involvedObject } = error;
|
||||
const { message, involvedObject, getAge } = error;
|
||||
const { uid, name, kind } = involvedObject;
|
||||
|
||||
warnings.push({
|
||||
getId: () => uid,
|
||||
getName: () => name,
|
||||
age: getAge(),
|
||||
message,
|
||||
kind,
|
||||
selfLink: lookupApiLink(involvedObject, error),
|
||||
@@ -78,7 +83,7 @@ export class ClusterIssues extends React.Component<Props> {
|
||||
getTableRow(uid: string) {
|
||||
const { warnings } = this;
|
||||
const warning = warnings.find(warn => warn.getId() == uid);
|
||||
const { getId, getName, message, kind, selfLink } = warning;
|
||||
const { getId, getName, message, kind, selfLink, age } = warning;
|
||||
|
||||
return (
|
||||
<TableRow
|
||||
@@ -96,6 +101,9 @@ export class ClusterIssues extends React.Component<Props> {
|
||||
<TableCell className="kind">
|
||||
{kind}
|
||||
</TableCell>
|
||||
<TableCell className="age">
|
||||
{age}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
}
|
||||
@@ -139,6 +147,7 @@ export class ClusterIssues extends React.Component<Props> {
|
||||
<TableCell className="message">Message</TableCell>
|
||||
<TableCell className="object" sortBy={sortBy.object}>Object</TableCell>
|
||||
<TableCell className="kind" sortBy={sortBy.type}>Type</TableCell>
|
||||
<TableCell className="timestamp" sortBy={sortBy.age}>Age</TableCell>
|
||||
</TableHead>
|
||||
</Table>
|
||||
</>
|
||||
|
||||
@@ -95,4 +95,4 @@ export const ClusterMetrics = observer(() => {
|
||||
{renderMetrics()}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -3,13 +3,9 @@ import "./cluster-overview.scss";
|
||||
import React from "react";
|
||||
import { reaction } from "mobx";
|
||||
import { disposeOnUnmount, observer } from "mobx-react";
|
||||
|
||||
import { eventStore } from "../+events/event.store";
|
||||
import { nodesStore } from "../+nodes/nodes.store";
|
||||
import { podsStore } from "../+workloads-pods/pods.store";
|
||||
import { getHostedCluster } from "../../../common/cluster-store";
|
||||
import { isAllowedResource } from "../../../common/rbac";
|
||||
import { KubeObjectStore } from "../../kube-object.store";
|
||||
import { interval } from "../../utils";
|
||||
import { TabLayout } from "../layout/tab-layout";
|
||||
import { Spinner } from "../spinner";
|
||||
@@ -20,42 +16,24 @@ import { ClusterPieCharts } from "./cluster-pie-charts";
|
||||
|
||||
@observer
|
||||
export class ClusterOverview extends React.Component {
|
||||
private stores: KubeObjectStore<any>[] = [];
|
||||
private subscribers: Array<() => void> = [];
|
||||
private metricPoller = interval(60, this.loadMetrics);
|
||||
|
||||
@disposeOnUnmount
|
||||
fetchMetrics = reaction(
|
||||
() => clusterOverviewStore.metricNodeRole, // Toggle Master/Worker node switcher
|
||||
() => this.metricPoller.restart(true)
|
||||
);
|
||||
private metricPoller = interval(60, () => this.loadMetrics());
|
||||
|
||||
loadMetrics() {
|
||||
getHostedCluster().available && clusterOverviewStore.loadMetrics();
|
||||
}
|
||||
|
||||
async componentDidMount() {
|
||||
if (isAllowedResource("nodes")) {
|
||||
this.stores.push(nodesStore);
|
||||
}
|
||||
componentDidMount() {
|
||||
this.metricPoller.start(true);
|
||||
|
||||
if (isAllowedResource("pods")) {
|
||||
this.stores.push(podsStore);
|
||||
}
|
||||
|
||||
if (isAllowedResource("events")) {
|
||||
this.stores.push(eventStore);
|
||||
}
|
||||
|
||||
await Promise.all(this.stores.map(store => store.loadAll()));
|
||||
this.loadMetrics();
|
||||
|
||||
this.subscribers = this.stores.map(store => store.subscribe());
|
||||
this.metricPoller.start();
|
||||
disposeOnUnmount(this, [
|
||||
reaction(
|
||||
() => clusterOverviewStore.metricNodeRole, // Toggle Master/Worker node switcher
|
||||
() => this.metricPoller.restart(true)
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
this.subscribers.forEach(dispose => dispose()); // unsubscribe all
|
||||
this.metricPoller.stop();
|
||||
}
|
||||
|
||||
|
||||
@@ -143,7 +143,7 @@ export const ClusterPieCharts = observer(() => {
|
||||
<div className="chart flex column align-center box grow">
|
||||
<PieChart
|
||||
data={cpuData}
|
||||
title={`CPU`}
|
||||
title="CPU"
|
||||
legendColors={["#c93dce", "#4caf50", "#3d90ce", defaultColor]}
|
||||
/>
|
||||
{cpuLimitsOverload && renderLimitWarning()}
|
||||
@@ -151,7 +151,7 @@ export const ClusterPieCharts = observer(() => {
|
||||
<div className="chart flex column align-center box grow">
|
||||
<PieChart
|
||||
data={memoryData}
|
||||
title={`Memory`}
|
||||
title="Memory"
|
||||
legendColors={["#c93dce", "#4caf50", "#3d90ce", defaultColor]}
|
||||
/>
|
||||
{memoryLimitsOverload && renderLimitWarning()}
|
||||
@@ -159,7 +159,7 @@ export const ClusterPieCharts = observer(() => {
|
||||
<div className="chart flex column align-center box grow">
|
||||
<PieChart
|
||||
data={podsData}
|
||||
title={`Pods`}
|
||||
title="Pods"
|
||||
legendColors={["#4caf50", defaultColor]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -11,13 +11,15 @@ import { Badge } from "../badge";
|
||||
import { cssNames } from "../../utils";
|
||||
import { KubeObjectStatusIcon } from "../kube-object-status-icon";
|
||||
|
||||
enum sortBy {
|
||||
enum columnId {
|
||||
name = "name",
|
||||
namespace = "namespace",
|
||||
metrics = "metrics",
|
||||
minPods = "min-pods",
|
||||
maxPods = "max-pods",
|
||||
replicas = "replicas",
|
||||
age = "age",
|
||||
status = "status"
|
||||
}
|
||||
|
||||
interface Props extends RouteComponentProps<IHpaRouteParams> {
|
||||
@@ -37,28 +39,30 @@ export class HorizontalPodAutoscalers extends React.Component<Props> {
|
||||
render() {
|
||||
return (
|
||||
<KubeObjectListLayout
|
||||
isConfigurable
|
||||
tableId="configuration_hpa"
|
||||
className="HorizontalPodAutoscalers" store={hpaStore}
|
||||
sortingCallbacks={{
|
||||
[sortBy.name]: (item: HorizontalPodAutoscaler) => item.getName(),
|
||||
[sortBy.namespace]: (item: HorizontalPodAutoscaler) => item.getNs(),
|
||||
[sortBy.minPods]: (item: HorizontalPodAutoscaler) => item.getMinPods(),
|
||||
[sortBy.maxPods]: (item: HorizontalPodAutoscaler) => item.getMaxPods(),
|
||||
[sortBy.replicas]: (item: HorizontalPodAutoscaler) => item.getReplicas()
|
||||
[columnId.name]: (item: HorizontalPodAutoscaler) => item.getName(),
|
||||
[columnId.namespace]: (item: HorizontalPodAutoscaler) => item.getNs(),
|
||||
[columnId.minPods]: (item: HorizontalPodAutoscaler) => item.getMinPods(),
|
||||
[columnId.maxPods]: (item: HorizontalPodAutoscaler) => item.getMaxPods(),
|
||||
[columnId.replicas]: (item: HorizontalPodAutoscaler) => item.getReplicas()
|
||||
}}
|
||||
searchFilters={[
|
||||
(item: HorizontalPodAutoscaler) => item.getSearchFields()
|
||||
]}
|
||||
renderHeaderTitle="Horizontal Pod Autoscalers"
|
||||
renderTableHeader={[
|
||||
{ title: "Name", className: "name", sortBy: sortBy.name },
|
||||
{ className: "warning" },
|
||||
{ title: "Namespace", className: "namespace", sortBy: sortBy.namespace },
|
||||
{ title: "Metrics", className: "metrics" },
|
||||
{ title: "Min Pods", className: "min-pods", sortBy: sortBy.minPods },
|
||||
{ title: "Max Pods", className: "max-pods", sortBy: sortBy.maxPods },
|
||||
{ title: "Replicas", className: "replicas", sortBy: sortBy.replicas },
|
||||
{ title: "Age", className: "age", sortBy: sortBy.age },
|
||||
{ title: "Status", className: "status" },
|
||||
{ title: "Name", className: "name", sortBy: columnId.name },
|
||||
{ className: "warning", showWithColumn: columnId.name },
|
||||
{ title: "Namespace", className: "namespace", sortBy: columnId.namespace, id: columnId.namespace },
|
||||
{ title: "Metrics", className: "metrics", id: columnId.metrics },
|
||||
{ title: "Min Pods", className: "min-pods", sortBy: columnId.minPods, id: columnId.minPods },
|
||||
{ title: "Max Pods", className: "max-pods", sortBy: columnId.maxPods, id: columnId.maxPods },
|
||||
{ title: "Replicas", className: "replicas", sortBy: columnId.replicas, id: columnId.replicas },
|
||||
{ title: "Age", className: "age", sortBy: columnId.age, id: columnId.age },
|
||||
{ title: "Status", className: "status", id: columnId.status },
|
||||
]}
|
||||
renderTableContents={(hpa: HorizontalPodAutoscaler) => [
|
||||
hpa.getName(),
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
export * from "./limit-ranges";
|
||||
export * from "./limit-ranges.route";
|
||||
export * from "./limit-range-details";
|
||||
Loaded 100 of 383 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user