mirror of
https://github.com/lensapp/lens.git
synced 2025-05-20 05:10:56 +00:00
Merge branch 'master' into feature/lens-proxy-tls
Signed-off-by: Jari Kolehmainen <jari.kolehmainen@gmail.com>
This commit is contained in:
commit
17477c4fd7
303 files changed
+14249
-3205
No files matched your search
@@ -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");
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
@@ -175,4 +175,4 @@ export function validateKubeConfig (config: KubeConfig) {
|
||||
throw new ExecValidationNotFoundError(execCommand, isAbsolute);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
+27
-26
@@ -7,37 +7,38 @@ export type KubeResource =
|
||||
"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: "limitranges" },
|
||||
{ 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;
|
||||
@@ -84,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;
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
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/log.store";
|
||||
export { logTabStore } from "../../renderer/components/dock/log-tab.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");
|
||||
|
||||
+68
-10
@@ -1,20 +1,78 @@
|
||||
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
|
||||
function handleAutoUpdateBackChannel(event: Electron.IpcMainEvent, ...[arg]: UpdateAvailableToBackchannel) {
|
||||
if (arg.doUpdate) {
|
||||
if (arg.now) {
|
||||
logger.info(`${AutoUpdateLogPrefix}: User chose to update now`);
|
||||
autoUpdater.downloadUpdate()
|
||||
.then(() => autoUpdater.quitAndInstall())
|
||||
.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`);
|
||||
}
|
||||
}
|
||||
|
||||
static checkForUpdates() {
|
||||
return autoUpdater.checkForUpdatesAndNotify();
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
autoUpdater.logger = logger;
|
||||
autoUpdater.autoDownload = false;
|
||||
autoUpdater.autoInstallOnAppQuit = false;
|
||||
|
||||
autoUpdater
|
||||
.on("update-available", (args: UpdateInfo) => {
|
||||
try {
|
||||
const backchannel = `auto-update:${args.version}`;
|
||||
|
||||
constructor(protected updateInterval = AppUpdater.defaultUpdateIntervalMs) {
|
||||
autoUpdater.logger = logger;
|
||||
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 });
|
||||
}
|
||||
});
|
||||
|
||||
async function helper() {
|
||||
while (true) {
|
||||
await checkForUpdates();
|
||||
await delay(interval);
|
||||
}
|
||||
}
|
||||
|
||||
helper();
|
||||
}
|
||||
|
||||
public start() {
|
||||
setInterval(AppUpdater.checkForUpdates, this.updateInterval);
|
||||
export async function checkForUpdates(): Promise<void> {
|
||||
try {
|
||||
logger.info(`📡 Checking for app updates`);
|
||||
|
||||
return AppUpdater.checkForUpdates();
|
||||
await autoUpdater.checkForUpdates();
|
||||
} catch (error) {
|
||||
logger.error(`${AutoUpdateLogPrefix}: failed with an error`, { error: String(error) });
|
||||
}
|
||||
}
|
||||
@@ -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 => {
|
||||
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(() => {
|
||||
|
||||
+62
-19
@@ -49,6 +49,7 @@ export interface ClusterState {
|
||||
isAdmin: boolean;
|
||||
allowedNamespaces: string[]
|
||||
allowedResources: string[]
|
||||
isGlobalWatchEnabled: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -92,7 +93,6 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
*/
|
||||
@observable initializing = false;
|
||||
|
||||
|
||||
/**
|
||||
* Is cluster object initialized
|
||||
*
|
||||
@@ -178,6 +178,12 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
* @observable
|
||||
*/
|
||||
@observable isAdmin = false;
|
||||
/**
|
||||
* Global watch-api accessibility , e.g. "/api/v1/services?watch=1"
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
@observable isGlobalWatchEnabled = false;
|
||||
/**
|
||||
* Preferences
|
||||
*
|
||||
@@ -191,7 +197,7 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
*/
|
||||
@observable metadata: ClusterMetadata = {};
|
||||
/**
|
||||
* List of allowed namespaces
|
||||
* List of allowed namespaces verified via K8S::SelfSubjectAccessReview api
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
@@ -204,7 +210,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
|
||||
*/
|
||||
@@ -225,7 +231,7 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
* @computed
|
||||
*/
|
||||
@computed get name() {
|
||||
return this.preferences.clusterName || this.contextName;
|
||||
return this.preferences.clusterName || this.contextName;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -280,7 +286,8 @@ 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);
|
||||
@@ -335,7 +342,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();
|
||||
}
|
||||
@@ -352,9 +360,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;
|
||||
@@ -374,7 +380,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();
|
||||
@@ -401,19 +408,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();
|
||||
}
|
||||
@@ -421,7 +427,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;
|
||||
@@ -432,7 +439,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;
|
||||
@@ -442,7 +462,8 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
@action async refreshAllowedResources() {
|
||||
@action
|
||||
async refreshAllowedResources() {
|
||||
this.allowedNamespaces = await this.getAllowedNamespaces();
|
||||
this.allowedResources = await this.getAllowedResources();
|
||||
}
|
||||
@@ -568,6 +589,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,
|
||||
@@ -601,6 +633,7 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
isAdmin: this.isAdmin,
|
||||
allowedNamespaces: this.allowedNamespaces,
|
||||
allowedResources: this.allowedResources,
|
||||
isGlobalWatchEnabled: this.isGlobalWatchEnabled,
|
||||
};
|
||||
|
||||
return toJS(state, {
|
||||
@@ -672,7 +705,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
|
||||
@@ -687,9 +720,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]);
|
||||
|
||||
+27
-5
@@ -10,7 +10,6 @@ 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";
|
||||
@@ -27,6 +26,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;
|
||||
@@ -62,20 +64,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(),
|
||||
@@ -87,6 +89,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);
|
||||
@@ -99,6 +102,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) {
|
||||
@@ -117,9 +121,27 @@ app.on("ready", async () => {
|
||||
}
|
||||
});
|
||||
|
||||
// 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 {
|
||||
|
||||
+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"],
|
||||
|
||||
@@ -30,7 +30,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;
|
||||
}
|
||||
@@ -43,13 +43,13 @@ export class LensProxy {
|
||||
|
||||
protected buildCustomProxy(): http.Server {
|
||||
const proxy = this.createProxy();
|
||||
const proxyCert = getProxyCertificate()
|
||||
const proxyCert = getProxyCertificate();
|
||||
const spdyProxy = spdy.createServer({
|
||||
key: proxyCert.private,
|
||||
cert: proxyCert.cert,
|
||||
spdy: {
|
||||
plain: false,
|
||||
protocols: ["http/1.1", "spdy/3.1"]
|
||||
protocols: ["h2", "http/1.1", "spdy/3.1"]
|
||||
}
|
||||
}, (req: http.IncomingMessage, res: http.ServerResponse) => {
|
||||
this.handleRequest(proxy, req, res);
|
||||
@@ -198,7 +198,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();
|
||||
+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
|
||||
};
|
||||
};
|
||||
@@ -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));
|
||||
@@ -46,12 +46,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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -86,7 +86,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;
|
||||
}
|
||||
|
||||
|
||||
@@ -104,6 +104,9 @@ export interface IPodContainer {
|
||||
configMapRef?: {
|
||||
name: string;
|
||||
};
|
||||
secretRef?: {
|
||||
name: string;
|
||||
}
|
||||
}[];
|
||||
volumeMounts?: {
|
||||
name: string;
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
import { stringify } from "querystring";
|
||||
import { EventEmitter } from "../../common/event-emitter";
|
||||
import { cancelableFetch } from "../utils/cancelableFetch";
|
||||
|
||||
export interface JsonApiData {
|
||||
}
|
||||
|
||||
@@ -55,6 +54,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 = reqPath; //`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" });
|
||||
}
|
||||
|
||||
@@ -9,7 +9,9 @@ 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 byline from "byline";
|
||||
import { ReadableWebToNodeStream } from "readable-web-to-node-stream";
|
||||
import { IKubeWatchEvent } from "./kube-watch-api";
|
||||
|
||||
export interface IKubeApiOptions<T extends KubeObject> {
|
||||
/**
|
||||
@@ -91,15 +93,13 @@ export function ensureObjectSelfLink(api: KubeApi, object: KubeJsonApiData) {
|
||||
}
|
||||
}
|
||||
|
||||
type KubeApiWatchOptions = {
|
||||
namespace: string;
|
||||
callback?: (data: IKubeWatchEvent) => void;
|
||||
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 +112,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 +125,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 +158,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 {
|
||||
@@ -365,8 +366,88 @@ 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();
|
||||
}
|
||||
const { abortController, namespace, callback } = opts;
|
||||
|
||||
const watchUrl = this.getWatchUrl(namespace);
|
||||
const responsePromise = this.request.getResponse(watchUrl, null, {
|
||||
signal: abortController.signal
|
||||
});
|
||||
|
||||
responsePromise.then((response) => {
|
||||
if (!response.ok && !abortController.signal.aborted) {
|
||||
if (response.status === 410) { // resourceVersion has gone
|
||||
setTimeout(() => {
|
||||
this.refreshResourceVersion().then(() => {
|
||||
this.watch({...opts, abortController});
|
||||
});
|
||||
}, 1000);
|
||||
|
||||
} else if (response.status >= 500) { // k8s is having hard time
|
||||
setTimeout(() => {
|
||||
this.watch({...opts, abortController});
|
||||
}, 5000);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
const nodeStream = new ReadableWebToNodeStream(response.body);
|
||||
const stream = byline(nodeStream);
|
||||
|
||||
stream.on("data", (line) => {
|
||||
try {
|
||||
const event: IKubeWatchEvent = JSON.parse(line);
|
||||
|
||||
this.modifyWatchEvent(event);
|
||||
|
||||
if (callback) {
|
||||
callback(event);
|
||||
}
|
||||
} catch (ignore) {
|
||||
// ignore parse errors
|
||||
}
|
||||
});
|
||||
|
||||
stream.on("close", () => {
|
||||
setTimeout(() => {
|
||||
if (!abortController.signal.aborted) this.watch({...opts, namespace, callback});
|
||||
}, 1000);
|
||||
});
|
||||
}, (error) => {
|
||||
if (error instanceof DOMException) return; // AbortController rejects, we can ignore it
|
||||
|
||||
console.error("watch rejected", error);
|
||||
}).catch((error) => {
|
||||
console.error("watch error", 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;
|
||||
};
|
||||
|
||||
+104
-146
@@ -1,183 +1,141 @@
|
||||
// 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> {
|
||||
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";
|
||||
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;
|
||||
@observable subscribers = observable.map<KubeApi, number>();
|
||||
@observable isConnected = false;
|
||||
|
||||
contextReady = when(() => Boolean(this.context));
|
||||
|
||||
constructor() {
|
||||
reaction(() => this.activeApis, () => this.connect(), {
|
||||
fireImmediately: true,
|
||||
delay: 500,
|
||||
});
|
||||
this.init();
|
||||
}
|
||||
|
||||
@computed get activeApis() {
|
||||
return Array.from(this.subscribers.keys());
|
||||
private async init() {
|
||||
await this.contextReady;
|
||||
}
|
||||
|
||||
getSubscribersCount(api: KubeApi) {
|
||||
return this.subscribers.get(api) || 0;
|
||||
isAllowedApi(api: KubeApi): boolean {
|
||||
return Boolean(this.context?.cluster.isAllowedResource(api.kind));
|
||||
}
|
||||
|
||||
subscribe(...apis: KubeApi[]) {
|
||||
apis.forEach(api => {
|
||||
this.subscribers.set(api, this.getSubscribersCount(api) + 1);
|
||||
});
|
||||
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>[] = [];
|
||||
|
||||
return () => apis.forEach(api => {
|
||||
const count = this.getSubscribersCount(api) - 1;
|
||||
for (const store of stores) {
|
||||
preloading.push(limitRequests(async () => {
|
||||
if (store.isLoaded && opts.loadOnce) return; // skip
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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(),
|
||||
@@ -74,13 +79,12 @@ export class HelmCharts extends Component<Props> {
|
||||
<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 +97,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";
|
||||
@@ -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> {
|
||||
@@ -58,38 +58,35 @@ export class ReleaseStore extends ItemStore<HelmRelease> {
|
||||
}
|
||||
|
||||
@action
|
||||
async loadAll() {
|
||||
async loadAll(namespaces = namespaceStore.allowedNamespaces) {
|
||||
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) {
|
||||
return helmReleasesApi.list();
|
||||
} else {
|
||||
return Promise
|
||||
.all(namespaces.map(namespace => helmReleasesApi.list(namespace)))
|
||||
.then(items => items.flat());
|
||||
}
|
||||
async loadFromContextNamespaces(): Promise<void> {
|
||||
return this.loadAll(namespaceStore.contextNamespaces);
|
||||
}
|
||||
|
||||
async loadItems(namespaces: string[]) {
|
||||
return Promise
|
||||
.all(namespaces.map(namespace => helmReleasesApi.list(namespace)))
|
||||
.then(items => items.flat());
|
||||
}
|
||||
|
||||
async create(payload: IReleaseCreatePayload) {
|
||||
const response = await helmReleasesApi.create(payload);
|
||||
|
||||
if (this.isLoaded) this.loadAll();
|
||||
if (this.isLoaded) this.loadFromContextNamespaces();
|
||||
|
||||
return response;
|
||||
}
|
||||
@@ -97,7 +94,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 +102,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();
|
||||
}
|
||||
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -9,7 +9,7 @@ import React from "react";
|
||||
import { KubeObjectStatusIcon } from "../kube-object-status-icon";
|
||||
import { LimitRange } from "../../api/endpoints/limit-range.api";
|
||||
|
||||
enum sortBy {
|
||||
enum columnId {
|
||||
name = "name",
|
||||
namespace = "namespace",
|
||||
age = "age",
|
||||
@@ -23,12 +23,14 @@ export class LimitRanges extends React.Component<Props> {
|
||||
render() {
|
||||
return (
|
||||
<KubeObjectListLayout
|
||||
isConfigurable
|
||||
tableId="configuration_limitranges"
|
||||
className="LimitRanges"
|
||||
store={limitRangeStore}
|
||||
sortingCallbacks={{
|
||||
[sortBy.name]: (item: LimitRange) => item.getName(),
|
||||
[sortBy.namespace]: (item: LimitRange) => item.getNs(),
|
||||
[sortBy.age]: (item: LimitRange) => item.metadata.creationTimestamp,
|
||||
[columnId.name]: (item: LimitRange) => item.getName(),
|
||||
[columnId.namespace]: (item: LimitRange) => item.getNs(),
|
||||
[columnId.age]: (item: LimitRange) => item.metadata.creationTimestamp,
|
||||
}}
|
||||
searchFilters={[
|
||||
(item: LimitRange) => item.getName(),
|
||||
@@ -36,10 +38,10 @@ export class LimitRanges extends React.Component<Props> {
|
||||
]}
|
||||
renderHeaderTitle={"Limit Ranges"}
|
||||
renderTableHeader={[
|
||||
{ title: "Name", className: "name", sortBy: sortBy.name },
|
||||
{ className: "warning" },
|
||||
{ title: "Namespace", className: "namespace", sortBy: sortBy.namespace },
|
||||
{ title: "Age", className: "age", sortBy: sortBy.age },
|
||||
{ title: "Name", className: "name", sortBy: columnId.name, id: columnId.name },
|
||||
{ className: "warning", showWithColumn: columnId.name },
|
||||
{ title: "Namespace", className: "namespace", sortBy: columnId.namespace, id: columnId.namespace },
|
||||
{ title: "Age", className: "age", sortBy: columnId.age, id: columnId.age },
|
||||
]}
|
||||
renderTableContents={(limitRange: LimitRange) => [
|
||||
limitRange.getName(),
|
||||
|
||||
@@ -9,7 +9,7 @@ import { KubeObjectListLayout } from "../kube-object";
|
||||
import { IConfigMapsRouteParams } from "./config-maps.route";
|
||||
import { KubeObjectStatusIcon } from "../kube-object-status-icon";
|
||||
|
||||
enum sortBy {
|
||||
enum columnId {
|
||||
name = "name",
|
||||
namespace = "namespace",
|
||||
keys = "keys",
|
||||
@@ -24,12 +24,14 @@ export class ConfigMaps extends React.Component<Props> {
|
||||
render() {
|
||||
return (
|
||||
<KubeObjectListLayout
|
||||
isConfigurable
|
||||
tableId="configuration_configmaps"
|
||||
className="ConfigMaps" store={configMapsStore}
|
||||
sortingCallbacks={{
|
||||
[sortBy.name]: (item: ConfigMap) => item.getName(),
|
||||
[sortBy.namespace]: (item: ConfigMap) => item.getNs(),
|
||||
[sortBy.keys]: (item: ConfigMap) => item.getKeys(),
|
||||
[sortBy.age]: (item: ConfigMap) => item.metadata.creationTimestamp,
|
||||
[columnId.name]: (item: ConfigMap) => item.getName(),
|
||||
[columnId.namespace]: (item: ConfigMap) => item.getNs(),
|
||||
[columnId.keys]: (item: ConfigMap) => item.getKeys(),
|
||||
[columnId.age]: (item: ConfigMap) => item.metadata.creationTimestamp,
|
||||
}}
|
||||
searchFilters={[
|
||||
(item: ConfigMap) => item.getSearchFields(),
|
||||
@@ -37,11 +39,11 @@ export class ConfigMaps extends React.Component<Props> {
|
||||
]}
|
||||
renderHeaderTitle="Config Maps"
|
||||
renderTableHeader={[
|
||||
{ title: "Name", className: "name", sortBy: sortBy.name },
|
||||
{ className: "warning" },
|
||||
{ title: "Namespace", className: "namespace", sortBy: sortBy.namespace },
|
||||
{ title: "Keys", className: "keys", sortBy: sortBy.keys },
|
||||
{ title: "Age", className: "age", sortBy: sortBy.age },
|
||||
{ title: "Name", className: "name", sortBy: columnId.name, id: columnId.name },
|
||||
{ className: "warning", showWithColumn: columnId.name },
|
||||
{ title: "Namespace", className: "namespace", sortBy: columnId.namespace, id: columnId.namespace },
|
||||
{ title: "Keys", className: "keys", sortBy: columnId.keys, id: columnId.keys },
|
||||
{ title: "Age", className: "age", sortBy: columnId.age, id: columnId.age },
|
||||
]}
|
||||
renderTableContents={(configMap: ConfigMap) => [
|
||||
configMap.getName(),
|
||||
|
||||
@@ -7,7 +7,7 @@ import { PodDisruptionBudget } from "../../api/endpoints/poddisruptionbudget.api
|
||||
import { KubeObjectDetailsProps, KubeObjectListLayout } from "../kube-object";
|
||||
import { KubeObjectStatusIcon } from "../kube-object-status-icon";
|
||||
|
||||
enum sortBy {
|
||||
enum columnId {
|
||||
name = "name",
|
||||
namespace = "namespace",
|
||||
minAvailable = "min-available",
|
||||
@@ -25,30 +25,32 @@ export class PodDisruptionBudgets extends React.Component<Props> {
|
||||
render() {
|
||||
return (
|
||||
<KubeObjectListLayout
|
||||
isConfigurable
|
||||
tableId="configuration_distribution_budgets"
|
||||
className="PodDisruptionBudgets"
|
||||
store={podDisruptionBudgetsStore}
|
||||
sortingCallbacks={{
|
||||
[sortBy.name]: (pdb: PodDisruptionBudget) => pdb.getName(),
|
||||
[sortBy.namespace]: (pdb: PodDisruptionBudget) => pdb.getNs(),
|
||||
[sortBy.minAvailable]: (pdb: PodDisruptionBudget) => pdb.getMinAvailable(),
|
||||
[sortBy.maxUnavailable]: (pdb: PodDisruptionBudget) => pdb.getMaxUnavailable(),
|
||||
[sortBy.currentHealthy]: (pdb: PodDisruptionBudget) => pdb.getCurrentHealthy(),
|
||||
[sortBy.desiredHealthy]: (pdb: PodDisruptionBudget) => pdb.getDesiredHealthy(),
|
||||
[sortBy.age]: (pdb: PodDisruptionBudget) => pdb.getAge(),
|
||||
[columnId.name]: (pdb: PodDisruptionBudget) => pdb.getName(),
|
||||
[columnId.namespace]: (pdb: PodDisruptionBudget) => pdb.getNs(),
|
||||
[columnId.minAvailable]: (pdb: PodDisruptionBudget) => pdb.getMinAvailable(),
|
||||
[columnId.maxUnavailable]: (pdb: PodDisruptionBudget) => pdb.getMaxUnavailable(),
|
||||
[columnId.currentHealthy]: (pdb: PodDisruptionBudget) => pdb.getCurrentHealthy(),
|
||||
[columnId.desiredHealthy]: (pdb: PodDisruptionBudget) => pdb.getDesiredHealthy(),
|
||||
[columnId.age]: (pdb: PodDisruptionBudget) => pdb.getAge(),
|
||||
}}
|
||||
searchFilters={[
|
||||
(pdb: PodDisruptionBudget) => pdb.getSearchFields(),
|
||||
]}
|
||||
renderHeaderTitle="Pod Disruption Budgets"
|
||||
renderTableHeader={[
|
||||
{ title: "Name", className: "name", sortBy: sortBy.name },
|
||||
{ className: "warning" },
|
||||
{ title: "Namespace", className: "namespace", sortBy: sortBy.namespace },
|
||||
{ title: "Min Available", className: "min-available", sortBy: sortBy.minAvailable },
|
||||
{ title: "Max Unavailable", className: "max-unavailable", sortBy: sortBy.maxUnavailable },
|
||||
{ title: "Current Healthy", className: "current-healthy", sortBy: sortBy.currentHealthy },
|
||||
{ title: "Desired Healthy", className: "desired-healthy", sortBy: sortBy.desiredHealthy },
|
||||
{ title: "Age", className: "age", sortBy: sortBy.age },
|
||||
{ title: "Name", className: "name", sortBy: columnId.name, id: columnId.name },
|
||||
{ className: "warning", showWithColumn: columnId.name },
|
||||
{ title: "Namespace", className: "namespace", sortBy: columnId.namespace, id: columnId.namespace },
|
||||
{ title: "Min Available", className: "min-available", sortBy: columnId.minAvailable, id: columnId.minAvailable },
|
||||
{ title: "Max Unavailable", className: "max-unavailable", sortBy: columnId.maxUnavailable, id: columnId.maxUnavailable },
|
||||
{ title: "Current Healthy", className: "current-healthy", sortBy: columnId.currentHealthy, id: columnId.currentHealthy },
|
||||
{ title: "Desired Healthy", className: "desired-healthy", sortBy: columnId.desiredHealthy, id: columnId.desiredHealthy },
|
||||
{ title: "Age", className: "age", sortBy: columnId.age, id: columnId.age },
|
||||
]}
|
||||
renderTableContents={(pdb: PodDisruptionBudget) => {
|
||||
return [
|
||||
|
||||
@@ -10,7 +10,7 @@ import { resourceQuotaStore } from "./resource-quotas.store";
|
||||
import { IResourceQuotaRouteParams } from "./resource-quotas.route";
|
||||
import { KubeObjectStatusIcon } from "../kube-object-status-icon";
|
||||
|
||||
enum sortBy {
|
||||
enum columnId {
|
||||
name = "name",
|
||||
namespace = "namespace",
|
||||
age = "age"
|
||||
@@ -25,11 +25,13 @@ export class ResourceQuotas extends React.Component<Props> {
|
||||
return (
|
||||
<>
|
||||
<KubeObjectListLayout
|
||||
isConfigurable
|
||||
tableId="configuration_quotas"
|
||||
className="ResourceQuotas" store={resourceQuotaStore}
|
||||
sortingCallbacks={{
|
||||
[sortBy.name]: (item: ResourceQuota) => item.getName(),
|
||||
[sortBy.namespace]: (item: ResourceQuota) => item.getNs(),
|
||||
[sortBy.age]: (item: ResourceQuota) => item.metadata.creationTimestamp,
|
||||
[columnId.name]: (item: ResourceQuota) => item.getName(),
|
||||
[columnId.namespace]: (item: ResourceQuota) => item.getNs(),
|
||||
[columnId.age]: (item: ResourceQuota) => item.metadata.creationTimestamp,
|
||||
}}
|
||||
searchFilters={[
|
||||
(item: ResourceQuota) => item.getSearchFields(),
|
||||
@@ -37,10 +39,10 @@ export class ResourceQuotas extends React.Component<Props> {
|
||||
]}
|
||||
renderHeaderTitle="Resource Quotas"
|
||||
renderTableHeader={[
|
||||
{ title: "Name", className: "name", sortBy: sortBy.name },
|
||||
{ className: "warning" },
|
||||
{ title: "Namespace", className: "namespace", sortBy: sortBy.namespace },
|
||||
{ title: "Age", className: "age", sortBy: sortBy.age },
|
||||
{ title: "Name", className: "name", sortBy: columnId.name, id: columnId.name },
|
||||
{ className: "warning", showWithColumn: columnId.name },
|
||||
{ title: "Namespace", className: "namespace", sortBy: columnId.namespace, id: columnId.namespace },
|
||||
{ title: "Age", className: "age", sortBy: columnId.age, id: columnId.age },
|
||||
]}
|
||||
renderTableContents={(resourceQuota: ResourceQuota) => [
|
||||
resourceQuota.getName(),
|
||||
|
||||
@@ -11,7 +11,7 @@ import { Badge } from "../badge";
|
||||
import { secretsStore } from "./secrets.store";
|
||||
import { KubeObjectStatusIcon } from "../kube-object-status-icon";
|
||||
|
||||
enum sortBy {
|
||||
enum columnId {
|
||||
name = "name",
|
||||
namespace = "namespace",
|
||||
labels = "labels",
|
||||
@@ -29,14 +29,16 @@ export class Secrets extends React.Component<Props> {
|
||||
return (
|
||||
<>
|
||||
<KubeObjectListLayout
|
||||
isConfigurable
|
||||
tableId="configuration_secrets"
|
||||
className="Secrets" store={secretsStore}
|
||||
sortingCallbacks={{
|
||||
[sortBy.name]: (item: Secret) => item.getName(),
|
||||
[sortBy.namespace]: (item: Secret) => item.getNs(),
|
||||
[sortBy.labels]: (item: Secret) => item.getLabels(),
|
||||
[sortBy.keys]: (item: Secret) => item.getKeys(),
|
||||
[sortBy.type]: (item: Secret) => item.type,
|
||||
[sortBy.age]: (item: Secret) => item.metadata.creationTimestamp,
|
||||
[columnId.name]: (item: Secret) => item.getName(),
|
||||
[columnId.namespace]: (item: Secret) => item.getNs(),
|
||||
[columnId.labels]: (item: Secret) => item.getLabels(),
|
||||
[columnId.keys]: (item: Secret) => item.getKeys(),
|
||||
[columnId.type]: (item: Secret) => item.type,
|
||||
[columnId.age]: (item: Secret) => item.metadata.creationTimestamp,
|
||||
}}
|
||||
searchFilters={[
|
||||
(item: Secret) => item.getSearchFields(),
|
||||
@@ -44,13 +46,13 @@ export class Secrets extends React.Component<Props> {
|
||||
]}
|
||||
renderHeaderTitle="Secrets"
|
||||
renderTableHeader={[
|
||||
{ title: "Name", className: "name", sortBy: sortBy.name },
|
||||
{ className: "warning" },
|
||||
{ title: "Namespace", className: "namespace", sortBy: sortBy.namespace },
|
||||
{ title: "Labels", className: "labels", sortBy: sortBy.labels },
|
||||
{ title: "Keys", className: "keys", sortBy: sortBy.keys },
|
||||
{ title: "Type", className: "type", sortBy: sortBy.type },
|
||||
{ title: "Age", className: "age", sortBy: sortBy.age },
|
||||
{ title: "Name", className: "name", sortBy: columnId.name, id: columnId.name },
|
||||
{ className: "warning", showWithColumn: columnId.name },
|
||||
{ title: "Namespace", className: "namespace", sortBy: columnId.namespace, id: columnId.namespace },
|
||||
{ title: "Labels", className: "labels", sortBy: columnId.labels, id: columnId.labels },
|
||||
{ title: "Keys", className: "keys", sortBy: columnId.keys, id: columnId.keys },
|
||||
{ title: "Type", className: "type", sortBy: columnId.type, id: columnId.type },
|
||||
{ title: "Age", className: "age", sortBy: columnId.age, id: columnId.age },
|
||||
]}
|
||||
renderTableContents={(secret: Secret) => [
|
||||
secret.getName(),
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import { navigate } from "../../navigation";
|
||||
import { commandRegistry } from "../../../extensions/registries/command-registry";
|
||||
import { configMapsURL } from "../+config-maps";
|
||||
import { secretsURL } from "../+config-secrets";
|
||||
import { resourceQuotaURL } from "../+config-resource-quotas";
|
||||
import { limitRangeURL } from "../+config-limit-ranges";
|
||||
import { hpaURL } from "../+config-autoscalers";
|
||||
import { pdbURL } from "../+config-pod-disruption-budgets";
|
||||
|
||||
commandRegistry.add({
|
||||
id: "cluster.viewConfigMaps",
|
||||
title: "Cluster: View ConfigMaps",
|
||||
scope: "cluster",
|
||||
action: () => navigate(configMapsURL())
|
||||
});
|
||||
|
||||
commandRegistry.add({
|
||||
id: "cluster.viewSecrets",
|
||||
title: "Cluster: View Secrets",
|
||||
scope: "cluster",
|
||||
action: () => navigate(secretsURL())
|
||||
});
|
||||
|
||||
commandRegistry.add({
|
||||
id: "cluster.viewResourceQuotas",
|
||||
title: "Cluster: View ResourceQuotas",
|
||||
scope: "cluster",
|
||||
action: () => navigate(resourceQuotaURL())
|
||||
});
|
||||
|
||||
commandRegistry.add({
|
||||
id: "cluster.viewLimitRanges",
|
||||
title: "Cluster: View LimitRanges",
|
||||
scope: "cluster",
|
||||
action: () => navigate(limitRangeURL())
|
||||
});
|
||||
|
||||
commandRegistry.add({
|
||||
id: "cluster.viewHorizontalPodAutoscalers",
|
||||
title: "Cluster: View HorizontalPodAutoscalers (HPA)",
|
||||
scope: "cluster",
|
||||
action: () => navigate(hpaURL())
|
||||
});
|
||||
|
||||
commandRegistry.add({
|
||||
id: "cluster.viewPodDisruptionBudget",
|
||||
title: "Cluster: View PodDisruptionBudgets",
|
||||
scope: "cluster",
|
||||
action: () => navigate(pdbURL())
|
||||
});
|
||||
@@ -1,2 +1,3 @@
|
||||
export * from "./config.route";
|
||||
export * from "./config";
|
||||
export * from "./config.command";
|
||||
@@ -19,7 +19,7 @@ export const crdGroupsUrlParam = createPageParam<string[]>({
|
||||
defaultValue: [],
|
||||
});
|
||||
|
||||
enum sortBy {
|
||||
enum columnId {
|
||||
kind = "kind",
|
||||
group = "group",
|
||||
version = "version",
|
||||
@@ -47,14 +47,16 @@ export class CrdList extends React.Component {
|
||||
render() {
|
||||
const selectedGroups = this.groups;
|
||||
const sortingCallbacks = {
|
||||
[sortBy.kind]: (crd: CustomResourceDefinition) => crd.getResourceKind(),
|
||||
[sortBy.group]: (crd: CustomResourceDefinition) => crd.getGroup(),
|
||||
[sortBy.version]: (crd: CustomResourceDefinition) => crd.getVersion(),
|
||||
[sortBy.scope]: (crd: CustomResourceDefinition) => crd.getScope(),
|
||||
[columnId.kind]: (crd: CustomResourceDefinition) => crd.getResourceKind(),
|
||||
[columnId.group]: (crd: CustomResourceDefinition) => crd.getGroup(),
|
||||
[columnId.version]: (crd: CustomResourceDefinition) => crd.getVersion(),
|
||||
[columnId.scope]: (crd: CustomResourceDefinition) => crd.getScope(),
|
||||
};
|
||||
|
||||
return (
|
||||
<KubeObjectListLayout
|
||||
isConfigurable
|
||||
tableId="crd"
|
||||
className="CrdList"
|
||||
isClusterScoped={true}
|
||||
store={crdStore}
|
||||
@@ -97,11 +99,11 @@ export class CrdList extends React.Component {
|
||||
};
|
||||
}}
|
||||
renderTableHeader={[
|
||||
{ title: "Resource", className: "kind", sortBy: sortBy.kind },
|
||||
{ title: "Group", className: "group", sortBy: sortBy.group },
|
||||
{ title: "Version", className: "version", sortBy: sortBy.group },
|
||||
{ title: "Scope", className: "scope", sortBy: sortBy.scope },
|
||||
{ title: "Age", className: "age", sortBy: sortBy.age },
|
||||
{ title: "Resource", className: "kind", sortBy: columnId.kind, id: columnId.kind },
|
||||
{ title: "Group", className: "group", sortBy: columnId.group, id: columnId.group },
|
||||
{ title: "Version", className: "version", sortBy: columnId.version, id: columnId.version },
|
||||
{ title: "Scope", className: "scope", sortBy: columnId.scope, id: columnId.scope },
|
||||
{ title: "Age", className: "age", sortBy: columnId.age, id: columnId.age },
|
||||
]}
|
||||
renderTableContents={(crd: CustomResourceDefinition) => [
|
||||
<Link key="link" to={crd.getResourceUrl()} onClick={stopPropagation}>
|
||||
|
||||
@@ -16,7 +16,7 @@ import { parseJsonPath } from "../../utils/jsonPath";
|
||||
interface Props extends RouteComponentProps<ICRDRouteParams> {
|
||||
}
|
||||
|
||||
enum sortBy {
|
||||
enum columnId {
|
||||
name = "name",
|
||||
namespace = "namespace",
|
||||
age = "age",
|
||||
@@ -30,7 +30,7 @@ export class CrdResources extends React.Component<Props> {
|
||||
const { store } = this;
|
||||
|
||||
if (store && !store.isLoading && !store.isLoaded) {
|
||||
store.loadAll();
|
||||
store.reloadAll();
|
||||
}
|
||||
})
|
||||
]);
|
||||
@@ -55,9 +55,9 @@ export class CrdResources extends React.Component<Props> {
|
||||
const isNamespaced = crd.isNamespaced();
|
||||
const extraColumns = crd.getPrinterColumns(false); // Cols with priority bigger than 0 are shown in details
|
||||
const sortingCallbacks: { [sortBy: string]: TableSortCallback } = {
|
||||
[sortBy.name]: (item: KubeObject) => item.getName(),
|
||||
[sortBy.namespace]: (item: KubeObject) => item.getNs(),
|
||||
[sortBy.age]: (item: KubeObject) => item.metadata.creationTimestamp,
|
||||
[columnId.name]: (item: KubeObject) => item.getName(),
|
||||
[columnId.namespace]: (item: KubeObject) => item.getNs(),
|
||||
[columnId.age]: (item: KubeObject) => item.metadata.creationTimestamp,
|
||||
};
|
||||
|
||||
extraColumns.forEach(column => {
|
||||
@@ -66,6 +66,8 @@ export class CrdResources extends React.Component<Props> {
|
||||
|
||||
return (
|
||||
<KubeObjectListLayout
|
||||
isConfigurable
|
||||
tableId="crd_resources"
|
||||
className="CrdResources"
|
||||
isClusterScoped={!isNamespaced}
|
||||
store={store}
|
||||
@@ -75,18 +77,19 @@ export class CrdResources extends React.Component<Props> {
|
||||
]}
|
||||
renderHeaderTitle={crd.getResourceTitle()}
|
||||
renderTableHeader={[
|
||||
{ title: "Name", className: "name", sortBy: sortBy.name },
|
||||
isNamespaced && { title: "Namespace", className: "namespace", sortBy: sortBy.namespace },
|
||||
{ title: "Name", className: "name", sortBy: columnId.name, id: columnId.name },
|
||||
isNamespaced && { title: "Namespace", className: "namespace", sortBy: columnId.namespace, id: columnId.namespace },
|
||||
...extraColumns.map(column => {
|
||||
const { name } = column;
|
||||
|
||||
return {
|
||||
title: name,
|
||||
className: name.toLowerCase(),
|
||||
sortBy: name
|
||||
sortBy: name,
|
||||
id: name
|
||||
};
|
||||
}),
|
||||
{ title: "Age", className: "age", sortBy: sortBy.age },
|
||||
{ title: "Age", className: "age", sortBy: columnId.age, id: columnId.age },
|
||||
]}
|
||||
renderTableContents={(crdInstance: KubeObject) => [
|
||||
crdInstance.getName(),
|
||||
@@ -94,7 +97,7 @@ export class CrdResources extends React.Component<Props> {
|
||||
...extraColumns.map((column) => {
|
||||
let value = jsonPath.value(crdInstance, parseJsonPath(column.jsonPath.slice(1)));
|
||||
|
||||
if (Array.isArray(value) || typeof value === "object") {
|
||||
if (Array.isArray(value) || typeof value === "object") {
|
||||
value = JSON.stringify(value);
|
||||
}
|
||||
|
||||
|
||||
@@ -52,6 +52,10 @@ export class EventStore extends KubeObjectStore<KubeEvent> {
|
||||
|
||||
return compact(eventsWithError);
|
||||
}
|
||||
|
||||
getWarningsCount() {
|
||||
return this.getWarnings().length;
|
||||
}
|
||||
}
|
||||
|
||||
export const eventStore = new EventStore();
|
||||
|
||||
@@ -12,11 +12,13 @@ import { cssNames, IClassName, stopPropagation } from "../../utils";
|
||||
import { Icon } from "../icon";
|
||||
import { lookupApiLink } from "../../api/kube-api";
|
||||
|
||||
enum sortBy {
|
||||
enum columnId {
|
||||
message = "message",
|
||||
namespace = "namespace",
|
||||
object = "object",
|
||||
type = "type",
|
||||
count = "count",
|
||||
source = "source",
|
||||
age = "age",
|
||||
}
|
||||
|
||||
@@ -39,15 +41,17 @@ export class Events extends React.Component<Props> {
|
||||
const events = (
|
||||
<KubeObjectListLayout
|
||||
{...layoutProps}
|
||||
isConfigurable
|
||||
tableId="events"
|
||||
className={cssNames("Events", className, { compact })}
|
||||
store={eventStore}
|
||||
isSelectable={false}
|
||||
sortingCallbacks={{
|
||||
[sortBy.namespace]: (event: KubeEvent) => event.getNs(),
|
||||
[sortBy.type]: (event: KubeEvent) => event.involvedObject.kind,
|
||||
[sortBy.object]: (event: KubeEvent) => event.involvedObject.name,
|
||||
[sortBy.count]: (event: KubeEvent) => event.count,
|
||||
[sortBy.age]: (event: KubeEvent) => event.metadata.creationTimestamp,
|
||||
[columnId.namespace]: (event: KubeEvent) => event.getNs(),
|
||||
[columnId.type]: (event: KubeEvent) => event.involvedObject.kind,
|
||||
[columnId.object]: (event: KubeEvent) => event.involvedObject.name,
|
||||
[columnId.count]: (event: KubeEvent) => event.count,
|
||||
[columnId.age]: (event: KubeEvent) => event.metadata.creationTimestamp,
|
||||
}}
|
||||
searchFilters={[
|
||||
(event: KubeEvent) => event.getSearchFields(),
|
||||
@@ -72,13 +76,13 @@ export class Events extends React.Component<Props> {
|
||||
})
|
||||
)}
|
||||
renderTableHeader={[
|
||||
{ title: "Message", className: "message" },
|
||||
{ title: "Namespace", className: "namespace", sortBy: sortBy.namespace },
|
||||
{ title: "Type", className: "type", sortBy: sortBy.type },
|
||||
{ title: "Involved Object", className: "object", sortBy: sortBy.object },
|
||||
{ title: "Source", className: "source" },
|
||||
{ title: "Count", className: "count", sortBy: sortBy.count },
|
||||
{ title: "Age", className: "age", sortBy: sortBy.age },
|
||||
{ title: "Message", className: "message", id: columnId.message },
|
||||
{ title: "Namespace", className: "namespace", sortBy: columnId.namespace, id: columnId.namespace },
|
||||
{ title: "Type", className: "type", sortBy: columnId.type, id: columnId.type },
|
||||
{ title: "Involved Object", className: "object", sortBy: columnId.object, id: columnId.object },
|
||||
{ title: "Source", className: "source", id: columnId.source },
|
||||
{ title: "Count", className: "count", sortBy: columnId.count, id: columnId.count },
|
||||
{ title: "Age", className: "age", sortBy: columnId.age, id: columnId.age },
|
||||
]}
|
||||
renderTableContents={(event: KubeEvent) => {
|
||||
const { involvedObject, type, message } = event;
|
||||
|
||||
@@ -14,7 +14,7 @@ export interface KubeEventDetailsProps {
|
||||
@observer
|
||||
export class KubeEventDetails extends React.Component<KubeEventDetailsProps> {
|
||||
async componentDidMount() {
|
||||
eventStore.loadAll();
|
||||
eventStore.reloadAll();
|
||||
}
|
||||
|
||||
render() {
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
export * from "./landing-page.route";
|
||||
export * from "./landing-page";
|
||||
export * from "./landing-page";
|
||||
@@ -32,8 +32,8 @@ export class NamespaceDetails extends React.Component<Props> {
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
resourceQuotaStore.loadAll();
|
||||
limitRangeStore.loadAll();
|
||||
resourceQuotaStore.reloadAll();
|
||||
limitRangeStore.reloadAll();
|
||||
}
|
||||
|
||||
render() {
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import "./namespace-select.scss";
|
||||
|
||||
import React from "react";
|
||||
import { observer } from "mobx-react";
|
||||
import { components, PlaceholderProps } from "react-select";
|
||||
|
||||
import { Icon } from "../icon";
|
||||
import { FilterIcon } from "../item-object-list/filter-icon";
|
||||
import { FilterType } from "../item-object-list/page-filters.store";
|
||||
import { SelectOption } from "../select";
|
||||
import { NamespaceSelect } from "./namespace-select";
|
||||
import { namespaceStore } from "./namespace.store";
|
||||
|
||||
const Placeholder = observer((props: PlaceholderProps<any>) => {
|
||||
const getPlaceholder = (): React.ReactNode => {
|
||||
const namespaces = namespaceStore.contextNamespaces;
|
||||
|
||||
switch (namespaces.length) {
|
||||
case 0:
|
||||
case namespaceStore.allowedNamespaces.length:
|
||||
return <>All namespaces</>;
|
||||
case 1:
|
||||
return <>Namespace: {namespaces[0]}</>;
|
||||
default:
|
||||
return <>Namespaces: {namespaces.join(", ")}</>;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<components.Placeholder {...props}>
|
||||
{getPlaceholder()}
|
||||
</components.Placeholder>
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@observer
|
||||
export class NamespaceSelectFilter extends React.Component {
|
||||
formatOptionLabel({ value: namespace, label }: SelectOption) {
|
||||
if (namespace) {
|
||||
const isSelected = namespaceStore.hasContext(namespace);
|
||||
|
||||
return (
|
||||
<div className="flex gaps align-center">
|
||||
<FilterIcon type={FilterType.NAMESPACE}/>
|
||||
<span>{namespace}</span>
|
||||
{isSelected && <Icon small material="check" className="box right"/>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return label;
|
||||
}
|
||||
|
||||
onChange([{ value: namespace }]: SelectOption[]) {
|
||||
if (namespace) {
|
||||
namespaceStore.toggleContext(namespace);
|
||||
} else {
|
||||
namespaceStore.resetContext(); // "All namespaces" clicked, empty list considered as "all"
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<NamespaceSelect
|
||||
isMulti={true}
|
||||
components={{ Placeholder }}
|
||||
showAllNamespacesOption={true}
|
||||
closeMenuOnSelect={false}
|
||||
controlShouldRenderValue={false}
|
||||
placeholder={""}
|
||||
onChange={this.onChange}
|
||||
formatOptionLabel={this.formatOptionLabel}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -2,53 +2,49 @@ import "./namespace-select.scss";
|
||||
|
||||
import React from "react";
|
||||
import { computed } from "mobx";
|
||||
import { observer } from "mobx-react";
|
||||
import { disposeOnUnmount, observer } from "mobx-react";
|
||||
import { Select, SelectOption, SelectProps } from "../select";
|
||||
import { cssNames, noop } from "../../utils";
|
||||
import { cssNames } from "../../utils";
|
||||
import { Icon } from "../icon";
|
||||
import { namespaceStore } from "./namespace.store";
|
||||
import { FilterIcon } from "../item-object-list/filter-icon";
|
||||
import { FilterType } from "../item-object-list/page-filters.store";
|
||||
import { kubeWatchApi } from "../../api/kube-watch-api";
|
||||
|
||||
interface Props extends SelectProps {
|
||||
showIcons?: boolean;
|
||||
showClusterOption?: boolean; // show cluster option on the top (default: false)
|
||||
clusterOptionLabel?: React.ReactNode; // label for cluster option (default: "Cluster")
|
||||
customizeOptions?(nsOptions: SelectOption[]): SelectOption[];
|
||||
showClusterOption?: boolean; // show "Cluster" option on the top (default: false)
|
||||
showAllNamespacesOption?: boolean; // show "All namespaces" option on the top (default: false)
|
||||
customizeOptions?(options: SelectOption[]): SelectOption[];
|
||||
}
|
||||
|
||||
const defaultProps: Partial<Props> = {
|
||||
showIcons: true,
|
||||
showClusterOption: false,
|
||||
get clusterOptionLabel() {
|
||||
return `Cluster`;
|
||||
},
|
||||
};
|
||||
|
||||
@observer
|
||||
export class NamespaceSelect extends React.Component<Props> {
|
||||
static defaultProps = defaultProps as object;
|
||||
private unsubscribe = noop;
|
||||
|
||||
async componentDidMount() {
|
||||
if (!namespaceStore.isLoaded) {
|
||||
await namespaceStore.loadAll();
|
||||
}
|
||||
this.unsubscribe = namespaceStore.subscribe();
|
||||
componentDidMount() {
|
||||
disposeOnUnmount(this, [
|
||||
kubeWatchApi.subscribeStores([namespaceStore], {
|
||||
preload: true,
|
||||
})
|
||||
]);
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
this.unsubscribe();
|
||||
}
|
||||
|
||||
@computed get options(): SelectOption[] {
|
||||
const { customizeOptions, showClusterOption, clusterOptionLabel } = this.props;
|
||||
@computed.struct get options(): SelectOption[] {
|
||||
const { customizeOptions, showClusterOption, showAllNamespacesOption } = this.props;
|
||||
let options: SelectOption[] = namespaceStore.items.map(ns => ({ value: ns.getName() }));
|
||||
|
||||
options = customizeOptions ? customizeOptions(options) : options;
|
||||
if (showAllNamespacesOption) {
|
||||
options.unshift({ label: "All Namespaces", value: "" });
|
||||
} else if (showClusterOption) {
|
||||
options.unshift({ label: "Cluster", value: "" });
|
||||
}
|
||||
|
||||
if (showClusterOption) {
|
||||
options.unshift({ value: null, label: clusterOptionLabel });
|
||||
if (customizeOptions) {
|
||||
options = customizeOptions(options);
|
||||
}
|
||||
|
||||
return options;
|
||||
@@ -60,14 +56,14 @@ export class NamespaceSelect extends React.Component<Props> {
|
||||
|
||||
return label || (
|
||||
<>
|
||||
{showIcons && <Icon small material="layers" />}
|
||||
{showIcons && <Icon small material="layers"/>}
|
||||
{value}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
render() {
|
||||
const { className, showIcons, showClusterOption, clusterOptionLabel, customizeOptions, ...selectProps } = this.props;
|
||||
const { className, showIcons, customizeOptions, ...selectProps } = this.props;
|
||||
|
||||
return (
|
||||
<Select
|
||||
@@ -80,36 +76,3 @@ export class NamespaceSelect extends React.Component<Props> {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@observer
|
||||
export class NamespaceSelectFilter extends React.Component {
|
||||
render() {
|
||||
const { contextNs, hasContext, toggleContext } = namespaceStore;
|
||||
let placeholder = <>All namespaces</>;
|
||||
|
||||
if (contextNs.length == 1) placeholder = <>Namespace: {contextNs[0]}</>;
|
||||
if (contextNs.length >= 2) placeholder = <>Namespaces: {contextNs.join(", ")}</>;
|
||||
|
||||
return (
|
||||
<NamespaceSelect
|
||||
placeholder={placeholder}
|
||||
closeMenuOnSelect={false}
|
||||
isOptionSelected={() => false}
|
||||
controlShouldRenderValue={false}
|
||||
isMulti
|
||||
onChange={([{ value }]: SelectOption[]) => toggleContext(value)}
|
||||
formatOptionLabel={({ value: namespace }: SelectOption) => {
|
||||
const isSelected = hasContext(namespace);
|
||||
|
||||
return (
|
||||
<div className="flex gaps align-center">
|
||||
<FilterIcon type={FilterType.NAMESPACE} />
|
||||
<span>{namespace}</span>
|
||||
{isSelected && <Icon small material="check" className="box right" />}
|
||||
</div>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,9 @@
|
||||
import { action, comparer, observable, reaction } from "mobx";
|
||||
import { action, comparer, computed, IReactionDisposer, IReactionOptions, observable, reaction } from "mobx";
|
||||
import { autobind, createStorage } from "../../utils";
|
||||
import { KubeObjectStore } from "../../kube-object.store";
|
||||
import { Namespace, namespacesApi } from "../../api/endpoints";
|
||||
import { KubeObjectStore, KubeObjectStoreLoadingParams } from "../../kube-object.store";
|
||||
import { Namespace, namespacesApi } from "../../api/endpoints/namespaces.api";
|
||||
import { createPageParam } from "../../navigation";
|
||||
import { apiManager } from "../../api/api-manager";
|
||||
import { isAllowedResource } from "../../../common/rbac";
|
||||
import { getHostedCluster } from "../../../common/cluster-store";
|
||||
|
||||
const storage = createStorage<string[]>("context_namespaces", []);
|
||||
|
||||
@@ -14,107 +12,171 @@ export const namespaceUrlParam = createPageParam<string[]>({
|
||||
isSystem: true,
|
||||
multiValues: true,
|
||||
get defaultValue() {
|
||||
return storage.get(); // initial namespaces coming from URL or local-storage (default)
|
||||
return storage.get() ?? []; // initial namespaces coming from URL or local-storage (default)
|
||||
}
|
||||
});
|
||||
|
||||
export function getDummyNamespace(name: string) {
|
||||
return new Namespace({
|
||||
kind: Namespace.kind,
|
||||
apiVersion: "v1",
|
||||
metadata: {
|
||||
name,
|
||||
uid: "",
|
||||
resourceVersion: "",
|
||||
selfLink: `/api/v1/namespaces/${name}`
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@autobind()
|
||||
export class NamespaceStore extends KubeObjectStore<Namespace> {
|
||||
api = namespacesApi;
|
||||
contextNs = observable.array<string>();
|
||||
|
||||
@observable private contextNs = observable.set<string>();
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this.init();
|
||||
}
|
||||
|
||||
private init() {
|
||||
this.setContext(this.initNamespaces);
|
||||
private async init() {
|
||||
await this.contextReady;
|
||||
|
||||
return reaction(() => this.contextNs.toJS(), namespaces => {
|
||||
this.setContext(this.initialNamespaces);
|
||||
this.autoLoadAllowedNamespaces();
|
||||
this.autoUpdateUrlAndLocalStorage();
|
||||
}
|
||||
|
||||
public onContextChange(callback: (contextNamespaces: string[]) => void, opts: IReactionOptions = {}): IReactionDisposer {
|
||||
return reaction(() => Array.from(this.contextNs), callback, {
|
||||
equals: comparer.shallow,
|
||||
...opts,
|
||||
});
|
||||
}
|
||||
|
||||
private autoUpdateUrlAndLocalStorage(): IReactionDisposer {
|
||||
return this.onContextChange(namespaces => {
|
||||
storage.set(namespaces); // save to local-storage
|
||||
namespaceUrlParam.set(namespaces, { replaceHistory: true }); // update url
|
||||
}, {
|
||||
fireImmediately: true,
|
||||
equals: comparer.identity,
|
||||
});
|
||||
}
|
||||
|
||||
get initNamespaces() {
|
||||
return namespaceUrlParam.get();
|
||||
private autoLoadAllowedNamespaces(): IReactionDisposer {
|
||||
return reaction(() => this.allowedNamespaces, namespaces => this.loadAll({ namespaces }), {
|
||||
fireImmediately: true,
|
||||
equals: comparer.shallow,
|
||||
});
|
||||
}
|
||||
|
||||
getContextParams() {
|
||||
return {
|
||||
namespaces: this.contextNs.toJS(),
|
||||
};
|
||||
}
|
||||
@computed
|
||||
private get initialNamespaces(): string[] {
|
||||
const namespaces = new Set(this.allowedNamespaces);
|
||||
const prevSelected = storage.get().filter(namespace => namespaces.has(namespace));
|
||||
|
||||
subscribe(apis = [this.api]) {
|
||||
const { accessibleNamespaces } = getHostedCluster();
|
||||
|
||||
// if user has given static list of namespaces let's not start watches because watch adds stuff that's not wanted
|
||||
if (accessibleNamespaces.length > 0) {
|
||||
return Function; // no-op
|
||||
// return previously saved namespaces from local-storage
|
||||
if (prevSelected.length > 0) {
|
||||
return prevSelected;
|
||||
}
|
||||
|
||||
return super.subscribe(apis);
|
||||
// otherwise select "default" or first allowed namespace
|
||||
if (namespaces.has("default")) {
|
||||
return ["default"];
|
||||
} else if (namespaces.size) {
|
||||
return [Array.from(namespaces)[0]];
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
protected async loadItems(namespaces?: string[]) {
|
||||
if (!isAllowedResource("namespaces")) {
|
||||
if (namespaces) return namespaces.map(this.getDummyNamespace);
|
||||
@computed get allowedNamespaces(): string[] {
|
||||
return Array.from(new Set([
|
||||
...(this.context?.allNamespaces ?? []), // allowed namespaces from cluster (main), updating every 30s
|
||||
...this.items.map(item => item.getName()), // loaded namespaces from k8s api
|
||||
].flat()));
|
||||
}
|
||||
|
||||
@computed get contextNamespaces(): string[] {
|
||||
const namespaces = Array.from(this.contextNs);
|
||||
|
||||
if (!namespaces.length) {
|
||||
return this.allowedNamespaces; // show all namespaces when nothing selected
|
||||
}
|
||||
|
||||
return namespaces;
|
||||
}
|
||||
|
||||
getSubscribeApis() {
|
||||
// if user has given static list of namespaces let's not start watches because watch adds stuff that's not wanted
|
||||
if (this.context?.cluster.accessibleNamespaces.length > 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (namespaces) {
|
||||
return Promise.all(namespaces.map(name => this.api.get({ name })));
|
||||
} else {
|
||||
return super.loadItems();
|
||||
}
|
||||
return super.getSubscribeApis();
|
||||
}
|
||||
|
||||
protected getDummyNamespace(name: string) {
|
||||
return new Namespace({
|
||||
kind: "Namespace",
|
||||
apiVersion: "v1",
|
||||
metadata: {
|
||||
name,
|
||||
uid: "",
|
||||
resourceVersion: "",
|
||||
selfLink: `/api/v1/namespaces/${name}`
|
||||
}
|
||||
});
|
||||
protected async loadItems(params: KubeObjectStoreLoadingParams) {
|
||||
const { allowedNamespaces } = this;
|
||||
|
||||
let namespaces = await super.loadItems(params);
|
||||
|
||||
namespaces = namespaces.filter(namespace => allowedNamespaces.includes(namespace.getName()));
|
||||
|
||||
if (!namespaces.length && allowedNamespaces.length > 0) {
|
||||
return allowedNamespaces.map(getDummyNamespace);
|
||||
}
|
||||
|
||||
return namespaces;
|
||||
}
|
||||
|
||||
@action
|
||||
setContext(namespaces: string[]) {
|
||||
setContext(namespace: string | string[]) {
|
||||
const namespaces = [namespace].flat();
|
||||
|
||||
this.contextNs.replace(namespaces);
|
||||
}
|
||||
|
||||
hasContext(namespace: string | string[]) {
|
||||
const context = Array.isArray(namespace) ? namespace : [namespace];
|
||||
@action
|
||||
resetContext() {
|
||||
this.contextNs.clear();
|
||||
}
|
||||
|
||||
return context.every(namespace => this.contextNs.includes(namespace));
|
||||
hasContext(namespaces: string | string[]) {
|
||||
return [namespaces].flat().every(namespace => this.contextNs.has(namespace));
|
||||
}
|
||||
|
||||
@computed get hasAllContexts(): boolean {
|
||||
return this.contextNs.size === this.allowedNamespaces.length;
|
||||
}
|
||||
|
||||
@action
|
||||
toggleContext(namespace: string) {
|
||||
if (this.hasContext(namespace)) this.contextNs.remove(namespace);
|
||||
else this.contextNs.push(namespace);
|
||||
if (this.hasContext(namespace)) {
|
||||
this.contextNs.delete(namespace);
|
||||
} else {
|
||||
this.contextNs.add(namespace);
|
||||
}
|
||||
}
|
||||
|
||||
@action
|
||||
reset() {
|
||||
super.reset();
|
||||
this.contextNs.clear();
|
||||
toggleAll(showAll?: boolean) {
|
||||
if (typeof showAll === "boolean") {
|
||||
if (showAll) {
|
||||
this.setContext(this.allowedNamespaces);
|
||||
} else {
|
||||
this.contextNs.clear();
|
||||
}
|
||||
} else {
|
||||
this.toggleAll(!this.hasAllContexts);
|
||||
}
|
||||
}
|
||||
|
||||
@action
|
||||
async remove(item: Namespace) {
|
||||
await super.remove(item);
|
||||
this.contextNs.remove(item.getName());
|
||||
this.contextNs.delete(item.getName());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ import { INamespacesRouteParams } from "./namespaces.route";
|
||||
import { namespaceStore } from "./namespace.store";
|
||||
import { KubeObjectStatusIcon } from "../kube-object-status-icon";
|
||||
|
||||
enum sortBy {
|
||||
enum columnId {
|
||||
name = "name",
|
||||
labels = "labels",
|
||||
age = "age",
|
||||
@@ -27,12 +27,14 @@ export class Namespaces extends React.Component<Props> {
|
||||
<TabLayout>
|
||||
<KubeObjectListLayout
|
||||
isClusterScoped
|
||||
isConfigurable
|
||||
tableId="namespaces"
|
||||
className="Namespaces" store={namespaceStore}
|
||||
sortingCallbacks={{
|
||||
[sortBy.name]: (ns: Namespace) => ns.getName(),
|
||||
[sortBy.labels]: (ns: Namespace) => ns.getLabels(),
|
||||
[sortBy.age]: (ns: Namespace) => ns.metadata.creationTimestamp,
|
||||
[sortBy.status]: (ns: Namespace) => ns.getStatus(),
|
||||
[columnId.name]: (ns: Namespace) => ns.getName(),
|
||||
[columnId.labels]: (ns: Namespace) => ns.getLabels(),
|
||||
[columnId.age]: (ns: Namespace) => ns.metadata.creationTimestamp,
|
||||
[columnId.status]: (ns: Namespace) => ns.getStatus(),
|
||||
}}
|
||||
searchFilters={[
|
||||
(item: Namespace) => item.getSearchFields(),
|
||||
@@ -40,11 +42,11 @@ export class Namespaces extends React.Component<Props> {
|
||||
]}
|
||||
renderHeaderTitle="Namespaces"
|
||||
renderTableHeader={[
|
||||
{ title: "Name", className: "name", sortBy: sortBy.name },
|
||||
{ className: "warning" },
|
||||
{ title: "Labels", className: "labels", sortBy: sortBy.labels },
|
||||
{ title: "Age", className: "age", sortBy: sortBy.age },
|
||||
{ title: "Status", className: "status", sortBy: sortBy.status },
|
||||
{ title: "Name", className: "name", sortBy: columnId.name, id: columnId.name },
|
||||
{ className: "warning", showWithColumn: columnId.name },
|
||||
{ title: "Labels", className: "labels", sortBy: columnId.labels, id: columnId.labels },
|
||||
{ title: "Age", className: "age", sortBy: columnId.age, id: columnId.age },
|
||||
{ title: "Status", className: "status", sortBy: columnId.status, id: columnId.status },
|
||||
]}
|
||||
renderTableContents={(item: Namespace) => [
|
||||
item.getName(),
|
||||
|
||||
@@ -9,9 +9,10 @@ import { endpointStore } from "./endpoints.store";
|
||||
import { KubeObjectListLayout } from "../kube-object";
|
||||
import { KubeObjectStatusIcon } from "../kube-object-status-icon";
|
||||
|
||||
enum sortBy {
|
||||
enum columnId {
|
||||
name = "name",
|
||||
namespace = "namespace",
|
||||
endpoints = "endpoints",
|
||||
age = "age",
|
||||
}
|
||||
|
||||
@@ -23,22 +24,24 @@ export class Endpoints extends React.Component<Props> {
|
||||
render() {
|
||||
return (
|
||||
<KubeObjectListLayout
|
||||
isConfigurable
|
||||
tableId="network_endpoints"
|
||||
className="Endpoints" store={endpointStore}
|
||||
sortingCallbacks={{
|
||||
[sortBy.name]: (endpoint: Endpoint) => endpoint.getName(),
|
||||
[sortBy.namespace]: (endpoint: Endpoint) => endpoint.getNs(),
|
||||
[sortBy.age]: (endpoint: Endpoint) => endpoint.metadata.creationTimestamp,
|
||||
[columnId.name]: (endpoint: Endpoint) => endpoint.getName(),
|
||||
[columnId.namespace]: (endpoint: Endpoint) => endpoint.getNs(),
|
||||
[columnId.age]: (endpoint: Endpoint) => endpoint.metadata.creationTimestamp,
|
||||
}}
|
||||
searchFilters={[
|
||||
(endpoint: Endpoint) => endpoint.getSearchFields()
|
||||
]}
|
||||
renderHeaderTitle="Endpoints"
|
||||
renderTableHeader={[
|
||||
{ title: "Name", className: "name", sortBy: sortBy.name },
|
||||
{ className: "warning" },
|
||||
{ title: "Namespace", className: "namespace", sortBy: sortBy.namespace },
|
||||
{ title: "Endpoints", className: "endpoints" },
|
||||
{ title: "Age", className: "age", sortBy: sortBy.age },
|
||||
{ title: "Name", className: "name", sortBy: columnId.name, id: columnId.name },
|
||||
{ className: "warning", showWithColumn: columnId.name },
|
||||
{ title: "Namespace", className: "namespace", sortBy: columnId.namespace, id: columnId.namespace },
|
||||
{ title: "Endpoints", className: "endpoints", id: columnId.endpoints },
|
||||
{ title: "Age", className: "age", sortBy: columnId.age, id: columnId.age },
|
||||
]}
|
||||
renderTableContents={(endpoint: Endpoint) => [
|
||||
endpoint.getName(),
|
||||
|
||||
@@ -9,9 +9,11 @@ import { ingressStore } from "./ingress.store";
|
||||
import { KubeObjectListLayout } from "../kube-object";
|
||||
import { KubeObjectStatusIcon } from "../kube-object-status-icon";
|
||||
|
||||
enum sortBy {
|
||||
enum columnId {
|
||||
name = "name",
|
||||
namespace = "namespace",
|
||||
loadBalancers ="load-balancers",
|
||||
rules = "rules",
|
||||
age = "age",
|
||||
}
|
||||
|
||||
@@ -23,11 +25,13 @@ export class Ingresses extends React.Component<Props> {
|
||||
render() {
|
||||
return (
|
||||
<KubeObjectListLayout
|
||||
isConfigurable
|
||||
tableId="network_ingresses"
|
||||
className="Ingresses" store={ingressStore}
|
||||
sortingCallbacks={{
|
||||
[sortBy.name]: (ingress: Ingress) => ingress.getName(),
|
||||
[sortBy.namespace]: (ingress: Ingress) => ingress.getNs(),
|
||||
[sortBy.age]: (ingress: Ingress) => ingress.metadata.creationTimestamp,
|
||||
[columnId.name]: (ingress: Ingress) => ingress.getName(),
|
||||
[columnId.namespace]: (ingress: Ingress) => ingress.getNs(),
|
||||
[columnId.age]: (ingress: Ingress) => ingress.metadata.creationTimestamp,
|
||||
}}
|
||||
searchFilters={[
|
||||
(ingress: Ingress) => ingress.getSearchFields(),
|
||||
@@ -35,12 +39,12 @@ export class Ingresses extends React.Component<Props> {
|
||||
]}
|
||||
renderHeaderTitle="Ingresses"
|
||||
renderTableHeader={[
|
||||
{ title: "Name", className: "name", sortBy: sortBy.name },
|
||||
{ className: "warning" },
|
||||
{ title: "Namespace", className: "namespace", sortBy: sortBy.namespace },
|
||||
{ title: "LoadBalancers", className: "loadbalancers" },
|
||||
{ title: "Rules", className: "rules" },
|
||||
{ title: "Age", className: "age", sortBy: sortBy.age },
|
||||
{ title: "Name", className: "name", sortBy: columnId.name, id: columnId.name },
|
||||
{ className: "warning", showWithColumn: columnId.name },
|
||||
{ title: "Namespace", className: "namespace", sortBy: columnId.namespace, id: columnId.namespace },
|
||||
{ title: "LoadBalancers", className: "loadbalancers", id: columnId.loadBalancers },
|
||||
{ title: "Rules", className: "rules", id: columnId.rules },
|
||||
{ title: "Age", className: "age", sortBy: columnId.age, id: columnId.age },
|
||||
]}
|
||||
renderTableContents={(ingress: Ingress) => [
|
||||
ingress.getName(),
|
||||
|
||||
@@ -9,9 +9,10 @@ import { INetworkPoliciesRouteParams } from "./network-policies.route";
|
||||
import { networkPolicyStore } from "./network-policy.store";
|
||||
import { KubeObjectStatusIcon } from "../kube-object-status-icon";
|
||||
|
||||
enum sortBy {
|
||||
enum columnId {
|
||||
name = "name",
|
||||
namespace = "namespace",
|
||||
types = "types",
|
||||
age = "age",
|
||||
}
|
||||
|
||||
@@ -23,22 +24,24 @@ export class NetworkPolicies extends React.Component<Props> {
|
||||
render() {
|
||||
return (
|
||||
<KubeObjectListLayout
|
||||
isConfigurable
|
||||
tableId="network_policies"
|
||||
className="NetworkPolicies" store={networkPolicyStore}
|
||||
sortingCallbacks={{
|
||||
[sortBy.name]: (item: NetworkPolicy) => item.getName(),
|
||||
[sortBy.namespace]: (item: NetworkPolicy) => item.getNs(),
|
||||
[sortBy.age]: (item: NetworkPolicy) => item.metadata.creationTimestamp,
|
||||
[columnId.name]: (item: NetworkPolicy) => item.getName(),
|
||||
[columnId.namespace]: (item: NetworkPolicy) => item.getNs(),
|
||||
[columnId.age]: (item: NetworkPolicy) => item.metadata.creationTimestamp,
|
||||
}}
|
||||
searchFilters={[
|
||||
(item: NetworkPolicy) => item.getSearchFields(),
|
||||
]}
|
||||
renderHeaderTitle="Network Policies"
|
||||
renderTableHeader={[
|
||||
{ title: "Name", className: "name", sortBy: sortBy.name },
|
||||
{ className: "warning" },
|
||||
{ title: "Namespace", className: "namespace", sortBy: sortBy.namespace },
|
||||
{ title: "Policy Types", className: "type" },
|
||||
{ title: "Age", className: "age", sortBy: sortBy.age },
|
||||
{ title: "Name", className: "name", sortBy: columnId.name, id: columnId.name },
|
||||
{ className: "warning", showWithColumn: columnId.name },
|
||||
{ title: "Namespace", className: "namespace", sortBy: columnId.namespace, id: columnId.namespace },
|
||||
{ title: "Policy Types", className: "type", id: columnId.types },
|
||||
{ title: "Age", className: "age", sortBy: columnId.age, id: columnId.age },
|
||||
]}
|
||||
renderTableContents={(item: NetworkPolicy) => [
|
||||
item.getName(),
|
||||
|
||||
Loaded 100 of 303 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user