mirror of
https://github.com/lensapp/lens.git
synced 2025-05-20 05:10:56 +00:00
merge master
Signed-off-by: Jari Kolehmainen <jari.kolehmainen@gmail.com>
This commit is contained in:
commit
5b0efe2c86
372 files changed
+37735
-4427
No files matched your search
@@ -0,0 +1,80 @@
|
||||
/**
|
||||
* @jest-environment jsdom
|
||||
*/
|
||||
|
||||
import { SearchStore } from "../search-store"
|
||||
|
||||
let searchStore: SearchStore = null;
|
||||
|
||||
const logs = [
|
||||
"1:M 30 Oct 2020 16:17:41.553 # Connection with replica 172.17.0.12:6379 lost",
|
||||
"1:M 30 Oct 2020 16:17:41.623 * Replica 172.17.0.12:6379 asks for synchronization",
|
||||
"1:M 30 Oct 2020 16:17:41.623 * Starting Partial resynchronization request from 172.17.0.12:6379 accepted. Sending 0 bytes of backlog starting from offset 14407."
|
||||
]
|
||||
|
||||
describe("search store tests", () => {
|
||||
beforeEach(async () => {
|
||||
searchStore = new SearchStore();
|
||||
})
|
||||
|
||||
it("does nothing with empty search query", () => {
|
||||
searchStore.onSearch([], "");
|
||||
expect(searchStore.occurrences).toEqual([]);
|
||||
})
|
||||
|
||||
it("doesn't break if no text provided", () => {
|
||||
searchStore.onSearch(null, "replica");
|
||||
expect(searchStore.occurrences).toEqual([]);
|
||||
|
||||
searchStore.onSearch([], "replica");
|
||||
expect(searchStore.occurrences).toEqual([]);
|
||||
})
|
||||
|
||||
it("find 3 occurences across 3 lines", () => {
|
||||
searchStore.onSearch(logs, "172");
|
||||
expect(searchStore.occurrences).toEqual([0, 1, 2]);
|
||||
})
|
||||
|
||||
it("find occurences within 1 line (case-insensitive)", () => {
|
||||
searchStore.onSearch(logs, "Starting");
|
||||
expect(searchStore.occurrences).toEqual([2, 2]);
|
||||
})
|
||||
|
||||
it("sets overlay index equal to first occurence", () => {
|
||||
searchStore.onSearch(logs, "Replica");
|
||||
expect(searchStore.activeOverlayIndex).toBe(0);
|
||||
})
|
||||
|
||||
it("set overlay index to next occurence", () => {
|
||||
searchStore.onSearch(logs, "172");
|
||||
searchStore.setNextOverlayActive();
|
||||
expect(searchStore.activeOverlayIndex).toBe(1);
|
||||
})
|
||||
|
||||
it("sets overlay to last occurence", () => {
|
||||
searchStore.onSearch(logs, "172");
|
||||
searchStore.setPrevOverlayActive();
|
||||
expect(searchStore.activeOverlayIndex).toBe(2);
|
||||
})
|
||||
|
||||
it("gets line index where overlay is located", () => {
|
||||
searchStore.onSearch(logs, "synchronization");
|
||||
expect(searchStore.activeOverlayLine).toBe(1);
|
||||
})
|
||||
|
||||
it("escapes string for using in regex", () => {
|
||||
const regex = searchStore.escapeRegex("some.interesting-query\\#?()[]");
|
||||
expect(regex).toBe("some\\.interesting\\-query\\\\\\#\\?\\(\\)\\[\\]");
|
||||
})
|
||||
|
||||
it("gets active find number", () => {
|
||||
searchStore.onSearch(logs, "172");
|
||||
searchStore.setNextOverlayActive();
|
||||
expect(searchStore.activeFind).toBe(2);
|
||||
})
|
||||
|
||||
it("gets total finds number", () => {
|
||||
searchStore.onSearch(logs, "Starting");
|
||||
expect(searchStore.totalFinds).toBe(2);
|
||||
})
|
||||
})
|
||||
@@ -57,11 +57,12 @@ describe("user store tests", () => {
|
||||
expect(us.preferences.colorTheme).toBe('light')
|
||||
})
|
||||
|
||||
it("correctly resets theme to default value", () => {
|
||||
it("correctly resets theme to default value", async () => {
|
||||
const us = UserStore.getInstance<UserStore>();
|
||||
us.isLoaded = true;
|
||||
|
||||
us.preferences.colorTheme = "some other theme";
|
||||
us.resetTheme();
|
||||
await us.resetTheme();
|
||||
expect(us.preferences.colorTheme).toBe(UserStore.defaultTheme);
|
||||
})
|
||||
|
||||
|
||||
@@ -38,15 +38,18 @@ describe("workspace store tests", () => {
|
||||
expect(() => ws.removeWorkspaceById(WorkspaceStore.defaultId)).toThrowError("Cannot remove");
|
||||
})
|
||||
|
||||
it("can update default workspace name", () => {
|
||||
it("can update workspace description", () => {
|
||||
const ws = WorkspaceStore.getInstance<WorkspaceStore>();
|
||||
|
||||
ws.addWorkspace(new Workspace({
|
||||
id: WorkspaceStore.defaultId,
|
||||
const workspace = ws.addWorkspace(new Workspace({
|
||||
id: "foobar",
|
||||
name: "foobar",
|
||||
}));
|
||||
|
||||
expect(ws.currentWorkspace.name).toBe("foobar");
|
||||
workspace.description = "Foobar description";
|
||||
ws.updateWorkspace(workspace);
|
||||
|
||||
expect(ws.getById("foobar").description).toBe("Foobar description");
|
||||
})
|
||||
|
||||
it("can add workspaces", () => {
|
||||
|
||||
@@ -2,7 +2,7 @@ import path from "path"
|
||||
import Config from "conf"
|
||||
import { Options as ConfOptions } from "conf/dist/source/types"
|
||||
import { app, ipcMain, IpcMainEvent, ipcRenderer, IpcRendererEvent, remote } from "electron"
|
||||
import { action, observable, reaction, runInAction, toJS, when } from "mobx";
|
||||
import { action, IReactionOptions, observable, reaction, runInAction, toJS, when } from "mobx";
|
||||
import Singleton from "./utils/singleton";
|
||||
import { getAppVersion } from "./utils/app-version";
|
||||
import logger from "../main/logger";
|
||||
@@ -12,6 +12,7 @@ import isEqual from "lodash/isEqual";
|
||||
export interface BaseStoreParams<T = any> extends ConfOptions<T> {
|
||||
autoLoad?: boolean;
|
||||
syncEnabled?: boolean;
|
||||
syncOptions?: IReactionOptions;
|
||||
}
|
||||
|
||||
export class BaseStore<T = any> extends Singleton {
|
||||
@@ -20,7 +21,7 @@ export class BaseStore<T = any> extends Singleton {
|
||||
|
||||
whenLoaded = when(() => this.isLoaded);
|
||||
@observable isLoaded = false;
|
||||
@observable protected data: T;
|
||||
@observable data = {} as T;
|
||||
|
||||
protected constructor(protected params: BaseStoreParams) {
|
||||
super();
|
||||
@@ -44,6 +45,10 @@ export class BaseStore<T = any> extends Singleton {
|
||||
return `store-sync-main:${this.name}`
|
||||
}
|
||||
|
||||
get path() {
|
||||
return this.storeConfig.path;
|
||||
}
|
||||
|
||||
protected async init() {
|
||||
if (this.params.autoLoad) {
|
||||
await this.load();
|
||||
@@ -60,19 +65,19 @@ export class BaseStore<T = any> extends Singleton {
|
||||
...confOptions,
|
||||
projectName: "lens",
|
||||
projectVersion: getAppVersion(),
|
||||
cwd: this.storePath(),
|
||||
cwd: this.cwd(),
|
||||
});
|
||||
logger.info(`[STORE]: LOADED from ${this.storeConfig.path}`);
|
||||
logger.info(`[STORE]: LOADED from ${this.path}`);
|
||||
this.fromStore(this.storeConfig.store);
|
||||
this.isLoaded = true;
|
||||
}
|
||||
|
||||
protected storePath() {
|
||||
protected cwd() {
|
||||
return (app || remote.app).getPath("userData")
|
||||
}
|
||||
|
||||
protected async saveToFile(model: T) {
|
||||
logger.info(`[STORE]: SAVING ${this.name}`);
|
||||
logger.info(`[STORE]: SAVING ${this.path}`);
|
||||
// todo: update when fixed https://github.com/sindresorhus/conf/issues/114
|
||||
Object.entries(model).forEach(([key, value]) => {
|
||||
this.storeConfig.set(key, value);
|
||||
@@ -81,7 +86,7 @@ export class BaseStore<T = any> extends Singleton {
|
||||
|
||||
enableSync() {
|
||||
this.syncDisposers.push(
|
||||
reaction(() => this.toJSON(), model => this.onModelChange(model)),
|
||||
reaction(() => this.toJSON(), model => this.onModelChange(model), this.params.syncOptions),
|
||||
);
|
||||
if (ipcMain) {
|
||||
const callback = (event: IpcMainEvent, model: T) => {
|
||||
@@ -143,6 +148,7 @@ export class BaseStore<T = any> extends Singleton {
|
||||
|
||||
@action
|
||||
protected fromStore(data: T) {
|
||||
if (!data) return;
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
|
||||
@@ -40,6 +40,7 @@ export interface ClusterModel {
|
||||
preferences?: ClusterPreferences;
|
||||
metadata?: ClusterMetadata;
|
||||
ownerRef?: string;
|
||||
accessibleNamespaces?: string[];
|
||||
|
||||
/** @deprecated */
|
||||
kubeConfig?: string; // yaml
|
||||
@@ -183,8 +184,8 @@ export class ClusterStore extends BaseStore<ClusterStoreModel> {
|
||||
}
|
||||
|
||||
@action
|
||||
addCluster(model: ClusterModel | Cluster ): Cluster {
|
||||
appEventBus.emit({name: "cluster", action: "add"})
|
||||
addCluster(model: ClusterModel | Cluster): Cluster {
|
||||
appEventBus.emit({ name: "cluster", action: "add" })
|
||||
let cluster = model as Cluster;
|
||||
if (!(model instanceof Cluster)) {
|
||||
cluster = new Cluster(model)
|
||||
@@ -199,7 +200,7 @@ export class ClusterStore extends BaseStore<ClusterStoreModel> {
|
||||
|
||||
@action
|
||||
async removeById(clusterId: ClusterId) {
|
||||
appEventBus.emit({name: "cluster", action: "remove"})
|
||||
appEventBus.emit({ name: "cluster", action: "remove" })
|
||||
const cluster = this.getById(clusterId);
|
||||
if (cluster) {
|
||||
this.clusters.delete(clusterId);
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
import { action, computed, observable } from "mobx";
|
||||
import { autobind } from "../renderer/utils";
|
||||
|
||||
export class SearchStore {
|
||||
@observable searchQuery = ""; // Text in the search input
|
||||
@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
|
||||
|
||||
/**
|
||||
* Sets default activeOverlayIndex
|
||||
* @param text An array of any textual data (logs, for example)
|
||||
* @param query Search query from input
|
||||
*/
|
||||
@action
|
||||
onSearch(text: string[], query = this.searchQuery) {
|
||||
this.searchQuery = query;
|
||||
if (!query) {
|
||||
this.reset();
|
||||
return;
|
||||
}
|
||||
this.occurrences = this.findOccurences(text, query);
|
||||
if (!this.occurrences.length) return;
|
||||
|
||||
// If new highlighted keyword in exact same place as previous one, then no changing in active overlay
|
||||
if (this.occurrences[this.activeOverlayIndex] !== undefined) return;
|
||||
this.activeOverlayIndex = this.getNextOverlay(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Does searching within text array, create a list of search keyword occurences.
|
||||
* Each keyword "occurency" is saved as index of the the line where keyword founded
|
||||
* @param text An array of any textual data (logs, for example)
|
||||
* @param query Search query from input
|
||||
* @returns {Array} Array of line indexes [0, 0, 14, 17, 17, 17, 20...]
|
||||
*/
|
||||
findOccurences(text: string[], query: string) {
|
||||
if (!text) return [];
|
||||
const occurences: number[] = [];
|
||||
text.forEach((line, index) => {
|
||||
const regex = new RegExp(this.escapeRegex(query), "gi");
|
||||
const matches = [...line.matchAll(regex)];
|
||||
matches.forEach(() => occurences.push(index));
|
||||
});
|
||||
return occurences;
|
||||
}
|
||||
|
||||
/**
|
||||
* Getting next overlay index within the occurences array
|
||||
* @param loopOver Allows to jump from last element to first
|
||||
* @returns {number} next overlay index
|
||||
*/
|
||||
getNextOverlay(loopOver = false) {
|
||||
const next = this.activeOverlayIndex + 1;
|
||||
if (next > this.occurrences.length - 1) {
|
||||
return loopOver ? 0 : this.activeOverlayIndex;
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
* Getting previous overlay index within the occurences array of occurences
|
||||
* @param loopOver Allows to jump from first element to last one
|
||||
* @returns {number} prev overlay index
|
||||
*/
|
||||
getPrevOverlay(loopOver = false) {
|
||||
const prev = this.activeOverlayIndex - 1;
|
||||
if (prev < 0) {
|
||||
return loopOver ? this.occurrences.length - 1 : this.activeOverlayIndex;
|
||||
}
|
||||
return prev;
|
||||
}
|
||||
|
||||
@autobind()
|
||||
setNextOverlayActive() {
|
||||
this.activeOverlayIndex = this.getNextOverlay(true);
|
||||
}
|
||||
|
||||
@autobind()
|
||||
setPrevOverlayActive() {
|
||||
this.activeOverlayIndex = this.getPrevOverlay(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets line index of where active overlay is located
|
||||
* @returns {number} A line index within the text/logs array
|
||||
*/
|
||||
@computed get activeOverlayLine(): number {
|
||||
return this.occurrences[this.activeOverlayIndex];
|
||||
}
|
||||
|
||||
@computed get activeFind(): number {
|
||||
return this.activeOverlayIndex + 1;
|
||||
}
|
||||
|
||||
@computed get totalFinds(): number {
|
||||
return this.occurrences.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if overlay is active (to highlight it with orange background usually)
|
||||
* @param line Index of the line where overlay is located
|
||||
* @param occurence Number of the overlay within one line
|
||||
*/
|
||||
@autobind()
|
||||
isActiveOverlay(line: number, occurence: number) {
|
||||
const firstLineIndex = this.occurrences.findIndex(item => item === line);
|
||||
return firstLineIndex + occurence === this.activeOverlayIndex;
|
||||
}
|
||||
|
||||
/**
|
||||
* An utility methods escaping user string to safely pass it into new Regex(variable)
|
||||
* @param value Unescaped string
|
||||
*/
|
||||
escapeRegex(value: string) {
|
||||
return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" );
|
||||
}
|
||||
|
||||
@action
|
||||
reset() {
|
||||
this.searchQuery = "";
|
||||
this.activeOverlayIndex = -1;
|
||||
this.occurrences = [];
|
||||
}
|
||||
}
|
||||
|
||||
export const searchStore = new SearchStore;
|
||||
@@ -31,7 +31,7 @@ export interface UserPreferences {
|
||||
}
|
||||
|
||||
export class UserStore extends BaseStore<UserStoreModel> {
|
||||
static readonly defaultTheme: ThemeId = "kontena-dark"
|
||||
static readonly defaultTheme: ThemeId = "lens-dark"
|
||||
|
||||
private constructor() {
|
||||
super({
|
||||
@@ -88,7 +88,8 @@ export class UserStore extends BaseStore<UserStoreModel> {
|
||||
}
|
||||
|
||||
@action
|
||||
resetTheme() {
|
||||
async resetTheme() {
|
||||
await this.whenLoaded;
|
||||
this.preferences.colorTheme = UserStore.defaultTheme;
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,6 @@ export function debouncePromise<T, F extends any[]>(func: (...args: F) => T | Pr
|
||||
let timer: NodeJS.Timeout;
|
||||
return (...params: any[]) => new Promise((resolve, reject) => {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => resolve(func.apply(this, params)), timeout);
|
||||
timer = global.setTimeout(() => resolve(func.apply(this, params)), timeout);
|
||||
});
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
// Save file to electron app directory (e.g. "/Users/$USER/Library/Application Support/Lens" for MacOS)
|
||||
import path from "path";
|
||||
import { app, remote } from "electron";
|
||||
import { ensureDirSync, writeFileSync, WriteFileOptions } from "fs-extra";
|
||||
import { ensureDirSync, writeFileSync } from "fs-extra";
|
||||
import { WriteFileOptions } from "fs"
|
||||
|
||||
export function saveToAppFiles(filePath: string, contents: any, options?: WriteFileOptions): string {
|
||||
const absPath = path.resolve((app || remote.app).getPath("userData"), filePath);
|
||||
|
||||
@@ -22,6 +22,7 @@ export const mainDir = path.join(contextDir, "src/main");
|
||||
export const rendererDir = path.join(contextDir, "src/renderer");
|
||||
export const htmlTemplate = path.resolve(rendererDir, "template.html");
|
||||
export const sassCommonVars = path.resolve(rendererDir, "components/vars.scss");
|
||||
export const webpackDevServerPort = 9009
|
||||
|
||||
// Special runtime paths
|
||||
defineGlobal("__static", {
|
||||
|
||||
@@ -150,20 +150,20 @@ export class WorkspaceStore extends BaseStore<WorkspaceStoreModel> {
|
||||
@action
|
||||
addWorkspace(workspace: Workspace) {
|
||||
const { id, name } = workspace;
|
||||
const existingWorkspace = this.getById(id);
|
||||
if (!name.trim() || this.getByName(name.trim())) {
|
||||
return;
|
||||
}
|
||||
if (existingWorkspace) {
|
||||
Object.assign(existingWorkspace, workspace);
|
||||
appEventBus.emit({name: "workspace", action: "update"})
|
||||
} else {
|
||||
appEventBus.emit({name: "workspace", action: "add"})
|
||||
}
|
||||
this.workspaces.set(id, workspace);
|
||||
appEventBus.emit({name: "workspace", action: "add"})
|
||||
return workspace;
|
||||
}
|
||||
|
||||
@action
|
||||
updateWorkspace(workspace: Workspace) {
|
||||
this.workspaces.set(workspace.id, workspace);
|
||||
appEventBus.emit({name: "workspace", action: "update"});
|
||||
}
|
||||
|
||||
@action
|
||||
removeWorkspace(workspace: Workspace) {
|
||||
this.removeWorkspaceById(workspace.id)
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { LensExtension } from "../lens-extension"
|
||||
|
||||
let ext: LensExtension = null
|
||||
|
||||
describe("lens extension", () => {
|
||||
beforeEach(async () => {
|
||||
ext = new LensExtension({
|
||||
manifest: {
|
||||
name: "foo-bar",
|
||||
version: "0.1.1"
|
||||
},
|
||||
manifestPath: "/this/is/fake/package.json",
|
||||
isBundled: false,
|
||||
isEnabled: true
|
||||
})
|
||||
})
|
||||
|
||||
describe("name", () => {
|
||||
it("returns name", () => {
|
||||
expect(ext.name).toBe("foo-bar")
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1 +1,2 @@
|
||||
export { ClusterFeature as Feature, ClusterFeatureStatus as FeatureStatus } from "../cluster-feature"
|
||||
export { ClusterFeature as Feature } from "../cluster-feature"
|
||||
export type { ClusterFeatureStatus as FeatureStatus } from "../cluster-feature"
|
||||
@@ -2,24 +2,19 @@
|
||||
export * from "../lens-main-extension"
|
||||
export * from "../lens-renderer-extension"
|
||||
|
||||
import type { WindowManager } from "../../main/window-manager";
|
||||
|
||||
// APIs
|
||||
import * as App from "./app"
|
||||
import * as EventBus from "./event-bus"
|
||||
import * as Store from "./stores"
|
||||
import * as Util from "./utils"
|
||||
import * as Registry from "../registries"
|
||||
import * as ClusterFeature from "./cluster-feature"
|
||||
|
||||
// TODO: allow to expose windowManager.navigate() as Navigation.navigate() in runtime
|
||||
export let windowManager: WindowManager;
|
||||
import * as Interface from "../interfaces"
|
||||
|
||||
export {
|
||||
App,
|
||||
EventBus,
|
||||
ClusterFeature,
|
||||
Interface,
|
||||
Store,
|
||||
Util,
|
||||
Registry,
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
export { ExtensionStore } from "../extension-store"
|
||||
export { clusterStore, ClusterModel } from "../../common/cluster-store"
|
||||
export { Cluster } from "../../main/cluster"
|
||||
export { workspaceStore, Workspace, WorkspaceModel } from "../../common/workspace-store"
|
||||
export { clusterStore } from "../../common/cluster-store"
|
||||
export type { ClusterModel } from "../../common/cluster-store"
|
||||
export { Cluster } from "../../main/cluster"
|
||||
export { workspaceStore, Workspace } from "../../common/workspace-store"
|
||||
export type { WorkspaceModel } from "../../common/workspace-store"
|
||||
@@ -1,15 +0,0 @@
|
||||
import React from "react";
|
||||
import { cssNames } from "../renderer/utils";
|
||||
import { TabLayout } from "../renderer/components/layout/tab-layout";
|
||||
import { PageRegistration } from "./registries/page-registry"
|
||||
|
||||
export class DynamicPage extends React.Component<{ page: PageRegistration }> {
|
||||
render() {
|
||||
const { className, components: { Page }, subPages = [] } = this.props.page;
|
||||
return (
|
||||
<TabLayout className={cssNames("ExtensionPage", className)} tabs={subPages}>
|
||||
<Page/>
|
||||
</TabLayout>
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
// Extension-api types generation bundle (used by rollup.js)
|
||||
// Extension-api types generation bundle
|
||||
|
||||
export * from "./core-api"
|
||||
export * from "./renderer-api"
|
||||
@@ -1,22 +1,16 @@
|
||||
import type { ExtensionId, ExtensionManifest, ExtensionModel, LensExtension } from "./lens-extension"
|
||||
import type { LensExtension, LensExtensionConstructor, LensExtensionId } from "./lens-extension"
|
||||
import type { LensMainExtension } from "./lens-main-extension"
|
||||
import type { LensRendererExtension } from "./lens-renderer-extension"
|
||||
import type { InstalledExtension } from "./extension-manager";
|
||||
import path from "path"
|
||||
import { broadcastMessage, subscribeToBroadcast } from "../common/ipc"
|
||||
import { observable, reaction, toJS, } from "mobx"
|
||||
import { action, computed, observable, reaction, toJS, when } from "mobx"
|
||||
import logger from "../main/logger"
|
||||
import { app, ipcRenderer, remote } from "electron"
|
||||
import { appEventBus } from "./core-api/event-bus"
|
||||
import { clusterStore } from "./core-api/stores"
|
||||
import {
|
||||
appPreferenceRegistry, clusterFeatureRegistry, clusterPageRegistry, globalPageRegistry,
|
||||
kubeObjectDetailRegistry, kubeObjectMenuRegistry, menuRegistry, statusBarRegistry
|
||||
} from "./registries";
|
||||
|
||||
export interface InstalledExtension extends ExtensionModel {
|
||||
manifestPath: string;
|
||||
manifest: ExtensionManifest;
|
||||
}
|
||||
import * as registries from "./registries";
|
||||
import { extensionsStore } from "./extensions-store";
|
||||
|
||||
// lazy load so that we get correct userData
|
||||
export function extensionPackagesRoot() {
|
||||
@@ -24,18 +18,23 @@ export function extensionPackagesRoot() {
|
||||
}
|
||||
|
||||
export class ExtensionLoader {
|
||||
@observable extensions = observable.map<ExtensionId, InstalledExtension>([], { deep: false });
|
||||
@observable instances = observable.map<ExtensionId, LensExtension>([], { deep: false })
|
||||
protected extensions = observable.map<LensExtensionId, InstalledExtension>();
|
||||
protected instances = observable.map<LensExtensionId, LensExtension>();
|
||||
|
||||
@observable isLoaded = false;
|
||||
whenLoaded = when(() => this.isLoaded);
|
||||
|
||||
constructor() {
|
||||
if (ipcRenderer) {
|
||||
subscribeToBroadcast("extensions:loaded", (event, extensions: InstalledExtension[]) => {
|
||||
extensions.forEach((ext) => {
|
||||
if (!this.getById(ext.manifestPath)) {
|
||||
this.extensions.set(ext.manifestPath, ext)
|
||||
subscribeToBroadcast("extensions:loaded", (event, extensions: [LensExtensionId, InstalledExtension][]) => {
|
||||
console.log("extensions", extensions)
|
||||
this.isLoaded = true;
|
||||
extensions.forEach(([extId, ext]) => {
|
||||
if (!this.extensions.has(extId)) {
|
||||
this.extensions.set(extId, ext)
|
||||
}
|
||||
})
|
||||
})
|
||||
});
|
||||
} else {
|
||||
reaction(() => this.extensions.toJS(), () => {
|
||||
this.broadcastExtensions()
|
||||
@@ -49,56 +48,82 @@ export class ExtensionLoader {
|
||||
this.broadcastExtensions()
|
||||
})
|
||||
}
|
||||
extensionsStore.manageState(this);
|
||||
}
|
||||
|
||||
@computed get userExtensions(): Map<LensExtensionId, InstalledExtension> {
|
||||
const extensions = this.extensions.toJS();
|
||||
extensions.forEach((ext, extId) => {
|
||||
if (ext.isBundled) {
|
||||
extensions.delete(extId);
|
||||
}
|
||||
})
|
||||
return extensions;
|
||||
}
|
||||
|
||||
@action
|
||||
async init(extensions: Map<LensExtensionId, InstalledExtension>) {
|
||||
this.extensions.replace(extensions);
|
||||
this.isLoaded = true;
|
||||
this.loadOnMain();
|
||||
this.broadcastExtensions();
|
||||
}
|
||||
|
||||
loadOnMain() {
|
||||
logger.info('[EXTENSIONS-LOADER]: load on main')
|
||||
this.autoloadExtensions((extension: LensMainExtension) => {
|
||||
extension.registerTo(menuRegistry, extension.appMenus)
|
||||
})
|
||||
this.autoInitExtensions((ext: LensMainExtension) => [
|
||||
registries.menuRegistry.add(ext.appMenus)
|
||||
]);
|
||||
}
|
||||
|
||||
loadOnClusterManagerRenderer() {
|
||||
logger.info('[EXTENSIONS-LOADER]: load on main renderer (cluster manager)')
|
||||
this.autoloadExtensions((extension: LensRendererExtension) => {
|
||||
extension.registerTo(globalPageRegistry, extension.globalPages)
|
||||
extension.registerTo(appPreferenceRegistry, extension.appPreferences)
|
||||
extension.registerTo(clusterFeatureRegistry, extension.clusterFeatures)
|
||||
extension.registerTo(statusBarRegistry, extension.statusBarItems)
|
||||
})
|
||||
this.autoInitExtensions((ext: LensRendererExtension) => [
|
||||
registries.globalPageRegistry.add(ext.globalPages, ext),
|
||||
registries.globalPageMenuRegistry.add(ext.globalPageMenus, ext),
|
||||
registries.appPreferenceRegistry.add(ext.appPreferences),
|
||||
registries.clusterFeatureRegistry.add(ext.clusterFeatures),
|
||||
registries.statusBarRegistry.add(ext.statusBarItems),
|
||||
]);
|
||||
}
|
||||
|
||||
loadOnClusterRenderer() {
|
||||
logger.info('[EXTENSIONS-LOADER]: load on cluster renderer (dashboard)')
|
||||
this.autoloadExtensions((extension: LensRendererExtension) => {
|
||||
extension.registerTo(clusterPageRegistry, extension.clusterPages)
|
||||
extension.registerTo(kubeObjectMenuRegistry, extension.kubeObjectMenuItems)
|
||||
extension.registerTo(kubeObjectDetailRegistry, extension.kubeObjectDetailItems)
|
||||
})
|
||||
this.autoInitExtensions((ext: LensRendererExtension) => [
|
||||
registries.clusterPageRegistry.add(ext.clusterPages, ext),
|
||||
registries.clusterPageMenuRegistry.add(ext.clusterPageMenus, ext),
|
||||
registries.kubeObjectMenuRegistry.add(ext.kubeObjectMenuItems),
|
||||
registries.kubeObjectDetailRegistry.add(ext.kubeObjectDetailItems),
|
||||
registries.kubeObjectStatusRegistry.add(ext.kubeObjectStatusTexts)
|
||||
])
|
||||
}
|
||||
|
||||
protected autoloadExtensions(callback: (instance: LensExtension) => void) {
|
||||
return reaction(() => this.extensions.toJS(), (installedExtensions) => {
|
||||
for(const [id, ext] of installedExtensions) {
|
||||
let instance = this.instances.get(ext.id)
|
||||
if (!instance) {
|
||||
const extensionModule = this.requireExtension(ext)
|
||||
if (!extensionModule) {
|
||||
continue
|
||||
}
|
||||
const LensExtensionClass = extensionModule.default;
|
||||
instance = new LensExtensionClass({ ...ext.manifest, manifestPath: ext.manifestPath, id: ext.manifestPath }, ext.manifest);
|
||||
protected autoInitExtensions(register: (ext: LensExtension) => Function[]) {
|
||||
return reaction(() => this.toJSON(), installedExtensions => {
|
||||
for (const [extId, ext] of installedExtensions) {
|
||||
let instance = this.instances.get(extId);
|
||||
if (ext.isEnabled && !instance) {
|
||||
try {
|
||||
instance.enable()
|
||||
callback(instance)
|
||||
} finally {
|
||||
this.instances.set(ext.id, instance)
|
||||
const LensExtensionClass: LensExtensionConstructor = this.requireExtension(ext)
|
||||
if (!LensExtensionClass) continue;
|
||||
instance = new LensExtensionClass(ext);
|
||||
instance.whenEnabled(() => register(instance));
|
||||
instance.enable();
|
||||
this.instances.set(extId, instance);
|
||||
} catch (err) {
|
||||
logger.error(`[EXTENSION-LOADER]: activation extension error`, { ext, err })
|
||||
}
|
||||
} else if (!ext.isEnabled && instance) {
|
||||
try {
|
||||
instance.disable();
|
||||
this.instances.delete(extId);
|
||||
} catch (err) {
|
||||
logger.error(`[EXTENSION-LOADER]: deactivation extension error`, { ext, err })
|
||||
}
|
||||
}
|
||||
}
|
||||
}, {
|
||||
fireImmediately: true,
|
||||
delay: 0,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -111,7 +136,7 @@ export class ExtensionLoader {
|
||||
extEntrypoint = path.resolve(path.join(path.dirname(extension.manifestPath), extension.manifest.main))
|
||||
}
|
||||
if (extEntrypoint !== "") {
|
||||
return __non_webpack_require__(extEntrypoint)
|
||||
return __non_webpack_require__(extEntrypoint).default;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`[EXTENSION-LOADER]: can't load extension main at ${extEntrypoint}: ${err}`, { extension });
|
||||
@@ -119,32 +144,20 @@ export class ExtensionLoader {
|
||||
}
|
||||
}
|
||||
|
||||
getById(id: ExtensionId): InstalledExtension {
|
||||
return this.extensions.get(id);
|
||||
getExtension(extId: LensExtensionId): InstalledExtension {
|
||||
return this.extensions.get(extId);
|
||||
}
|
||||
|
||||
async removeById(id: ExtensionId) {
|
||||
const extension = this.getById(id);
|
||||
if (extension) {
|
||||
const instance = this.instances.get(extension.id)
|
||||
if (instance) {
|
||||
await instance.disable()
|
||||
}
|
||||
this.extensions.delete(id);
|
||||
}
|
||||
}
|
||||
|
||||
broadcastExtensions() {
|
||||
broadcastMessage("extensions:loaded", this.toJSON().extensions)
|
||||
}
|
||||
|
||||
toJSON() {
|
||||
return toJS({
|
||||
extensions: Array.from(this.extensions).map(([id, instance]) => instance),
|
||||
}, {
|
||||
toJSON(): Map<LensExtensionId, InstalledExtension> {
|
||||
return toJS(this.extensions, {
|
||||
exportMapsAsObjects: false,
|
||||
recurseEverything: true,
|
||||
})
|
||||
}
|
||||
|
||||
broadcastExtensions() {
|
||||
broadcastMessage("extensions:loaded", Array.from(this.toJSON()))
|
||||
}
|
||||
}
|
||||
|
||||
export const extensionLoader = new ExtensionLoader()
|
||||
export const extensionLoader = new ExtensionLoader();
|
||||
@@ -1,12 +1,19 @@
|
||||
import type { ExtensionManifest } from "./lens-extension"
|
||||
import type { LensExtensionId, LensExtensionManifest } from "./lens-extension"
|
||||
import path from "path"
|
||||
import os from "os"
|
||||
import fs from "fs-extra"
|
||||
import child_process from "child_process";
|
||||
import logger from "../main/logger"
|
||||
import { extensionPackagesRoot, InstalledExtension } from "./extension-loader"
|
||||
import * as child_process from 'child_process';
|
||||
import { extensionPackagesRoot } from "./extension-loader"
|
||||
import { getBundledExtensions } from "../common/utils/app-version"
|
||||
|
||||
export interface InstalledExtension {
|
||||
readonly manifest: LensExtensionManifest;
|
||||
readonly manifestPath: string;
|
||||
readonly isBundled: boolean; // defined in project root's package.json
|
||||
isEnabled: boolean;
|
||||
}
|
||||
|
||||
type Dependencies = {
|
||||
[name: string]: string;
|
||||
}
|
||||
@@ -51,7 +58,7 @@ export class ExtensionManager {
|
||||
return path.join(this.extensionPackagesRoot, "package.json")
|
||||
}
|
||||
|
||||
async load() {
|
||||
async load(): Promise<Map<LensExtensionId, InstalledExtension>> {
|
||||
logger.info("[EXTENSION-MANAGER] loading extensions from " + this.extensionPackagesRoot)
|
||||
if (fs.existsSync(path.join(this.extensionPackagesRoot, "package-lock.json"))) {
|
||||
await fs.remove(path.join(this.extensionPackagesRoot, "package-lock.json"))
|
||||
@@ -71,8 +78,8 @@ export class ExtensionManager {
|
||||
return await this.loadExtensions();
|
||||
}
|
||||
|
||||
async getExtensionByManifest(manifestPath: string): Promise<InstalledExtension> {
|
||||
let manifestJson: ExtensionManifest;
|
||||
protected async getByManifest(manifestPath: string, { isBundled = false } = {}): Promise<InstalledExtension> {
|
||||
let manifestJson: LensExtensionManifest;
|
||||
try {
|
||||
fs.accessSync(manifestPath, fs.constants.F_OK); // check manifest file for existence
|
||||
manifestJson = __non_webpack_require__(manifestPath)
|
||||
@@ -80,11 +87,10 @@ export class ExtensionManager {
|
||||
|
||||
logger.info("[EXTENSION-MANAGER] installed extension " + manifestJson.name)
|
||||
return {
|
||||
id: manifestJson.name,
|
||||
version: manifestJson.version,
|
||||
name: manifestJson.name,
|
||||
manifestPath: path.join(this.nodeModulesPath, manifestJson.name, "package.json"),
|
||||
manifest: manifestJson
|
||||
manifest: manifestJson,
|
||||
isBundled: isBundled,
|
||||
isEnabled: isBundled,
|
||||
}
|
||||
} catch (err) {
|
||||
logger.error(`[EXTENSION-MANAGER]: can't install extension at ${manifestPath}: ${err}`, { manifestJson });
|
||||
@@ -109,10 +115,10 @@ export class ExtensionManager {
|
||||
async loadExtensions() {
|
||||
const bundledExtensions = await this.loadBundledExtensions()
|
||||
const localExtensions = await this.loadFromFolder(this.localFolderPath)
|
||||
await fs.writeFile(path.join(this.packageJsonPath), JSON.stringify(this.packagesJson, null, 2), {mode: 0o600})
|
||||
await fs.writeFile(path.join(this.packageJsonPath), JSON.stringify(this.packagesJson, null, 2), { mode: 0o600 })
|
||||
await this.installPackages()
|
||||
const extensions = bundledExtensions.concat(localExtensions)
|
||||
return new Map(extensions.map(ext => [ext.id, ext]));
|
||||
return new Map(extensions.map(ext => [ext.manifestPath, ext]));
|
||||
}
|
||||
|
||||
async loadBundledExtensions() {
|
||||
@@ -126,7 +132,7 @@ export class ExtensionManager {
|
||||
}
|
||||
const absPath = path.resolve(folderPath, fileName);
|
||||
const manifestPath = path.resolve(absPath, "package.json");
|
||||
const ext = await this.getExtensionByManifest(manifestPath).catch(() => null)
|
||||
const ext = await this.getByManifest(manifestPath, { isBundled: true }).catch(() => null)
|
||||
if (ext) {
|
||||
extensions.push(ext)
|
||||
}
|
||||
@@ -152,7 +158,7 @@ export class ExtensionManager {
|
||||
continue
|
||||
}
|
||||
const manifestPath = path.resolve(absPath, "package.json");
|
||||
const ext = await this.getExtensionByManifest(manifestPath).catch(() => null)
|
||||
const ext = await this.getByManifest(manifestPath).catch(() => null)
|
||||
if (ext) {
|
||||
extensions.push(ext)
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ export class ExtensionStore<T = any> extends BaseStore<T> {
|
||||
await super.load()
|
||||
}
|
||||
|
||||
protected storePath() {
|
||||
return path.join(super.storePath(), "extension-store", this.extension.name)
|
||||
protected cwd() {
|
||||
return path.join(super.cwd(), "extension-store", this.extension.name)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import type { LensExtensionId } from "./lens-extension";
|
||||
import type { ExtensionLoader } from "./extension-loader";
|
||||
import { BaseStore } from "../common/base-store"
|
||||
import { action, observable, reaction, toJS } from "mobx";
|
||||
|
||||
export interface LensExtensionsStoreModel {
|
||||
extensions: Record<LensExtensionId, LensExtensionState>;
|
||||
}
|
||||
|
||||
export interface LensExtensionState {
|
||||
enabled?: boolean;
|
||||
}
|
||||
|
||||
export class ExtensionsStore extends BaseStore<LensExtensionsStoreModel> {
|
||||
constructor() {
|
||||
super({
|
||||
configName: "lens-extensions",
|
||||
});
|
||||
}
|
||||
|
||||
protected state = observable.map<LensExtensionId, LensExtensionState>();
|
||||
|
||||
protected getState(extensionLoader: ExtensionLoader) {
|
||||
const state: Record<LensExtensionId, LensExtensionState> = {};
|
||||
return Array.from(extensionLoader.userExtensions).reduce((state, [extId, ext]) => {
|
||||
state[extId] = {
|
||||
enabled: ext.isEnabled,
|
||||
}
|
||||
return state;
|
||||
}, state)
|
||||
}
|
||||
|
||||
async manageState(extensionLoader: ExtensionLoader) {
|
||||
await extensionLoader.whenLoaded;
|
||||
await this.whenLoaded;
|
||||
|
||||
// activate user-extensions when state is ready
|
||||
extensionLoader.userExtensions.forEach((ext, extId) => {
|
||||
ext.isEnabled = this.isEnabled(extId);
|
||||
});
|
||||
|
||||
// apply state on changes from store
|
||||
reaction(() => this.state.toJS(), extensionsState => {
|
||||
extensionsState.forEach((state, extId) => {
|
||||
const ext = extensionLoader.getExtension(extId);
|
||||
if (ext && !ext.isBundled) {
|
||||
ext.isEnabled = state.enabled;
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
// save state on change `extension.isEnabled`
|
||||
reaction(() => this.getState(extensionLoader), extensionsState => {
|
||||
this.state.merge(extensionsState)
|
||||
})
|
||||
}
|
||||
|
||||
isEnabled(extId: LensExtensionId) {
|
||||
const state = this.state.get(extId);
|
||||
return !state /* enabled by default */ || state.enabled;
|
||||
}
|
||||
|
||||
@action
|
||||
protected fromStore({ extensions }: LensExtensionsStoreModel) {
|
||||
this.state.merge(extensions);
|
||||
}
|
||||
|
||||
toJSON(): LensExtensionsStoreModel {
|
||||
return toJS({
|
||||
extensions: this.state.toJSON(),
|
||||
}, {
|
||||
recurseEverything: true
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export const extensionsStore = new ExtensionsStore();
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./registrations"
|
||||
@@ -0,0 +1,8 @@
|
||||
export type { AppPreferenceRegistration, AppPreferenceComponents } from "../registries/app-preference-registry"
|
||||
export type { ClusterFeatureRegistration, ClusterFeatureComponents } from "../registries/cluster-feature-registry"
|
||||
export type { KubeObjectDetailRegistration, KubeObjectDetailComponents } from "../registries/kube-object-detail-registry"
|
||||
export type { KubeObjectMenuRegistration, KubeObjectMenuComponents } from "../registries/kube-object-menu-registry"
|
||||
export type { KubeObjectStatusRegistration } from "../registries/kube-object-status-registry"
|
||||
export type { PageRegistration, PageComponents } from "../registries/page-registry"
|
||||
export type { PageMenuRegistration, PageMenuComponents } from "../registries/page-menu-registry"
|
||||
export type { StatusBarRegistration } from "../registries/status-bar-registry"
|
||||
@@ -1,75 +1,92 @@
|
||||
import { readJsonSync } from "fs-extra";
|
||||
import { action, observable, toJS } from "mobx";
|
||||
import type { InstalledExtension } from "./extension-manager";
|
||||
import { action, observable, reaction } from "mobx";
|
||||
import logger from "../main/logger";
|
||||
import { BaseRegistry } from "./registries/base-registry";
|
||||
|
||||
export type ExtensionId = string | ExtensionPackageJsonPath;
|
||||
export type ExtensionPackageJsonPath = string;
|
||||
export type ExtensionVersion = string | number;
|
||||
export type LensExtensionId = string; // path to manifest (package.json)
|
||||
export type LensExtensionConstructor = new (...args: ConstructorParameters<typeof LensExtension>) => LensExtension;
|
||||
|
||||
export interface ExtensionModel {
|
||||
id: ExtensionId;
|
||||
version: ExtensionVersion;
|
||||
export interface LensExtensionManifest {
|
||||
name: string;
|
||||
manifestPath: string;
|
||||
version: string;
|
||||
description?: string;
|
||||
enabled?: boolean;
|
||||
updateUrl?: string;
|
||||
main?: string; // path to %ext/dist/main.js
|
||||
renderer?: string; // path to %ext/dist/renderer.js
|
||||
}
|
||||
|
||||
export interface ExtensionManifest extends ExtensionModel {
|
||||
main?: string;
|
||||
renderer?: string;
|
||||
description?: string; // todo: add more fields similar to package.json + some extra
|
||||
}
|
||||
export class LensExtension {
|
||||
readonly manifest: LensExtensionManifest;
|
||||
readonly manifestPath: string;
|
||||
readonly isBundled: boolean;
|
||||
|
||||
export class LensExtension implements ExtensionModel {
|
||||
public id: ExtensionId;
|
||||
public updateUrl: string;
|
||||
protected disposers: (() => void)[] = [];
|
||||
@observable private isEnabled = false;
|
||||
|
||||
@observable name = "";
|
||||
@observable description = "";
|
||||
@observable version: ExtensionVersion = "0.0.0";
|
||||
@observable manifest: ExtensionManifest;
|
||||
@observable manifestPath: string;
|
||||
@observable isEnabled = false;
|
||||
constructor({ manifest, manifestPath, isBundled }: InstalledExtension) {
|
||||
this.manifest = manifest
|
||||
this.manifestPath = manifestPath
|
||||
this.isBundled = !!isBundled
|
||||
}
|
||||
|
||||
constructor(model: ExtensionModel, manifest: ExtensionManifest) {
|
||||
this.importModel(model, manifest);
|
||||
get id(): LensExtensionId {
|
||||
return this.manifestPath;
|
||||
}
|
||||
|
||||
get name() {
|
||||
return this.manifest.name
|
||||
}
|
||||
|
||||
get version() {
|
||||
return this.manifest.version
|
||||
}
|
||||
|
||||
get description() {
|
||||
return this.manifest.description
|
||||
}
|
||||
|
||||
@action
|
||||
async importModel({ enabled, manifestPath, ...model }: ExtensionModel, manifest?: ExtensionManifest) {
|
||||
try {
|
||||
this.manifest = manifest || await readJsonSync(manifestPath, { throws: true })
|
||||
this.manifestPath = manifestPath;
|
||||
Object.assign(this, model);
|
||||
} catch (err) {
|
||||
logger.error(`[EXTENSION]: cannot read manifest at ${manifestPath}`, { ...model, err: String(err) })
|
||||
this.disable();
|
||||
}
|
||||
}
|
||||
|
||||
async migrate(appVersion: string) {
|
||||
// mock
|
||||
}
|
||||
|
||||
async enable() {
|
||||
if (this.isEnabled) return;
|
||||
this.isEnabled = true;
|
||||
logger.info(`[EXTENSION]: enabled ${this.name}@${this.version}`);
|
||||
this.onActivate();
|
||||
logger.info(`[EXTENSION]: enabled ${this.name}@${this.version}`);
|
||||
}
|
||||
|
||||
@action
|
||||
async disable() {
|
||||
this.onDeactivate();
|
||||
if (!this.isEnabled) return;
|
||||
this.isEnabled = false;
|
||||
this.disposers.forEach(cleanUp => cleanUp());
|
||||
this.disposers.length = 0;
|
||||
this.onDeactivate();
|
||||
logger.info(`[EXTENSION]: disabled ${this.name}@${this.version}`);
|
||||
}
|
||||
|
||||
// todo: add more hooks
|
||||
toggle(enable?: boolean) {
|
||||
if (typeof enable === "boolean") {
|
||||
enable ? this.enable() : this.disable()
|
||||
} else {
|
||||
this.isEnabled ? this.disable() : this.enable()
|
||||
}
|
||||
}
|
||||
|
||||
async whenEnabled(handlers: () => Function[]) {
|
||||
const disposers: Function[] = [];
|
||||
const unregisterHandlers = () => {
|
||||
disposers.forEach(unregister => unregister())
|
||||
disposers.length = 0;
|
||||
}
|
||||
const cancelReaction = reaction(() => this.isEnabled, isEnabled => {
|
||||
if (isEnabled) {
|
||||
disposers.push(...handlers());
|
||||
} else {
|
||||
unregisterHandlers();
|
||||
}
|
||||
}, {
|
||||
fireImmediately: true
|
||||
})
|
||||
return () => {
|
||||
unregisterHandlers();
|
||||
cancelReaction();
|
||||
}
|
||||
}
|
||||
|
||||
protected onActivate() {
|
||||
// mock
|
||||
}
|
||||
@@ -77,37 +94,4 @@ export class LensExtension implements ExtensionModel {
|
||||
protected onDeactivate() {
|
||||
// mock
|
||||
}
|
||||
|
||||
registerTo<T = any>(registry: BaseRegistry<T>, items: T[] = []) {
|
||||
const disposers = items.map(item => registry.add(item));
|
||||
this.disposers.push(...disposers);
|
||||
return () => {
|
||||
this.disposers = this.disposers.filter(disposer => !disposers.includes(disposer))
|
||||
};
|
||||
}
|
||||
|
||||
getMeta() {
|
||||
return toJS({
|
||||
id: this.id,
|
||||
manifest: this.manifest,
|
||||
manifestPath: this.manifestPath,
|
||||
enabled: this.isEnabled
|
||||
}, {
|
||||
recurseEverything: true
|
||||
})
|
||||
}
|
||||
|
||||
toJSON(): ExtensionModel {
|
||||
return toJS({
|
||||
id: this.id,
|
||||
name: this.name,
|
||||
version: this.version,
|
||||
description: this.description,
|
||||
manifestPath: this.manifestPath,
|
||||
enabled: this.isEnabled,
|
||||
updateUrl: this.updateUrl,
|
||||
}, {
|
||||
recurseEverything: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,19 @@
|
||||
import type { MenuRegistration } from "./registries/menu-registry";
|
||||
import { observable } from "mobx";
|
||||
import { LensExtension } from "./lens-extension"
|
||||
import { WindowManager } from "../main/window-manager";
|
||||
import { getExtensionPageUrl } from "./registries/page-registry"
|
||||
|
||||
export class LensMainExtension extends LensExtension {
|
||||
@observable.shallow appMenus: MenuRegistration[] = []
|
||||
|
||||
async navigate<P extends object>(pageId?: string, params?: P, frameId?: number) {
|
||||
const windowManager = WindowManager.getInstance<WindowManager>();
|
||||
const pageUrl = getExtensionPageUrl({
|
||||
extensionId: this.name,
|
||||
pageId: pageId,
|
||||
params: params ?? {}, // compile to url with params
|
||||
});
|
||||
await windowManager.navigate(pageUrl, frameId);
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,27 @@
|
||||
import type {
|
||||
AppPreferenceRegistration, ClusterFeatureRegistration,
|
||||
KubeObjectMenuRegistration, KubeObjectDetailRegistration,
|
||||
PageRegistration, StatusBarRegistration
|
||||
} from "./registries"
|
||||
import type { AppPreferenceRegistration, ClusterFeatureRegistration, KubeObjectDetailRegistration, KubeObjectMenuRegistration, KubeObjectStatusRegistration, PageMenuRegistration, PageRegistration, StatusBarRegistration, } from "./registries"
|
||||
import { observable } from "mobx";
|
||||
import { LensExtension } from "./lens-extension"
|
||||
import { getExtensionPageUrl } from "./registries/page-registry"
|
||||
|
||||
export class LensRendererExtension extends LensExtension {
|
||||
@observable.shallow globalPages: PageRegistration[] = []
|
||||
@observable.shallow clusterPages: PageRegistration[] = []
|
||||
@observable.shallow globalPageMenus: PageMenuRegistration[] = []
|
||||
@observable.shallow clusterPageMenus: PageMenuRegistration[] = []
|
||||
@observable.shallow kubeObjectStatusTexts: KubeObjectStatusRegistration[] = []
|
||||
@observable.shallow appPreferences: AppPreferenceRegistration[] = []
|
||||
@observable.shallow clusterFeatures: ClusterFeatureRegistration[] = []
|
||||
@observable.shallow statusBarItems: StatusBarRegistration[] = []
|
||||
@observable.shallow kubeObjectDetailItems: KubeObjectDetailRegistration[] = []
|
||||
@observable.shallow kubeObjectMenuItems: KubeObjectMenuRegistration[] = []
|
||||
|
||||
async navigate<P extends object>(pageId?: string, params?: P) {
|
||||
const { navigate } = await import("../renderer/navigation");
|
||||
const pageUrl = getExtensionPageUrl({
|
||||
extensionId: this.name,
|
||||
pageId: pageId,
|
||||
params: params ?? {}, // compile to url with params
|
||||
});
|
||||
navigate(pageUrl);
|
||||
}
|
||||
}
|
||||
@@ -1,2 +1,3 @@
|
||||
api.d.ts
|
||||
dist/
|
||||
yarn.lock
|
||||
__mocks__/
|
||||
@@ -5,9 +5,12 @@
|
||||
"version": "0.0.0",
|
||||
"copyright": "© 2020, Mirantis, Inc.",
|
||||
"license": "MIT",
|
||||
"types": "api.d.ts",
|
||||
"main": "dist/src/extensions/extension-api.js",
|
||||
"types": "dist/src/extensions/extension-api.d.ts",
|
||||
"files": [
|
||||
"api.d.ts"
|
||||
"dist/**/*.ts",
|
||||
"__mocks__/*.ts",
|
||||
"dist/**/*.js"
|
||||
],
|
||||
"author": {
|
||||
"name": "Mirantis, Inc.",
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import { getExtensionPageUrl, globalPageRegistry, PageRegistration } from "../page-registry"
|
||||
import { LensExtension } from "../../lens-extension"
|
||||
import React from "react";
|
||||
|
||||
let ext: LensExtension = null
|
||||
|
||||
describe("getPageUrl", () => {
|
||||
beforeEach(async () => {
|
||||
ext = new LensExtension({
|
||||
manifest: {
|
||||
name: "foo-bar",
|
||||
version: "0.1.1"
|
||||
},
|
||||
manifestPath: "/this/is/fake/package.json",
|
||||
isBundled: false,
|
||||
isEnabled: true
|
||||
})
|
||||
})
|
||||
|
||||
it("returns a page url for extension", () => {
|
||||
expect(getExtensionPageUrl({ extensionId: ext.name })).toBe("/extension/foo-bar")
|
||||
})
|
||||
|
||||
it("allows to pass base url as parameter", () => {
|
||||
expect(getExtensionPageUrl({ extensionId: ext.name, pageId: "/test" })).toBe("/extension/foo-bar/test")
|
||||
})
|
||||
|
||||
it("removes @", () => {
|
||||
expect(getExtensionPageUrl({ extensionId: "@foo/bar" })).toBe("/extension/foo-bar")
|
||||
})
|
||||
|
||||
it("adds / prefix", () => {
|
||||
expect(getExtensionPageUrl({ extensionId: ext.name, pageId: "test" })).toBe("/extension/foo-bar/test")
|
||||
})
|
||||
})
|
||||
|
||||
describe("globalPageRegistry", () => {
|
||||
beforeEach(async () => {
|
||||
ext = new LensExtension({
|
||||
manifest: {
|
||||
name: "@acme/foo-bar",
|
||||
version: "0.1.1"
|
||||
},
|
||||
manifestPath: "/this/is/fake/package.json",
|
||||
isBundled: false,
|
||||
isEnabled: true
|
||||
})
|
||||
globalPageRegistry.add([
|
||||
{
|
||||
id: "test-page",
|
||||
components: {
|
||||
Page: () => React.createElement('Text')
|
||||
}
|
||||
},
|
||||
{
|
||||
id: "another-page",
|
||||
components: {
|
||||
Page: () => React.createElement('Text')
|
||||
},
|
||||
},
|
||||
{
|
||||
components: {
|
||||
Page: () => React.createElement('Default')
|
||||
}
|
||||
},
|
||||
], ext)
|
||||
})
|
||||
|
||||
describe("getByPageMenuTarget", () => {
|
||||
it("matching to first registered page without id", () => {
|
||||
const page = globalPageRegistry.getByPageMenuTarget({ extensionId: ext.name })
|
||||
expect(page.id).toEqual(undefined);
|
||||
expect(page.extensionId).toEqual(ext.name);
|
||||
expect(page.routePath).toEqual(getExtensionPageUrl({ extensionId: ext.name }));
|
||||
});
|
||||
|
||||
it("returns matching page", () => {
|
||||
const page = globalPageRegistry.getByPageMenuTarget({
|
||||
pageId: "test-page",
|
||||
extensionId: ext.name
|
||||
})
|
||||
expect(page.id).toEqual("test-page")
|
||||
})
|
||||
|
||||
it("returns null if target not found", () => {
|
||||
const page = globalPageRegistry.getByPageMenuTarget({
|
||||
pageId: "wrong-page",
|
||||
extensionId: ext.name
|
||||
})
|
||||
expect(page).toBeNull()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,17 +1,26 @@
|
||||
// Base class for extensions-api registries
|
||||
import { observable } from "mobx";
|
||||
import { action, observable } from "mobx";
|
||||
import { LensExtension } from "../lens-extension";
|
||||
|
||||
export class BaseRegistry<T = any> {
|
||||
protected items = observable<T>([], { deep: false });
|
||||
export class BaseRegistry<T = object, I extends T = T> {
|
||||
private items = observable<T>([], { deep: false });
|
||||
|
||||
getItems(): T[] {
|
||||
return this.items.toJS();
|
||||
getItems(): I[] {
|
||||
return this.items.toJS() as I[];
|
||||
}
|
||||
|
||||
add(item: T) {
|
||||
this.items.push(item);
|
||||
return () => {
|
||||
add(items: T | T[], ext?: LensExtension): () => void; // allow method overloading with required "ext"
|
||||
@action
|
||||
add(items: T | T[]) {
|
||||
const normalizedItems = (Array.isArray(items) ? items : [items])
|
||||
this.items.push(...normalizedItems);
|
||||
return () => this.remove(...normalizedItems);
|
||||
}
|
||||
|
||||
@action
|
||||
remove(...items: T[]) {
|
||||
items.forEach(item => {
|
||||
this.items.remove(item); // works because of {deep: false};
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import type React from "react"
|
||||
import { BaseRegistry } from "./base-registry";
|
||||
import { ClusterFeature } from "../cluster-feature";
|
||||
|
||||
@@ -11,6 +12,7 @@ export interface ClusterFeatureRegistration {
|
||||
feature: ClusterFeature
|
||||
}
|
||||
|
||||
export class ClusterFeatureRegistry extends BaseRegistry<ClusterFeatureRegistration> {}
|
||||
export class ClusterFeatureRegistry extends BaseRegistry<ClusterFeatureRegistration> {
|
||||
}
|
||||
|
||||
export const clusterFeatureRegistry = new ClusterFeatureRegistry()
|
||||
@@ -1,9 +1,11 @@
|
||||
// All registries managed by extensions api
|
||||
|
||||
export * from "./page-registry"
|
||||
export * from "./page-menu-registry"
|
||||
export * from "./menu-registry"
|
||||
export * from "./app-preference-registry"
|
||||
export * from "./status-bar-registry"
|
||||
export * from "./kube-object-detail-registry";
|
||||
export * from "./kube-object-menu-registry";
|
||||
export * from "./cluster-feature-registry"
|
||||
export * from "./kube-object-status-registry"
|
||||
@@ -9,13 +9,20 @@ export interface KubeObjectDetailRegistration {
|
||||
kind: string;
|
||||
apiVersions: string[];
|
||||
components: KubeObjectDetailComponents;
|
||||
priority?: number;
|
||||
}
|
||||
|
||||
export class KubeObjectDetailRegistry extends BaseRegistry<KubeObjectDetailRegistration> {
|
||||
getItemsForKind(kind: string, apiVersion: string) {
|
||||
return this.items.filter((item) => {
|
||||
const items = this.getItems().filter((item) => {
|
||||
return item.kind === kind && item.apiVersions.includes(apiVersion)
|
||||
}).map((item) => {
|
||||
if (item.priority === null) {
|
||||
item.priority = 50
|
||||
}
|
||||
return item
|
||||
})
|
||||
return items.sort((a, b) => b.priority - a.priority)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ export interface KubeObjectMenuRegistration {
|
||||
|
||||
export class KubeObjectMenuRegistry extends BaseRegistry<KubeObjectMenuRegistration> {
|
||||
getItemsForKind(kind: string, apiVersion: string) {
|
||||
return this.items.filter((item) => {
|
||||
return this.getItems().filter((item) => {
|
||||
return item.kind === kind && item.apiVersions.includes(apiVersion)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { KubeObject, KubeObjectStatus } from "../renderer-api/k8s-api";
|
||||
import { BaseRegistry } from "./base-registry";
|
||||
|
||||
export interface KubeObjectStatusRegistration {
|
||||
kind: string;
|
||||
apiVersions: string[];
|
||||
resolve: (object: KubeObject) => KubeObjectStatus;
|
||||
}
|
||||
|
||||
export class KubeObjectStatusRegistry extends BaseRegistry<KubeObjectStatusRegistration> {
|
||||
getItemsForKind(kind: string, apiVersion: string) {
|
||||
return this.getItems().filter((item) => {
|
||||
return item.kind === kind && item.apiVersions.includes(apiVersion)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export const kubeObjectStatusRegistry = new KubeObjectStatusRegistry();
|
||||
@@ -0,0 +1,39 @@
|
||||
// Extensions-api -> Register page menu items
|
||||
import type { IconProps } from "../../renderer/components/icon";
|
||||
import type React from "react";
|
||||
import { action } from "mobx";
|
||||
import { BaseRegistry } from "./base-registry";
|
||||
import { LensExtension } from "../lens-extension";
|
||||
|
||||
export interface PageMenuTarget<P extends object = any> {
|
||||
extensionId?: string;
|
||||
pageId?: string;
|
||||
params?: P;
|
||||
}
|
||||
|
||||
export interface PageMenuRegistration {
|
||||
target?: PageMenuTarget;
|
||||
title: React.ReactNode;
|
||||
components: PageMenuComponents;
|
||||
}
|
||||
|
||||
export interface PageMenuComponents {
|
||||
Icon: React.ComponentType<IconProps>;
|
||||
}
|
||||
|
||||
export class PageMenuRegistry extends BaseRegistry<PageMenuRegistration, Required<PageMenuRegistration>> {
|
||||
@action
|
||||
add(items: PageMenuRegistration[], ext: LensExtension) {
|
||||
const normalizedItems = items.map(menuItem => {
|
||||
menuItem.target = {
|
||||
extensionId: ext.name,
|
||||
...(menuItem.target || {}),
|
||||
};
|
||||
return menuItem
|
||||
})
|
||||
return super.add(normalizedItems);
|
||||
}
|
||||
}
|
||||
|
||||
export const globalPageMenuRegistry = new PageMenuRegistry();
|
||||
export const clusterPageMenuRegistry = new PageMenuRegistry();
|
||||
@@ -1,31 +1,96 @@
|
||||
// Extensions-api -> Custom page registration
|
||||
|
||||
import type { PageMenuTarget } from "./page-menu-registry";
|
||||
import type React from "react";
|
||||
import type { RouteProps } from "react-router";
|
||||
import type { IconProps } from "../../renderer/components/icon";
|
||||
import type { IClassName } from "../../renderer/utils";
|
||||
import type { TabRoute } from "../../renderer/components/layout/tab-layout";
|
||||
import path from "path";
|
||||
import { action } from "mobx";
|
||||
import { compile } from "path-to-regexp";
|
||||
import { BaseRegistry } from "./base-registry";
|
||||
import { LensExtension } from "../lens-extension";
|
||||
import logger from "../../main/logger";
|
||||
|
||||
export interface PageRegistration extends RouteProps {
|
||||
className?: IClassName;
|
||||
url?: string; // initial url to be used for building menus and tabs, otherwise "path" applied by default
|
||||
title?: React.ReactNode; // used in sidebar's & tabs-layout if provided
|
||||
hideInMenu?: boolean; // hide element within app's navigation menu
|
||||
subPages?: (PageRegistration & TabRoute)[];
|
||||
export interface PageRegistration {
|
||||
/**
|
||||
* Page ID or additional route path to indicate uniqueness within current extension registered pages
|
||||
* Might contain special url placeholders, e.g. "/users/:userId?" (? - marks as optional param)
|
||||
* When not provided, first registered page without "id" would be used for page-menus without target.pageId for same extension
|
||||
*/
|
||||
id?: string;
|
||||
/**
|
||||
* Alias to page ID which assume to be used as path with possible :param placeholders
|
||||
* @deprecated
|
||||
*/
|
||||
routePath?: string;
|
||||
/**
|
||||
* Strict route matching to provided page-id, read also: https://reactrouter.com/web/api/NavLink/exact-bool
|
||||
* In case when more than one page registered at same extension "pageId" is required to identify different pages,
|
||||
* It might be useful to provide `exact: true` in some cases to avoid overlapping routes.
|
||||
* Without {exact:true} second page never matches since first page-id/route already includes partial route.
|
||||
* @example const pages = [
|
||||
* {id: "/users", exact: true},
|
||||
* {id: "/users/:userId?"}
|
||||
* ]
|
||||
* Pro-tip: registering pages in opposite order will make same effect without "exact".
|
||||
*/
|
||||
exact?: boolean;
|
||||
components: PageComponents;
|
||||
}
|
||||
|
||||
export interface RegisteredPage extends PageRegistration {
|
||||
extensionId: string; // required for compiling registered page to url with page-menu-target to compare
|
||||
routePath: string; // full route-path to registered extension page
|
||||
}
|
||||
|
||||
export interface PageComponents {
|
||||
Page: React.ComponentType<any>;
|
||||
MenuIcon?: React.ComponentType<IconProps>;
|
||||
}
|
||||
|
||||
export class GlobalPageRegistry extends BaseRegistry<PageRegistration> {
|
||||
export function sanitizeExtensionName(name: string) {
|
||||
return name.replace("@", "").replace("/", "-")
|
||||
}
|
||||
|
||||
export class ClusterPageRegistry extends BaseRegistry<PageRegistration> {
|
||||
export function getExtensionPageUrl<P extends object>({ extensionId, pageId = "", params }: PageMenuTarget<P>): string {
|
||||
const extensionBaseUrl = compile(`/extension/:name`)({
|
||||
name: sanitizeExtensionName(extensionId), // compile only with extension-id first and define base path
|
||||
});
|
||||
const extPageRoutePath = path.join(extensionBaseUrl, pageId); // page-id might contain route :param-s, so don't compile yet
|
||||
if (params) {
|
||||
return compile(extPageRoutePath)(params); // might throw error when required params not passed
|
||||
}
|
||||
return extPageRoutePath;
|
||||
}
|
||||
|
||||
export const globalPageRegistry = new GlobalPageRegistry();
|
||||
export const clusterPageRegistry = new ClusterPageRegistry();
|
||||
export class PageRegistry extends BaseRegistry<PageRegistration, RegisteredPage> {
|
||||
@action
|
||||
add(items: PageRegistration[], ext: LensExtension) {
|
||||
let registeredPages: RegisteredPage[] = [];
|
||||
try {
|
||||
registeredPages = items.map(page => ({
|
||||
...page,
|
||||
extensionId: ext.name,
|
||||
routePath: getExtensionPageUrl({ extensionId: ext.name, pageId: page.id ?? page.routePath }),
|
||||
}))
|
||||
} catch (err) {
|
||||
logger.error(`[EXTENSION]: page-registration failed`, {
|
||||
items,
|
||||
extension: ext,
|
||||
error: String(err),
|
||||
})
|
||||
}
|
||||
return super.add(registeredPages);
|
||||
}
|
||||
|
||||
getUrl<P extends object>({ extensionId, id: pageId }: RegisteredPage, params?: P) {
|
||||
return getExtensionPageUrl({ extensionId, pageId, params });
|
||||
}
|
||||
|
||||
getByPageMenuTarget(target: PageMenuTarget = {}): RegisteredPage | null {
|
||||
const targetUrl = getExtensionPageUrl(target);
|
||||
return this.getItems().find(({ id: pageId, extensionId }) => {
|
||||
const pageUrl = getExtensionPageUrl({ extensionId, pageId, params: target.params }); // compiled with provided params
|
||||
return targetUrl === pageUrl;
|
||||
}) || null;
|
||||
}
|
||||
}
|
||||
|
||||
export const globalPageRegistry = new PageRegistry();
|
||||
export const clusterPageRegistry = new PageRegistry();
|
||||
@@ -1,23 +1,38 @@
|
||||
// TODO: add more common re-usable UI components + refactor interfaces (Props -> ComponentProps)
|
||||
// Common UI components
|
||||
|
||||
export * from "../../renderer/components/icon"
|
||||
export * from "../../renderer/components/checkbox"
|
||||
export * from "../../renderer/components/tooltip"
|
||||
export * from "../../renderer/components/button"
|
||||
export * from "../../renderer/components/tabs"
|
||||
export * from "../../renderer/components/badge"
|
||||
// layouts
|
||||
export * from "../../renderer/components/layout/page-layout"
|
||||
export * from "../../renderer/components/layout/wizard-layout"
|
||||
export * from "../../renderer/components/layout/tab-layout"
|
||||
|
||||
// form-controls
|
||||
export * from "../../renderer/components/button"
|
||||
export * from "../../renderer/components/checkbox"
|
||||
export * from "../../renderer/components/radio"
|
||||
export * from "../../renderer/components/select"
|
||||
export * from "../../renderer/components/slider"
|
||||
export * from "../../renderer/components/input/input"
|
||||
|
||||
// other components
|
||||
export * from "../../renderer/components/icon"
|
||||
export * from "../../renderer/components/tooltip"
|
||||
export * from "../../renderer/components/tabs"
|
||||
export * from "../../renderer/components/table"
|
||||
export * from "../../renderer/components/badge"
|
||||
export * from "../../renderer/components/drawer"
|
||||
export * from "../../renderer/components/dialog"
|
||||
export * from "../../renderer/components/confirm-dialog";
|
||||
export * from "../../renderer/components/line-progress"
|
||||
export * from "../../renderer/components/menu"
|
||||
export * from "../../renderer/components/notifications"
|
||||
export * from "../../renderer/components/spinner"
|
||||
export * from "../../renderer/components/stepper"
|
||||
|
||||
// kube helpers
|
||||
export { KubeObjectDetailsProps, KubeObjectMenuProps } from "../../renderer/components/kube-object"
|
||||
export { KubeObjectMeta } from "../../renderer/components/kube-object/kube-object-meta"
|
||||
export { KubeObjectListLayout, KubeObjectListLayoutProps } from "../../renderer/components/kube-object/kube-object-list-layout";
|
||||
export { KubeEventDetails } from "../../renderer/components/+events/kube-event-details"
|
||||
export * from "../../renderer/components/kube-object"
|
||||
export * from "../../renderer/components/+events/kube-event-details"
|
||||
|
||||
// specific exports
|
||||
export { ConfirmDialog } from "../../renderer/components/confirm-dialog";
|
||||
export { MenuItem, SubMenu } from "../../renderer/components/menu";
|
||||
export { StatusBrick } from "../../renderer/components/status-brick";
|
||||
export * from "../../renderer/components/status-brick";
|
||||
export { terminalStore, createTerminalTab } from "../../renderer/components/dock/terminal.store";
|
||||
export { createPodLogsTab } from "../../renderer/components/dock/pod-logs.store";
|
||||
@@ -4,9 +4,11 @@
|
||||
import * as Component from "./components"
|
||||
import * as K8sApi from "./k8s-api"
|
||||
import * as Navigation from "./navigation"
|
||||
import * as Theme from "./theming"
|
||||
|
||||
export {
|
||||
Component,
|
||||
K8sApi,
|
||||
Navigation,
|
||||
Theme,
|
||||
}
|
||||
@@ -3,24 +3,25 @@ export { apiManager } from "../../renderer/api/api-manager";
|
||||
export { KubeObjectStore } from "../../renderer/kube-object.store"
|
||||
export { KubeApi, forCluster, IKubeApiCluster } from "../../renderer/api/kube-api";
|
||||
export { KubeObject } from "../../renderer/api/kube-object";
|
||||
export { Pod, podsApi, IPodContainer, IPodContainerStatus } from "../../renderer/api/endpoints";
|
||||
export { Node, nodesApi } from "../../renderer/api/endpoints";
|
||||
export { Deployment, deploymentApi } from "../../renderer/api/endpoints";
|
||||
export { Pod, podsApi, PodsApi, IPodContainer, IPodContainerStatus } from "../../renderer/api/endpoints";
|
||||
export { Node, nodesApi, NodesApi } from "../../renderer/api/endpoints";
|
||||
export { Deployment, deploymentApi, DeploymentApi } from "../../renderer/api/endpoints";
|
||||
export { DaemonSet, daemonSetApi } from "../../renderer/api/endpoints";
|
||||
export { StatefulSet, statefulSetApi } from "../../renderer/api/endpoints";
|
||||
export { Job, jobApi } from "../../renderer/api/endpoints";
|
||||
export { CronJob, cronJobApi } from "../../renderer/api/endpoints";
|
||||
export { ConfigMap, configMapApi } from "../../renderer/api/endpoints";
|
||||
export { Secret, secretsApi, ISecretRef } from "../../renderer/api/endpoints";
|
||||
export { ReplicaSet, replicaSetApi } from "../../renderer/api/endpoints";
|
||||
export { ResourceQuota, resourceQuotaApi } from "../../renderer/api/endpoints";
|
||||
export { HorizontalPodAutoscaler, hpaApi } from "../../renderer/api/endpoints";
|
||||
export { PodDisruptionBudget, pdbApi } from "../../renderer/api/endpoints";
|
||||
export { Service, serviceApi } from "../../renderer/api/endpoints";
|
||||
export { Endpoint, endpointApi } from "../../renderer/api/endpoints";
|
||||
export { Ingress, ingressApi } from "../../renderer/api/endpoints";
|
||||
export { Ingress, ingressApi, IngressApi } from "../../renderer/api/endpoints";
|
||||
export { NetworkPolicy, networkPolicyApi } from "../../renderer/api/endpoints";
|
||||
export { PersistentVolume, persistentVolumeApi } from "../../renderer/api/endpoints";
|
||||
export { PersistentVolumeClaim, PersistentVolumeClaimsApi } from "../../renderer/api/endpoints";
|
||||
export { PersistentVolumeClaim, pvcApi, PersistentVolumeClaimsApi } from "../../renderer/api/endpoints";
|
||||
export { StorageClass, storageClassApi } from "../../renderer/api/endpoints";
|
||||
export { Namespace, namespacesApi } from "../../renderer/api/endpoints";
|
||||
export { KubeEvent, eventApi } from "../../renderer/api/endpoints";
|
||||
@@ -29,3 +30,34 @@ export { Role, roleApi } from "../../renderer/api/endpoints";
|
||||
export { RoleBinding, roleBindingApi } from "../../renderer/api/endpoints";
|
||||
export { ClusterRole, clusterRoleApi } from "../../renderer/api/endpoints";
|
||||
export { ClusterRoleBinding, clusterRoleBindingApi } from "../../renderer/api/endpoints";
|
||||
export { CustomResourceDefinition, crdApi } from "../../renderer/api/endpoints";
|
||||
export { KubeObjectStatus, KubeObjectStatusLevel } from "./kube-object-status"
|
||||
|
||||
// stores
|
||||
export type { EventStore } from "../../renderer/components/+events/event.store"
|
||||
export type { PodsStore } from "../../renderer/components/+workloads-pods/pods.store"
|
||||
export type { NodesStore } from "../../renderer/components/+nodes/nodes.store"
|
||||
export type { DeploymentStore } from "../../renderer/components/+workloads-deployments/deployments.store"
|
||||
export type { DaemonSetStore } from "../../renderer/components/+workloads-daemonsets/daemonsets.store"
|
||||
export type { StatefulSetStore } from "../../renderer/components/+workloads-statefulsets/statefulset.store"
|
||||
export type { JobStore } from "../../renderer/components/+workloads-jobs/job.store"
|
||||
export type { CronJobStore } from "../../renderer/components/+workloads-cronjobs/cronjob.store"
|
||||
export type { ConfigMapsStore } from "../../renderer/components/+config-maps/config-maps.store"
|
||||
export type { SecretsStore } from "../../renderer/components/+config-secrets/secrets.store"
|
||||
export type { ReplicaSetStore } from "../../renderer/components/+workloads-replicasets/replicasets.store"
|
||||
export type { ResourceQuotasStore } from "../../renderer/components/+config-resource-quotas/resource-quotas.store"
|
||||
export type { HPAStore } from "../../renderer/components/+config-autoscalers/hpa.store"
|
||||
export type { PodDisruptionBudgetsStore } from "../../renderer/components/+config-pod-disruption-budgets/pod-disruption-budgets.store"
|
||||
export type { ServiceStore } from "../../renderer/components/+network-services/services.store"
|
||||
export type { EndpointStore } from "../../renderer/components/+network-endpoints/endpoints.store"
|
||||
export type { IngressStore } from "../../renderer/components/+network-ingresses/ingress.store"
|
||||
export type { NetworkPolicyStore } from "../../renderer/components/+network-policies/network-policy.store"
|
||||
export type { PersistentVolumesStore } from "../../renderer/components/+storage-volumes/volumes.store"
|
||||
export type { VolumeClaimStore } from "../../renderer/components/+storage-volume-claims/volume-claim.store"
|
||||
export type { StorageClassStore } from "../../renderer/components/+storage-classes/storage-class.store"
|
||||
export type { NamespaceStore } from "../../renderer/components/+namespaces/namespace.store"
|
||||
export type { ServiceAccountsStore } from "../../renderer/components/+user-management-service-accounts/service-accounts.store"
|
||||
export type { RolesStore } from "../../renderer/components/+user-management-roles/roles.store"
|
||||
export type { RoleBindingsStore } from "../../renderer/components/+user-management-roles-bindings/role-bindings.store"
|
||||
export type { CRDStore } from "../../renderer/components/+custom-resources/crd.store"
|
||||
export type { CRDResourceStore } from "../../renderer/components/+custom-resources/crd-resource.store"
|
||||
@@ -0,0 +1,11 @@
|
||||
export type KubeObjectStatus = {
|
||||
level: KubeObjectStatusLevel;
|
||||
text: string;
|
||||
timestamp?: string;
|
||||
}
|
||||
|
||||
export enum KubeObjectStatusLevel {
|
||||
INFO = 1,
|
||||
WARNING = 2,
|
||||
CRITICAL = 3
|
||||
}
|
||||
@@ -1,3 +1,3 @@
|
||||
export { navigate, hideDetails, showDetails, getDetailsUrl } from "../../renderer/navigation"
|
||||
export { RouteProps } from "react-router"
|
||||
export { navigate } from "../../renderer/navigation";
|
||||
export { hideDetails, showDetails, getDetailsUrl } from "../../renderer/navigation"
|
||||
export { IURLParams } from "../../common/utils/buildUrl";
|
||||
@@ -0,0 +1,5 @@
|
||||
import { themeStore } from "../../renderer/theme.store";
|
||||
|
||||
export function getActiveTheme() {
|
||||
return themeStore.activeTheme;
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
// Workaround for using Typescript in Rollup configutation
|
||||
// https://stackoverflow.com/questions/54711437/does-rollup-support-typescript-in-rollup-config-file
|
||||
|
||||
require('ts-node').register();
|
||||
module.exports = require('./rollup.config.ts');
|
||||
@@ -1,57 +0,0 @@
|
||||
// Generating declaration types for extensions-api
|
||||
// Rollup: https://rollupjs.org/guide/en/
|
||||
// Plugin docs: https://github.com/Swatinem/rollup-plugin-dts
|
||||
|
||||
import { OutputChunk, Plugin, RollupOptions } from 'rollup';
|
||||
import json from '@rollup/plugin-json';
|
||||
import dts from "rollup-plugin-dts";
|
||||
import ignoreImport from 'rollup-plugin-ignore-import'
|
||||
|
||||
const config: RollupOptions = {
|
||||
input: "src/extensions/extension-api.ts",
|
||||
output: [
|
||||
{ file: "src/extensions/npm/extensions/api.d.ts", format: "es", }
|
||||
],
|
||||
plugins: [
|
||||
dts(),
|
||||
dtsModuleWrap({ name: "@k8slens/extensions" }),
|
||||
ignoreImport({ extensions: ['.scss'] }),
|
||||
json(),
|
||||
],
|
||||
};
|
||||
|
||||
function dtsModuleWrap({ name }: { name: string }): Plugin {
|
||||
return {
|
||||
name,
|
||||
generateBundle: (options, bundle) => {
|
||||
const apiTypes = Object.values(bundle)[0] as OutputChunk; // extension-api.d.ts
|
||||
const typeRefs: string[] = []
|
||||
const declarations: string[] = []
|
||||
const apiLines = apiTypes.code.split("\n")
|
||||
let outputCode = ""
|
||||
|
||||
apiLines.forEach(line => {
|
||||
if (line.startsWith("///")) {
|
||||
typeRefs.push(line)
|
||||
} else {
|
||||
declarations.push(line)
|
||||
}
|
||||
})
|
||||
|
||||
// print external @types refs first
|
||||
if (typeRefs.length) {
|
||||
outputCode += typeRefs.join("\n") + "\n\n"
|
||||
}
|
||||
|
||||
// wrap declarations into global module definition
|
||||
outputCode += `declare module "${name}" {\n`
|
||||
outputCode += declarations.map(line => `\t${line}`).join("\n")
|
||||
outputCode += `\n}`
|
||||
|
||||
// save
|
||||
apiTypes.code = outputCode;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default [config];
|
||||
@@ -6,9 +6,11 @@ import { clusterStore, getClusterIdFromHost } from "../common/cluster-store"
|
||||
import { Cluster } from "./cluster"
|
||||
import logger from "./logger";
|
||||
import { apiKubePrefix } from "../common/vars";
|
||||
import { Singleton } from "../common/utils";
|
||||
|
||||
export class ClusterManager {
|
||||
export class ClusterManager extends Singleton {
|
||||
constructor(public readonly port: number) {
|
||||
super()
|
||||
// auto-init clusters
|
||||
autorun(() => {
|
||||
clusterStore.enabledClustersList.forEach(cluster => {
|
||||
|
||||
+24
-19
@@ -80,13 +80,18 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
@observable metadata: ClusterMetadata = {};
|
||||
@observable allowedNamespaces: string[] = [];
|
||||
@observable allowedResources: string[] = [];
|
||||
@observable accessibleNamespaces: string[] = [];
|
||||
|
||||
@computed get available() {
|
||||
return this.accessible && !this.disconnected;
|
||||
}
|
||||
|
||||
@computed get name() {
|
||||
return this.preferences.clusterName || this.contextName
|
||||
}
|
||||
|
||||
get version(): string {
|
||||
return String(this.metadata?.version) || ""
|
||||
return String(this.metadata?.version) || ""
|
||||
}
|
||||
|
||||
constructor(model: ClusterModel) {
|
||||
@@ -149,7 +154,7 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
}
|
||||
|
||||
@action
|
||||
async activate(force = false ) {
|
||||
async activate(force = false) {
|
||||
if (this.activated && !force) {
|
||||
return this.pushState();
|
||||
}
|
||||
@@ -252,16 +257,12 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
}
|
||||
|
||||
protected async k8sRequest<T = any>(path: string, options: RequestPromiseOptions = {}): Promise<T> {
|
||||
const apiUrl = this.kubeProxyUrl + path;
|
||||
return request(apiUrl, {
|
||||
json: true,
|
||||
timeout: 30000,
|
||||
...options,
|
||||
headers: {
|
||||
Host: `${this.id}.${new URL(this.kubeProxyUrl).host}`, // required in ClusterManager.getClusterForRequest()
|
||||
...(options.headers || {}),
|
||||
},
|
||||
})
|
||||
options.headers ??= {}
|
||||
options.json ??= true
|
||||
options.timeout ??= 30000
|
||||
options.headers.Host = `${this.id}.${new URL(this.kubeProxyUrl).host}` // required in ClusterManager.getClusterForRequest()
|
||||
|
||||
return request(this.kubeProxyUrl + path, options)
|
||||
}
|
||||
|
||||
getMetrics(prometheusPath: string, queryParams: IMetricsReqParams & { query: string }) {
|
||||
@@ -340,7 +341,7 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
for (const w of warnings) {
|
||||
if (w.involvedObject.kind === 'Pod') {
|
||||
try {
|
||||
const pod = (await client.readNamespacedPod(w.involvedObject.name, w.involvedObject.namespace)).body;
|
||||
const { body: pod } = await client.readNamespacedPod(w.involvedObject.name, w.involvedObject.namespace);
|
||||
logger.debug(`checking pod ${w.involvedObject.namespace}/${w.involvedObject.name}`)
|
||||
if (podHasIssues(pod)) {
|
||||
uniqEventSources.add(w.involvedObject.uid);
|
||||
@@ -351,11 +352,10 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
uniqEventSources.add(w.involvedObject.uid);
|
||||
}
|
||||
}
|
||||
let nodeNotificationCount = 0;
|
||||
const nodes = (await client.listNode()).body.items;
|
||||
nodes.map(n => {
|
||||
nodeNotificationCount = nodeNotificationCount + getNodeWarningConditions(n).length
|
||||
});
|
||||
const nodeNotificationCount = nodes
|
||||
.map(getNodeWarningConditions)
|
||||
.reduce((sum, conditions) => sum + conditions.length, 0);
|
||||
return uniqEventSources.size + nodeNotificationCount;
|
||||
} catch (error) {
|
||||
logger.error("Failed to fetch event count: " + JSON.stringify(error))
|
||||
@@ -371,7 +371,8 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
workspace: this.workspace,
|
||||
preferences: this.preferences,
|
||||
metadata: this.metadata,
|
||||
ownerRef: this.ownerRef
|
||||
ownerRef: this.ownerRef,
|
||||
accessibleNamespaces: this.accessibleNamespaces,
|
||||
};
|
||||
return toJS(model, {
|
||||
recurseEverything: true
|
||||
@@ -422,6 +423,10 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
}
|
||||
|
||||
protected async getAllowedNamespaces() {
|
||||
if (this.accessibleNamespaces.length) {
|
||||
return this.accessibleNamespaces
|
||||
}
|
||||
|
||||
const api = this.getProxyKubeconfig().makeApiClient(CoreV1Api)
|
||||
try {
|
||||
const namespaceList = await api.listNamespace()
|
||||
@@ -438,7 +443,7 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
} catch (error) {
|
||||
const ctx = this.getProxyKubeconfig().getContextObject(this.contextName)
|
||||
if (ctx.namespace) return [ctx.namespace]
|
||||
return []
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { app } from "electron";
|
||||
import { WindowManager } from "./window-manager";
|
||||
import { appEventBus } from "../common/event-bus";
|
||||
import { ClusterManager } from "./cluster-manager";
|
||||
import logger from "./logger";
|
||||
|
||||
|
||||
export function exitApp() {
|
||||
const windowManager = WindowManager.getInstance<WindowManager>()
|
||||
const clusterManager = ClusterManager.getInstance<ClusterManager>()
|
||||
appEventBus.emit({ name: "service", action: "close" })
|
||||
windowManager.hide();
|
||||
clusterManager.stop();
|
||||
logger.info('SERVICE:QUIT');
|
||||
setTimeout(() => {
|
||||
app.exit()
|
||||
}, 1000)
|
||||
}
|
||||
+10
-11
@@ -15,13 +15,14 @@ import { shellSync } from "./shell-sync"
|
||||
import { getFreePort } from "./port"
|
||||
import { mangleProxyEnv } from "./proxy-env"
|
||||
import { registerFileProtocol } from "../common/register-protocol";
|
||||
import logger from "./logger"
|
||||
import { clusterStore } from "../common/cluster-store"
|
||||
import { userStore } from "../common/user-store";
|
||||
import { workspaceStore } from "../common/workspace-store";
|
||||
import { appEventBus } from "../common/event-bus"
|
||||
import { extensionManager } from "../extensions/extension-manager";
|
||||
import { extensionLoader } from "../extensions/extension-loader";
|
||||
import logger from "./logger"
|
||||
import { extensionManager } from "../extensions/extension-manager";
|
||||
import { extensionsStore } from "../extensions/extensions-store";
|
||||
|
||||
const workingDir = path.join(app.getPath("appData"), appName);
|
||||
let proxyPort: number;
|
||||
@@ -48,11 +49,12 @@ app.on("ready", async () => {
|
||||
|
||||
registerFileProtocol("static", __static);
|
||||
|
||||
// preload isomorphic stores
|
||||
// preload
|
||||
await Promise.all([
|
||||
userStore.load(),
|
||||
clusterStore.load(),
|
||||
workspaceStore.load(),
|
||||
extensionsStore.load(),
|
||||
]);
|
||||
|
||||
// find free port
|
||||
@@ -65,7 +67,7 @@ app.on("ready", async () => {
|
||||
}
|
||||
|
||||
// create cluster manager
|
||||
clusterManager = new ClusterManager(proxyPort);
|
||||
clusterManager = ClusterManager.getInstance<ClusterManager>(proxyPort);
|
||||
|
||||
// run proxy
|
||||
try {
|
||||
@@ -76,15 +78,11 @@ app.on("ready", async () => {
|
||||
app.exit();
|
||||
}
|
||||
|
||||
windowManager = new WindowManager(proxyPort);
|
||||
|
||||
LensExtensionsApi.windowManager = windowManager; // expose to extensions
|
||||
extensionLoader.loadOnMain()
|
||||
extensionLoader.extensions.replace(await extensionManager.load())
|
||||
extensionLoader.broadcastExtensions()
|
||||
windowManager = WindowManager.getInstance<WindowManager>(proxyPort);
|
||||
extensionLoader.init(await extensionManager.load()); // call after windowManager to see splash earlier
|
||||
|
||||
setTimeout(() => {
|
||||
appEventBus.emit({ name: "app", action: "start" })
|
||||
appEventBus.emit({ name: "service", action: "start" })
|
||||
}, 1000)
|
||||
});
|
||||
|
||||
@@ -98,6 +96,7 @@ app.on("activate", (event, hasVisibleWindows) => {
|
||||
// Quit app on Cmd+Q (MacOS)
|
||||
app.on("will-quit", (event) => {
|
||||
logger.info('APP:QUIT');
|
||||
appEventBus.emit({name: "app", action: "close"})
|
||||
event.preventDefault(); // prevent app's default shutdown (e.g. required for telemetry, etc.)
|
||||
clusterManager?.stop(); // close cluster connections
|
||||
return; // skip exit to make tray work, to quit go to app's global menu or tray's menu
|
||||
|
||||
@@ -131,7 +131,11 @@ export class LensProxy {
|
||||
}
|
||||
}
|
||||
}
|
||||
res.writeHead(500).end("Oops, something went wrong.")
|
||||
try {
|
||||
res.writeHead(500).end("Oops, something went wrong.")
|
||||
} catch (e) {
|
||||
logger.error(`[LENS-PROXY]: Failed to write headers: `, e)
|
||||
}
|
||||
})
|
||||
|
||||
return proxy;
|
||||
|
||||
+73
-6
@@ -1,13 +1,15 @@
|
||||
import { app, BrowserWindow, dialog, Menu, MenuItem, MenuItemConstructorOptions, webContents } from "electron"
|
||||
import { app, BrowserWindow, dialog, ipcMain, IpcMainEvent, Menu, MenuItem, MenuItemConstructorOptions, webContents, shell } from "electron"
|
||||
import { autorun } from "mobx";
|
||||
import { WindowManager } from "./window-manager";
|
||||
import { appName, isMac, isWindows } from "../common/vars";
|
||||
import { appName, isMac, isWindows, isTestEnv } from "../common/vars";
|
||||
import { addClusterURL } from "../renderer/components/+add-cluster/add-cluster.route";
|
||||
import { preferencesURL } from "../renderer/components/+preferences/preferences.route";
|
||||
import { whatsNewURL } from "../renderer/components/+whats-new/whats-new.route";
|
||||
import { clusterSettingsURL } from "../renderer/components/+cluster-settings/cluster-settings.route";
|
||||
import { extensionsURL } from "../renderer/components/+extensions/extensions.route";
|
||||
import { menuRegistry } from "../extensions/registries/menu-registry";
|
||||
import logger from "./logger";
|
||||
import { exitApp } from "./exit-app";
|
||||
|
||||
export type MenuTopId = "mac" | "file" | "edit" | "view" | "help"
|
||||
|
||||
@@ -70,6 +72,13 @@ export function buildMenu(windowManager: WindowManager) {
|
||||
navigate(preferencesURL())
|
||||
}
|
||||
},
|
||||
{
|
||||
label: 'Extensions',
|
||||
accelerator: 'CmdOrCtrl+Shift+E',
|
||||
click() {
|
||||
navigate(extensionsURL())
|
||||
}
|
||||
},
|
||||
{ type: 'separator' },
|
||||
{ role: 'services' },
|
||||
{ type: 'separator' },
|
||||
@@ -81,7 +90,7 @@ export function buildMenu(windowManager: WindowManager) {
|
||||
label: 'Quit',
|
||||
accelerator: 'Cmd+Q',
|
||||
click() {
|
||||
app.exit(); // force quit since might be blocked within app.on("will-quit")
|
||||
exitApp()
|
||||
}
|
||||
}
|
||||
]
|
||||
@@ -119,11 +128,29 @@ export function buildMenu(windowManager: WindowManager) {
|
||||
navigate(preferencesURL())
|
||||
}
|
||||
},
|
||||
{ type: 'separator' },
|
||||
{ role: 'quit' }
|
||||
{
|
||||
label: 'Extensions',
|
||||
accelerator: 'Ctrl+Shift+E',
|
||||
click() {
|
||||
navigate(extensionsURL())
|
||||
}
|
||||
}
|
||||
]),
|
||||
{ type: 'separator' },
|
||||
{ role: 'close' } // close current window
|
||||
{
|
||||
role: 'close',
|
||||
label: "Close Window"
|
||||
},
|
||||
...ignoreOnMac([
|
||||
{ type: 'separator' },
|
||||
{
|
||||
label: 'Exit',
|
||||
accelerator: 'Alt+F4',
|
||||
click() {
|
||||
exitApp()
|
||||
}
|
||||
}
|
||||
])
|
||||
]
|
||||
};
|
||||
|
||||
@@ -185,6 +212,12 @@ export function buildMenu(windowManager: WindowManager) {
|
||||
navigate(whatsNewURL())
|
||||
},
|
||||
},
|
||||
{
|
||||
label: "Documentation",
|
||||
click: async () => {
|
||||
shell.openExternal('https://docs.k8slens.dev/');
|
||||
},
|
||||
},
|
||||
...ignoreOnMac([
|
||||
{
|
||||
label: "About Lens",
|
||||
@@ -221,4 +254,38 @@ export function buildMenu(windowManager: WindowManager) {
|
||||
|
||||
const menu = Menu.buildFromTemplate(Object.values(appMenu));
|
||||
Menu.setApplicationMenu(menu);
|
||||
|
||||
if (isTestEnv) {
|
||||
// this is a workaround for the test environment (spectron) not being able to directly access
|
||||
// the application menus (https://github.com/electron-userland/spectron/issues/21)
|
||||
ipcMain.on('test-menu-item-click', (event: IpcMainEvent, ...names: string[]) => {
|
||||
let menu: Menu = Menu.getApplicationMenu()
|
||||
const parentLabels: string[] = [];
|
||||
let menuItem: MenuItem
|
||||
|
||||
for (const name of names) {
|
||||
parentLabels.push(name);
|
||||
menuItem = menu?.items?.find(item => item.label === name);
|
||||
if (!menuItem) {
|
||||
break;
|
||||
}
|
||||
menu = menuItem.submenu;
|
||||
}
|
||||
|
||||
const menuPath: string = parentLabels.join(" -> ")
|
||||
if (!menuItem) {
|
||||
logger.info(`[MENU:test-menu-item-click] Cannot find menu item ${menuPath}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const { enabled, visible, click } = menuItem;
|
||||
if (enabled === false || visible === false || typeof click !== 'function') {
|
||||
logger.info(`[MENU:test-menu-item-click] Menu item ${menuPath} not clickable`);
|
||||
return;
|
||||
}
|
||||
|
||||
logger.info(`[MENU:test-menu-item-click] Menu item ${menuPath} click!`);
|
||||
menuItem.click();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -73,7 +73,7 @@ export class NodeShellSession extends ShellSession {
|
||||
}],
|
||||
containers: [{
|
||||
name: "shell",
|
||||
image: "docker.io/alpine:3.9",
|
||||
image: "docker.io/alpine:3.12",
|
||||
securityContext: {
|
||||
privileged: true,
|
||||
},
|
||||
|
||||
+27
-8
@@ -4,8 +4,9 @@ import http from "http"
|
||||
import path from "path"
|
||||
import { readFile } from "fs-extra"
|
||||
import { Cluster } from "./cluster"
|
||||
import { apiPrefix, appName, publicPath } from "../common/vars";
|
||||
import { apiPrefix, appName, publicPath, isDevelopment, webpackDevServerPort } from "../common/vars";
|
||||
import { helmRoute, kubeconfigRoute, metricsRoute, portForwardRoute, resourceApplierRoute, watchRoute } from "./routes";
|
||||
import logger from "./logger"
|
||||
|
||||
export interface RouterRequestOpts {
|
||||
req: http.IncomingMessage;
|
||||
@@ -94,23 +95,41 @@ export class Router {
|
||||
return mimeTypes[path.extname(filename).slice(1)] || "text/plain"
|
||||
}
|
||||
|
||||
async handleStaticFile(filePath: string, res: http.ServerResponse) {
|
||||
async handleStaticFile(filePath: string, res: http.ServerResponse, req: http.IncomingMessage, retryCount = 0) {
|
||||
const asset = path.join(__static, filePath);
|
||||
try {
|
||||
const filename = path.basename(req.url);
|
||||
// redirect requests to [appName].js, [appName].html /sockjs-node/ to webpack-dev-server (for hot-reload support)
|
||||
const toWebpackDevServer = filename.includes(appName) || filename.includes('hot-update') || req.url.includes('sockjs-node');
|
||||
if (isDevelopment && toWebpackDevServer) {
|
||||
const redirectLocation = `http://localhost:${webpackDevServerPort}` + req.url;
|
||||
res.statusCode = 307;
|
||||
res.setHeader('Location', redirectLocation);
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
const data = await readFile(asset);
|
||||
res.setHeader("Content-Type", this.getMimeType(asset));
|
||||
res.write(data)
|
||||
res.end()
|
||||
res.write(data);
|
||||
res.end();
|
||||
} catch (err) {
|
||||
this.handleStaticFile(`${publicPath}/${appName}.html`, res);
|
||||
if (retryCount > 5) {
|
||||
logger.error("handleStaticFile:", err.toString())
|
||||
res.statusCode = 404
|
||||
res.end()
|
||||
return
|
||||
}
|
||||
this.handleStaticFile(`${publicPath}/${appName}.html`, res, req, Math.max(retryCount, 0) + 1);
|
||||
}
|
||||
}
|
||||
|
||||
protected addRoutes() {
|
||||
// Static assets
|
||||
this.router.add({ method: 'get', path: '/{path*}' }, ({ params, response }: LensApiRequest) => {
|
||||
this.handleStaticFile(params.path, response);
|
||||
});
|
||||
this.router.add(
|
||||
{ method: 'get', path: '/{path*}' },
|
||||
({ params, response, path, raw: { req } }: LensApiRequest) => {
|
||||
this.handleStaticFile(params.path, response, req);
|
||||
});
|
||||
|
||||
this.router.add({ method: "get", path: `${apiPrefix}/kubeconfig/service-account/{namespace}/{account}` }, kubeconfigRoute.routeServiceAccountRoute.bind(kubeconfigRoute))
|
||||
|
||||
|
||||
@@ -1,72 +1,73 @@
|
||||
import { LensApiRequest } from "../router"
|
||||
import { LensApi } from "../lens-api"
|
||||
import { PrometheusClusterQuery, PrometheusIngressQuery, PrometheusNodeQuery, PrometheusPodQuery, PrometheusProvider, PrometheusPvcQuery, PrometheusQueryOpts } from "../prometheus/provider-registry"
|
||||
import { Cluster } from "../cluster"
|
||||
import _ from "lodash"
|
||||
|
||||
export type IMetricsQuery = string | string[] | {
|
||||
[metricName: string]: string;
|
||||
}
|
||||
|
||||
// This is used for backoff retry tracking.
|
||||
const MAX_ATTEMPTS = 5
|
||||
const ATTEMPTS = [...(_.fill(Array(MAX_ATTEMPTS - 1), false)), true]
|
||||
|
||||
// prometheus metrics loader
|
||||
async function loadMetrics(promQueries: string[], cluster: Cluster, prometheusPath: string, queryParams: Record<string, string>): Promise<any[]> {
|
||||
const queries = promQueries.map(p => p.trim())
|
||||
const loaders = new Map<string, Promise<any>>()
|
||||
|
||||
async function loadMetric(query: string): Promise<any> {
|
||||
async function loadMetricHelper(): Promise<any> {
|
||||
for (const [attempt, lastAttempt] of ATTEMPTS.entries()) { // retry
|
||||
try {
|
||||
return await cluster.getMetrics(prometheusPath, { query, ...queryParams })
|
||||
} catch (error) {
|
||||
if (lastAttempt || error?.statusCode === 404) {
|
||||
return {
|
||||
status: error.toString(),
|
||||
data: { result: [] },
|
||||
}
|
||||
}
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, (attempt + 1) * 1000)); // add delay before repeating request
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return loaders.get(query) ?? loaders.set(query, loadMetricHelper()).get(query)
|
||||
}
|
||||
|
||||
return Promise.all(queries.map(loadMetric))
|
||||
}
|
||||
|
||||
class MetricsRoute extends LensApi {
|
||||
async routeMetrics(request: LensApiRequest) {
|
||||
const { response, cluster, payload } = request
|
||||
const queryParams: IMetricsQuery = {}
|
||||
request.query.forEach((value: string, key: string) => {
|
||||
queryParams[key] = value
|
||||
})
|
||||
let prometheusPath: string
|
||||
let prometheusProvider: PrometheusProvider
|
||||
async routeMetrics({ response, cluster, payload, query }: LensApiRequest) {
|
||||
const queryParams: IMetricsQuery = Object.fromEntries(query.entries())
|
||||
|
||||
try {
|
||||
[prometheusPath, prometheusProvider] = await Promise.all([
|
||||
const [prometheusPath, prometheusProvider] = await Promise.all([
|
||||
cluster.contextHandler.getPrometheusPath(),
|
||||
cluster.contextHandler.getPrometheusProvider()
|
||||
])
|
||||
|
||||
// return data in same structure as query
|
||||
if (typeof payload === "string") {
|
||||
const [data] = await loadMetrics([payload], cluster, prometheusPath, queryParams)
|
||||
this.respondJson(response, data)
|
||||
} else if (Array.isArray(payload)) {
|
||||
const data = await loadMetrics(payload, cluster, prometheusPath, queryParams)
|
||||
this.respondJson(response, data)
|
||||
} else {
|
||||
const queries = Object.entries(payload).map(([queryName, queryOpts]) => (
|
||||
(prometheusProvider.getQueries(queryOpts) as Record<string, string>)[queryName]
|
||||
))
|
||||
const result = await loadMetrics(queries, cluster, prometheusPath, queryParams)
|
||||
const data = Object.fromEntries(Object.keys(payload).map((metricName, i) => [metricName, result[i]]))
|
||||
this.respondJson(response, data)
|
||||
}
|
||||
} catch {
|
||||
this.respondJson(response, {})
|
||||
return
|
||||
}
|
||||
// prometheus metrics loader
|
||||
const attempts: { [query: string]: number } = {};
|
||||
const maxAttempts = 5;
|
||||
const loadMetrics = (promQuery: string): Promise<any> => {
|
||||
const query = promQuery.trim()
|
||||
const attempt = attempts[query] = (attempts[query] || 0) + 1;
|
||||
return cluster.getMetrics(prometheusPath, { query, ...queryParams }).catch(async error => {
|
||||
if (attempt < maxAttempts && (error.statusCode && error.statusCode != 404)) {
|
||||
await new Promise(resolve => setTimeout(resolve, attempt * 1000)); // add delay before repeating request
|
||||
return loadMetrics(query);
|
||||
}
|
||||
return {
|
||||
status: error.toString(),
|
||||
data: {
|
||||
result: []
|
||||
}
|
||||
}
|
||||
})
|
||||
};
|
||||
|
||||
// return data in same structure as query
|
||||
let data: any;
|
||||
if (typeof payload === "string") {
|
||||
data = await loadMetrics(payload)
|
||||
} else if (Array.isArray(payload)) {
|
||||
data = await Promise.all(payload.map(loadMetrics));
|
||||
} else {
|
||||
data = {};
|
||||
const result = await Promise.all(
|
||||
Object.entries(payload).map((queryEntry: any) => {
|
||||
const queryName: string = queryEntry[0]
|
||||
const queryOpts: PrometheusQueryOpts = queryEntry[1]
|
||||
const queries = prometheusProvider.getQueries(queryOpts)
|
||||
const q = queries[queryName as keyof (PrometheusNodeQuery | PrometheusClusterQuery | PrometheusPodQuery | PrometheusPvcQuery | PrometheusIngressQuery)]
|
||||
return loadMetrics(q)
|
||||
})
|
||||
);
|
||||
Object.keys(payload).forEach((metricName, index) => {
|
||||
data[metricName] = result[index];
|
||||
});
|
||||
}
|
||||
|
||||
this.respondJson(response, data)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+5
-4
@@ -1,6 +1,6 @@
|
||||
import path from "path"
|
||||
import packageInfo from "../../package.json"
|
||||
import { app, dialog, Menu, NativeImage, nativeTheme, Tray } from "electron"
|
||||
import { dialog, Menu, NativeImage, nativeTheme, Tray } from "electron"
|
||||
import { autorun } from "mobx";
|
||||
import { showAbout } from "./menu";
|
||||
import { AppUpdater } from "./app-updater";
|
||||
@@ -11,12 +11,13 @@ import { preferencesURL } from "../renderer/components/+preferences/preferences.
|
||||
import { clusterViewURL } from "../renderer/components/cluster-manager/cluster-view.route";
|
||||
import logger from "./logger";
|
||||
import { isDevelopment } from "../common/vars";
|
||||
import { exitApp } from "./exit-app";
|
||||
|
||||
// note: instance of Tray should be saved somewhere, otherwise it disappears
|
||||
export let tray: Tray;
|
||||
|
||||
// refresh icon when MacOS dark/light theme has changed
|
||||
nativeTheme.on("updated", () => tray?.setImage(getTrayIcon()));
|
||||
nativeTheme?.on("updated", () => tray?.setImage(getTrayIcon()));
|
||||
|
||||
export function getTrayIcon(isDark = nativeTheme.shouldUseDarkColors): string {
|
||||
return path.resolve(
|
||||
@@ -88,7 +89,7 @@ export function createTrayMenu(windowManager: WindowManager): Menu {
|
||||
label: workspace.name,
|
||||
toolTip: workspace.description,
|
||||
submenu: clusters.map(cluster => {
|
||||
const { id: clusterId, preferences: { clusterName: label }, online, workspace } = cluster;
|
||||
const { id: clusterId, name: label, online, workspace } = cluster;
|
||||
return {
|
||||
label: `${online ? '✓' : '\x20'.repeat(3)/*offset*/}${label}`,
|
||||
toolTip: clusterId,
|
||||
@@ -119,7 +120,7 @@ export function createTrayMenu(windowManager: WindowManager): Menu {
|
||||
{
|
||||
label: 'Quit App',
|
||||
click() {
|
||||
app.exit();
|
||||
exitApp()
|
||||
}
|
||||
}
|
||||
]);
|
||||
|
||||
@@ -7,8 +7,9 @@ import { appEventBus } from "../common/event-bus"
|
||||
import { subscribeToBroadcast } from "../common/ipc"
|
||||
import { initMenu } from "./menu";
|
||||
import { initTray } from "./tray";
|
||||
import { Singleton } from "../common/utils";
|
||||
|
||||
export class WindowManager {
|
||||
export class WindowManager extends Singleton {
|
||||
protected mainWindow: BrowserWindow;
|
||||
protected splashWindow: BrowserWindow;
|
||||
protected windowState: windowStateKeeper.State;
|
||||
@@ -17,6 +18,7 @@ export class WindowManager {
|
||||
@observable activeClusterId: ClusterId;
|
||||
|
||||
constructor(protected proxyPort: number) {
|
||||
super();
|
||||
this.bindEvents();
|
||||
this.initMenu();
|
||||
this.initTray();
|
||||
@@ -83,6 +85,7 @@ export class WindowManager {
|
||||
await this.mainWindow.loadURL(this.mainUrl);
|
||||
this.mainWindow.show();
|
||||
this.splashWindow?.close();
|
||||
appEventBus.emit({ name: "app", action: "start" })
|
||||
} catch (err) {
|
||||
dialog.showErrorBox("ERROR!", err.toString())
|
||||
}
|
||||
@@ -120,7 +123,7 @@ export class WindowManager {
|
||||
async navigate(url: string, frameId?: number) {
|
||||
await this.ensureMainWindow();
|
||||
this.sendToView({
|
||||
channel: "menu:navigate",
|
||||
channel: "renderer:navigate",
|
||||
frameId: frameId,
|
||||
data: [url],
|
||||
})
|
||||
@@ -129,7 +132,7 @@ export class WindowManager {
|
||||
reload() {
|
||||
const frameId = clusterStore.getById(this.activeClusterId)?.frameId;
|
||||
if (frameId) {
|
||||
this.sendToView({ channel: "menu:reload", frameId });
|
||||
this.sendToView({ channel: "renderer:reload", frameId });
|
||||
} else {
|
||||
webContents.getFocusedWebContents()?.reload();
|
||||
}
|
||||
@@ -154,6 +157,11 @@ export class WindowManager {
|
||||
this.splashWindow.show();
|
||||
}
|
||||
|
||||
hide() {
|
||||
if (!this.mainWindow?.isDestroyed()) this.mainWindow.hide();
|
||||
if (!this.splashWindow.isDestroyed()) this.splashWindow.hide();
|
||||
}
|
||||
|
||||
destroy() {
|
||||
this.mainWindow.destroy();
|
||||
this.splashWindow.destroy();
|
||||
|
||||
@@ -1,29 +1,20 @@
|
||||
import type { KubeObjectStore } from "../kube-object.store";
|
||||
import type { KubeObjectDetailsProps, KubeObjectListLayoutProps, KubeObjectMenuProps } from "../components/kube-object";
|
||||
import type React from "react";
|
||||
|
||||
import { observable } from "mobx";
|
||||
import { action, observable } from "mobx";
|
||||
import { autobind } from "../utils";
|
||||
import { KubeApi } from "./kube-api";
|
||||
|
||||
export interface ApiComponents {
|
||||
List?: React.ComponentType<KubeObjectListLayoutProps>;
|
||||
Menu?: React.ComponentType<KubeObjectMenuProps>;
|
||||
Details?: React.ComponentType<KubeObjectDetailsProps>;
|
||||
}
|
||||
|
||||
@autobind()
|
||||
export class ApiManager {
|
||||
private apis = observable.map<string, KubeApi>();
|
||||
private stores = observable.map<KubeApi, KubeObjectStore>();
|
||||
private views = observable.map<KubeApi, ApiComponents>();
|
||||
|
||||
getApi(pathOrCallback: string | ((api: KubeApi) => boolean)) {
|
||||
if (typeof pathOrCallback === "string") {
|
||||
return this.apis.get(pathOrCallback) || this.apis.get(KubeApi.parseApi(pathOrCallback).apiBase);
|
||||
}
|
||||
|
||||
return Array.from(this.apis.values()).find(pathOrCallback);
|
||||
return Array.from(this.apis.values()).find(pathOrCallback ?? ((api: KubeApi) => true));
|
||||
}
|
||||
|
||||
registerApi(apiBase: string, api: KubeApi) {
|
||||
@@ -46,8 +37,11 @@ export class ApiManager {
|
||||
}
|
||||
}
|
||||
|
||||
registerStore(api: KubeApi, store: KubeObjectStore) {
|
||||
this.stores.set(api, store);
|
||||
@action
|
||||
registerStore(store: KubeObjectStore, apis: KubeApi[] = [store.api]) {
|
||||
apis.forEach(api => {
|
||||
this.stores.set(api, store);
|
||||
})
|
||||
}
|
||||
|
||||
getStore(api: string | KubeApi): KubeObjectStore {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { KubeObject } from "../kube-object";
|
||||
import { VersionedKubeApi } from "../kube-api-versioned";
|
||||
import { crdResourcesURL } from "../../components/+custom-resources/crd.route";
|
||||
import { KubeApi } from "../kube-api";
|
||||
|
||||
type AdditionalPrinterColumnsCommon = {
|
||||
name: string;
|
||||
@@ -9,7 +9,7 @@ type AdditionalPrinterColumnsCommon = {
|
||||
description: string;
|
||||
}
|
||||
|
||||
type AdditionalPrinterColumnsV1 = AdditionalPrinterColumnsCommon & {
|
||||
export type AdditionalPrinterColumnsV1 = AdditionalPrinterColumnsCommon & {
|
||||
jsonPath: string;
|
||||
}
|
||||
|
||||
@@ -120,9 +120,9 @@ export class CustomResourceDefinition extends KubeObject {
|
||||
return JSON.stringify(this.spec.conversion);
|
||||
}
|
||||
|
||||
getPrinterColumns(ignorePriority = true) {
|
||||
getPrinterColumns(ignorePriority = true): AdditionalPrinterColumnsV1[] {
|
||||
const columns = this.spec.versions.find(a => this.getVersion() == a.name)?.additionalPrinterColumns
|
||||
?? this.spec.additionalPrinterColumns?.map(({JSONPath, ...rest}) => ({ ...rest, jsonPath: JSONPath })) // map to V1 shape
|
||||
?? this.spec.additionalPrinterColumns?.map(({ JSONPath, ...rest }) => ({ ...rest, jsonPath: JSONPath })) // map to V1 shape
|
||||
?? [];
|
||||
return columns
|
||||
.filter(column => column.name != "Age")
|
||||
@@ -146,7 +146,7 @@ export class CustomResourceDefinition extends KubeObject {
|
||||
}
|
||||
}
|
||||
|
||||
export const crdApi = new VersionedKubeApi<CustomResourceDefinition>({
|
||||
objectConstructor: CustomResourceDefinition
|
||||
export const crdApi = new KubeApi<CustomResourceDefinition>({
|
||||
objectConstructor: CustomResourceDefinition,
|
||||
checkPreferredVersion: true,
|
||||
});
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import moment from "moment";
|
||||
|
||||
import { IAffinity, WorkloadKubeObject } from "../workload-kube-object";
|
||||
import { autobind } from "../../utils";
|
||||
import { KubeApi } from "../kube-api";
|
||||
@@ -23,6 +25,25 @@ export class DeploymentApi extends KubeApi<Deployment> {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
restart(params: { namespace: string; name: string }) {
|
||||
return this.request.patch(this.getUrl(params), {
|
||||
data: {
|
||||
spec: {
|
||||
template: {
|
||||
metadata: {
|
||||
annotations: {"kubectl.kubernetes.io/restartedAt" : moment.utc().format()}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
'content-type': 'application/strategic-merge-patch+json'
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@autobind()
|
||||
@@ -38,6 +59,7 @@ export class Deployment extends WorkloadKubeObject {
|
||||
metadata: {
|
||||
creationTimestamp?: string;
|
||||
labels: { [app: string]: string };
|
||||
annotations?: { [app: string]: string };
|
||||
};
|
||||
spec: {
|
||||
containers: {
|
||||
|
||||
@@ -5,6 +5,7 @@ export * from "./cluster.api"
|
||||
export * from "./cluster-role.api"
|
||||
export * from "./cluster-role-binding.api"
|
||||
export * from "./configmap.api"
|
||||
export * from "./crd.api"
|
||||
export * from "./cron-job.api"
|
||||
export * from "./daemon-set.api"
|
||||
export * from "./deployment.api"
|
||||
|
||||
@@ -64,7 +64,7 @@ export class JsonApi<D = JsonApiData, P extends JsonApiParams = JsonApiParams> {
|
||||
}
|
||||
|
||||
patch<T = D>(path: string, params?: P, reqInit: RequestInit = {}) {
|
||||
return this.request<T>(path, params, { ...reqInit, method: "patch" });
|
||||
return this.request<T>(path, params, { ...reqInit, method: "PATCH" });
|
||||
}
|
||||
|
||||
del<T = D>(path: string, params?: P, reqInit: RequestInit = {}) {
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
import { stringify } from "querystring";
|
||||
import { KubeObject } from "./kube-object";
|
||||
import { createKubeApiURL } from "./kube-api-parse";
|
||||
import { KubeApi, IKubeApiQueryParams, IKubeApiOptions } from "./kube-api";
|
||||
import { apiManager } from "./api-manager";
|
||||
|
||||
export class VersionedKubeApi<T extends KubeObject = any> extends KubeApi<T> {
|
||||
private preferredVersion?: string;
|
||||
|
||||
constructor(opts: IKubeApiOptions<T>) {
|
||||
super(opts);
|
||||
|
||||
this.getPreferredVersion().then(() => {
|
||||
if (this.apiBase != opts.apiBase)
|
||||
apiManager.registerApi(this.apiBase, this);
|
||||
});
|
||||
}
|
||||
|
||||
// override this property to make read-write
|
||||
apiBase: string
|
||||
|
||||
async getPreferredVersion() {
|
||||
if (this.preferredVersion) return;
|
||||
|
||||
const apiGroupVersion = await this.request.get<{ preferredVersion?: { version: string; }; }>(`${this.apiPrefix}/${this.apiGroup}`);
|
||||
|
||||
if (!apiGroupVersion?.preferredVersion) return;
|
||||
|
||||
this.preferredVersion = apiGroupVersion.preferredVersion.version;
|
||||
|
||||
// update apiBase
|
||||
this.apiBase = this.getUrl();
|
||||
}
|
||||
|
||||
async list({ namespace = "" } = {}, query?: IKubeApiQueryParams): Promise<T[]> {
|
||||
await this.getPreferredVersion();
|
||||
return await super.list({namespace}, query);
|
||||
}
|
||||
async get({ name = "", namespace = "default" } = {}, query?: IKubeApiQueryParams): Promise<T> {
|
||||
await this.getPreferredVersion();
|
||||
return super.get({ name, namespace }, query);
|
||||
}
|
||||
|
||||
getUrl({ name = "", namespace = "" } = {}, query?: Partial<IKubeApiQueryParams>) {
|
||||
const { apiPrefix, apiGroup, apiVersion, apiResource, preferredVersion, isNamespaced } = this;
|
||||
|
||||
const resourcePath = createKubeApiURL({
|
||||
apiPrefix: apiPrefix,
|
||||
apiVersion: `${apiGroup}/${preferredVersion ?? apiVersion}`,
|
||||
resource: apiResource,
|
||||
namespace: isNamespaced ? namespace : undefined,
|
||||
name: name,
|
||||
});
|
||||
return resourcePath + (query ? `?` + stringify(query) : "");
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,6 @@ import { kubeWatchApi } from "./kube-watch-api";
|
||||
import { apiManager } from "./api-manager";
|
||||
import { createKubeApiURL, parseKubeApi } from "./kube-api-parse";
|
||||
import { apiKubePrefix, isDevelopment } from "../../common/vars";
|
||||
import * as URL from "url"
|
||||
|
||||
export interface IKubeApiOptions<T extends KubeObject> {
|
||||
apiBase?: string; // base api-path for listing all resources, e.g. "/api/v1/pods"
|
||||
@@ -17,6 +16,7 @@ export interface IKubeApiOptions<T extends KubeObject> {
|
||||
request?: KubeJsonApi;
|
||||
isNamespaced?: boolean;
|
||||
kind?: string;
|
||||
checkPreferredVersion?: boolean;
|
||||
}
|
||||
|
||||
export interface IKubeApiQueryParams {
|
||||
@@ -25,6 +25,14 @@ export interface IKubeApiQueryParams {
|
||||
timeoutSeconds?: number;
|
||||
limit?: number; // doesn't work with ?watch
|
||||
continue?: string; // might be used with ?limit from second request
|
||||
labelSelector?: string | string[]; // restrict list of objects by their labels, e.g. labelSelector: ["label=value"]
|
||||
fieldSelector?: string | string[]; // restrict list of objects by their fields, e.g. fieldSelector: "field=name"
|
||||
}
|
||||
|
||||
export interface IKubePreferredVersion {
|
||||
preferredVersion?: {
|
||||
version: string;
|
||||
}
|
||||
}
|
||||
|
||||
export interface IKubeApiCluster {
|
||||
@@ -59,7 +67,7 @@ export class KubeApi<T extends KubeObject = any> {
|
||||
readonly apiPrefix: string
|
||||
readonly apiGroup: string
|
||||
readonly apiVersion: string
|
||||
readonly apiVersionWithGroup: string
|
||||
readonly apiVersionPreferred?: string;
|
||||
readonly apiResource: string
|
||||
readonly isNamespaced: boolean
|
||||
|
||||
@@ -85,15 +93,35 @@ export class KubeApi<T extends KubeObject = any> {
|
||||
this.apiPrefix = apiPrefix;
|
||||
this.apiGroup = apiGroup;
|
||||
this.apiVersion = apiVersion;
|
||||
this.apiVersionWithGroup = apiVersionWithGroup;
|
||||
this.apiResource = resource;
|
||||
this.request = request;
|
||||
this.objectConstructor = objectConstructor;
|
||||
|
||||
this.checkPreferredVersion();
|
||||
this.parseResponse = this.parseResponse.bind(this);
|
||||
apiManager.registerApi(apiBase, this);
|
||||
}
|
||||
|
||||
get apiVersionWithGroup() {
|
||||
return [this.apiGroup, this.apiVersionPreferred ?? this.apiVersion]
|
||||
.filter(Boolean)
|
||||
.join("/")
|
||||
}
|
||||
|
||||
protected async checkPreferredVersion() {
|
||||
if (this.options.checkPreferredVersion && this.apiVersionPreferred === undefined) {
|
||||
const res = await this.request.get<IKubePreferredVersion>(`${this.apiPrefix}/${this.apiGroup}`);
|
||||
Object.defineProperty(this, "apiVersionPreferred", {
|
||||
value: res?.preferredVersion?.version ?? null,
|
||||
});
|
||||
|
||||
if (this.apiVersionPreferred) {
|
||||
Object.defineProperty(this, "apiBase", { value: this.getUrl() })
|
||||
apiManager.registerApi(this.apiBase, this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
setResourceVersion(namespace = "", newVersion: string) {
|
||||
this.resourceVersions.set(namespace, newVersion);
|
||||
}
|
||||
@@ -107,15 +135,24 @@ export class KubeApi<T extends KubeObject = any> {
|
||||
}
|
||||
|
||||
getUrl({ name = "", namespace = "" } = {}, query?: Partial<IKubeApiQueryParams>) {
|
||||
const { apiPrefix, apiVersionWithGroup, apiResource } = this;
|
||||
const resourcePath = createKubeApiURL({
|
||||
apiPrefix: apiPrefix,
|
||||
apiVersion: apiVersionWithGroup,
|
||||
resource: apiResource,
|
||||
apiPrefix: this.apiPrefix,
|
||||
apiVersion: this.apiVersionWithGroup,
|
||||
resource: this.apiResource,
|
||||
namespace: this.isNamespaced ? namespace : undefined,
|
||||
name: name,
|
||||
});
|
||||
return resourcePath + (query ? `?` + stringify(query) : "");
|
||||
return resourcePath + (query ? `?` + stringify(this.normalizeQuery(query)) : "");
|
||||
}
|
||||
|
||||
protected normalizeQuery(query: Partial<IKubeApiQueryParams> = {}) {
|
||||
if (query.labelSelector) {
|
||||
query.labelSelector = [query.labelSelector].flat().join(",")
|
||||
}
|
||||
if (query.fieldSelector) {
|
||||
query.fieldSelector = [query.fieldSelector].flat().join(",")
|
||||
}
|
||||
return query;
|
||||
}
|
||||
|
||||
protected parseResponse(data: KubeJsonApiData | KubeJsonApiData[] | KubeJsonApiDataList, namespace?: string): any {
|
||||
@@ -145,18 +182,21 @@ export class KubeApi<T extends KubeObject = any> {
|
||||
}
|
||||
|
||||
async list({ namespace = "" } = {}, query?: IKubeApiQueryParams): Promise<T[]> {
|
||||
await this.checkPreferredVersion();
|
||||
return this.request
|
||||
.get(this.getUrl({ namespace }), { query })
|
||||
.then(data => this.parseResponse(data, namespace));
|
||||
}
|
||||
|
||||
async get({ name = "", namespace = "default" } = {}, query?: IKubeApiQueryParams): Promise<T> {
|
||||
await this.checkPreferredVersion();
|
||||
return this.request
|
||||
.get(this.getUrl({ namespace, name }), { query })
|
||||
.then(this.parseResponse);
|
||||
}
|
||||
|
||||
async create({ name = "", namespace = "default" } = {}, data?: Partial<T>): Promise<T> {
|
||||
await this.checkPreferredVersion();
|
||||
const apiUrl = this.getUrl({ namespace });
|
||||
|
||||
return this.request
|
||||
@@ -174,6 +214,7 @@ export class KubeApi<T extends KubeObject = any> {
|
||||
}
|
||||
|
||||
async update({ name = "", namespace = "default" } = {}, data?: Partial<T>): Promise<T> {
|
||||
await this.checkPreferredVersion();
|
||||
const apiUrl = this.getUrl({ namespace, name });
|
||||
return this.request
|
||||
.put(apiUrl, { data })
|
||||
@@ -181,6 +222,7 @@ export class KubeApi<T extends KubeObject = any> {
|
||||
}
|
||||
|
||||
async delete({ name = "", namespace = "default" }) {
|
||||
await this.checkPreferredVersion();
|
||||
const apiUrl = this.getUrl({ namespace, name });
|
||||
return this.request.del(apiUrl)
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@ import React from "react";
|
||||
import * as Mobx from "mobx"
|
||||
import * as MobxReact from "mobx-react"
|
||||
import * as LensExtensions from "../extensions/extension-api"
|
||||
import { App } from "./components/app";
|
||||
import { LensApp } from "./lens-app";
|
||||
import { render, unmountComponentAtNode } from "react-dom";
|
||||
import { isMac } from "../common/vars";
|
||||
import { userStore } from "../common/user-store";
|
||||
@@ -11,8 +13,7 @@ import { workspaceStore } from "../common/workspace-store";
|
||||
import { clusterStore } from "../common/cluster-store";
|
||||
import { i18nStore } from "./i18n";
|
||||
import { themeStore } from "./theme.store";
|
||||
import { App } from "./components/app";
|
||||
import { LensApp } from "./lens-app";
|
||||
import { extensionsStore } from "../extensions/extensions-store";
|
||||
|
||||
type AppComponent = React.ComponentType & {
|
||||
init?(): Promise<void>;
|
||||
@@ -34,6 +35,7 @@ export async function bootstrap(App: AppComponent) {
|
||||
userStore.load(),
|
||||
workspaceStore.load(),
|
||||
clusterStore.load(),
|
||||
extensionsStore.load(),
|
||||
i18nStore.init(),
|
||||
themeStore.init(),
|
||||
]);
|
||||
|
||||
@@ -11,7 +11,7 @@ import { navigation } from "../../navigation";
|
||||
import { ItemListLayout } from "../item-object-list/item-list-layout";
|
||||
import { t, Trans } from "@lingui/macro";
|
||||
import { _i18n } from "../../i18n";
|
||||
import { SearchInput } from "../input";
|
||||
import { SearchInputUrl } from "../input";
|
||||
|
||||
enum sortBy {
|
||||
name = "name",
|
||||
@@ -72,7 +72,7 @@ export class HelmCharts extends Component<Props> {
|
||||
(items: HelmChart[]) => items.filter(item => !item.deprecated)
|
||||
]}
|
||||
customizeHeader={() => (
|
||||
<SearchInput placeholder={_i18n._(t`Search Helm Charts`)} />
|
||||
<SearchInputUrl placeholder={_i18n._(t`Search Helm Charts`)} />
|
||||
)}
|
||||
renderTableHeader={[
|
||||
{ className: "icon" },
|
||||
|
||||
@@ -1,41 +1,34 @@
|
||||
import React from "react";
|
||||
import { observer } from "mobx-react";
|
||||
import { Redirect, Route, Switch } from "react-router";
|
||||
import { Trans } from "@lingui/macro";
|
||||
import { TabLayout, TabRoute } from "../layout/tab-layout";
|
||||
import { TabLayout, TabLayoutRoute } from "../layout/tab-layout";
|
||||
import { HelmCharts, helmChartsRoute, helmChartsURL } from "../+apps-helm-charts";
|
||||
import { HelmReleases, releaseRoute, releaseURL } from "../+apps-releases";
|
||||
import { namespaceStore } from "../+namespaces/namespace.store";
|
||||
|
||||
@observer
|
||||
export class Apps extends React.Component {
|
||||
static get tabRoutes(): TabRoute[] {
|
||||
static get tabRoutes(): TabLayoutRoute[] {
|
||||
const query = namespaceStore.getContextParams();
|
||||
return [
|
||||
{
|
||||
title: <Trans>Charts</Trans>,
|
||||
component: HelmCharts,
|
||||
url: helmChartsURL(),
|
||||
path: helmChartsRoute.path,
|
||||
routePath: helmChartsRoute.path.toString(),
|
||||
},
|
||||
{
|
||||
title: <Trans>Releases</Trans>,
|
||||
component: HelmReleases,
|
||||
url: releaseURL({ query }),
|
||||
path: releaseRoute.path,
|
||||
routePath: releaseRoute.path.toString(),
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
render() {
|
||||
const tabRoutes = Apps.tabRoutes;
|
||||
return (
|
||||
<TabLayout className="Apps" tabs={tabRoutes}>
|
||||
<Switch>
|
||||
{tabRoutes.map((route, index) => <Route key={index} {...route}/>)}
|
||||
<Redirect to={tabRoutes[0].url}/>
|
||||
</Switch>
|
||||
</TabLayout>
|
||||
<TabLayout className="Apps" tabs={Apps.tabRoutes}/>
|
||||
)
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
import React from "react";
|
||||
import { observer } from "mobx-react";
|
||||
import { Cluster } from "../../../../main/cluster";
|
||||
import { SubTitle } from "../../layout/sub-title";
|
||||
import { EditableList } from "../../editable-list";
|
||||
import { observable } from "mobx";
|
||||
import { _i18n } from "../../../i18n";
|
||||
import { Trans } from "@lingui/macro";
|
||||
|
||||
interface Props {
|
||||
cluster: Cluster;
|
||||
}
|
||||
|
||||
@observer
|
||||
export class ClusterAccessibleNamespaces extends React.Component<Props> {
|
||||
@observable namespaces = new Set(this.props.cluster.accessibleNamespaces);
|
||||
|
||||
render() {
|
||||
return (
|
||||
<>
|
||||
<SubTitle title="Accessible Namespaces" />
|
||||
<p><Trans>This setting is useful for manually specifying which namespaces you have access to. This is useful when you don't have permissions to list namespaces.</Trans></p>
|
||||
<EditableList
|
||||
placeholder={_i18n._("Add new namespace...")}
|
||||
add={(newNamespace) => {
|
||||
this.namespaces.add(newNamespace);
|
||||
this.props.cluster.accessibleNamespaces = Array.from(this.namespaces);
|
||||
}}
|
||||
items={Array.from(this.namespaces)}
|
||||
remove={({ oldItem: oldNamesapce }) => {
|
||||
this.namespaces.delete(oldNamesapce);
|
||||
this.props.cluster.accessibleNamespaces = Array.from(this.namespaces);
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import { ClusterIconSetting } from "./components/cluster-icon-setting";
|
||||
import { ClusterProxySetting } from "./components/cluster-proxy-setting";
|
||||
import { ClusterPrometheusSetting } from "./components/cluster-prometheus-setting";
|
||||
import { ClusterHomeDirSetting } from "./components/cluster-home-dir-setting";
|
||||
import { ClusterAccessibleNamespaces } from "./components/cluster-accessible-namespaces";
|
||||
|
||||
interface Props {
|
||||
cluster: Cluster;
|
||||
@@ -21,6 +22,7 @@ export class General extends React.Component<Props> {
|
||||
<ClusterProxySetting cluster={this.props.cluster} />
|
||||
<ClusterPrometheusSetting cluster={this.props.cluster} />
|
||||
<ClusterHomeDirSetting cluster={this.props.cluster} />
|
||||
<ClusterAccessibleNamespaces cluster={this.props.cluster} />
|
||||
</div>;
|
||||
}
|
||||
}
|
||||
@@ -107,4 +107,4 @@ export class ClusterStore extends KubeObjectStore<Cluster> {
|
||||
}
|
||||
|
||||
export const clusterStore = new ClusterStore();
|
||||
apiManager.registerStore(clusterApi, clusterStore);
|
||||
apiManager.registerStore(clusterStore);
|
||||
@@ -121,8 +121,6 @@ export class HpaDetails extends React.Component<Props> {
|
||||
<div className="metrics">
|
||||
{this.renderMetrics()}
|
||||
</div>
|
||||
|
||||
<KubeEventDetails object={hpa}/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -135,3 +133,12 @@ kubeObjectDetailRegistry.add({
|
||||
Details: (props) => <HpaDetails {...props} />
|
||||
}
|
||||
})
|
||||
|
||||
kubeObjectDetailRegistry.add({
|
||||
kind: "HorizontalPodAutoscaler",
|
||||
apiVersions: ["autoscaling/v1"],
|
||||
priority: 5,
|
||||
components: {
|
||||
Details: (props) => <KubeEventDetails {...props} />
|
||||
}
|
||||
})
|
||||
@@ -6,6 +6,10 @@
|
||||
flex: 1.5;
|
||||
}
|
||||
|
||||
&.warning {
|
||||
@include table-cell-warning;
|
||||
}
|
||||
|
||||
&.metrics {
|
||||
flex: 1.5;
|
||||
}
|
||||
|
||||
@@ -9,4 +9,4 @@ export class HPAStore extends KubeObjectStore<HorizontalPodAutoscaler> {
|
||||
}
|
||||
|
||||
export const hpaStore = new HPAStore();
|
||||
apiManager.registerStore(hpaApi, hpaStore);
|
||||
apiManager.registerStore(hpaStore);
|
||||
@@ -4,14 +4,13 @@ import React from "react";
|
||||
import { observer } from "mobx-react";
|
||||
import { RouteComponentProps } from "react-router";
|
||||
import { Trans } from "@lingui/macro";
|
||||
import { KubeObjectMenu, KubeObjectMenuProps } from "../kube-object/kube-object-menu";
|
||||
import { KubeObjectListLayout } from "../kube-object";
|
||||
import { IHpaRouteParams } from "./hpa.route";
|
||||
import { HorizontalPodAutoscaler, hpaApi } from "../../api/endpoints/hpa.api";
|
||||
import { HorizontalPodAutoscaler } from "../../api/endpoints/hpa.api";
|
||||
import { hpaStore } from "./hpa.store";
|
||||
import { Badge } from "../badge";
|
||||
import { cssNames } from "../../utils";
|
||||
import { apiManager } from "../../api/api-manager";
|
||||
import { KubeObjectStatusIcon } from "../kube-object-status-icon";
|
||||
|
||||
enum sortBy {
|
||||
name = "name",
|
||||
@@ -52,6 +51,7 @@ export class HorizontalPodAutoscalers extends React.Component<Props> {
|
||||
renderHeaderTitle={<Trans>Horizontal Pod Autoscalers</Trans>}
|
||||
renderTableHeader={[
|
||||
{ title: <Trans>Name</Trans>, className: "name", sortBy: sortBy.name },
|
||||
{ className: "warning" },
|
||||
{ title: <Trans>Namespace</Trans>, className: "namespace", sortBy: sortBy.namespace },
|
||||
{ title: <Trans>Metrics</Trans>, className: "metrics" },
|
||||
{ title: <Trans>Min Pods</Trans>, className: "min-pods", sortBy: sortBy.minPods },
|
||||
@@ -62,6 +62,7 @@ export class HorizontalPodAutoscalers extends React.Component<Props> {
|
||||
]}
|
||||
renderTableContents={(hpa: HorizontalPodAutoscaler) => [
|
||||
hpa.getName(),
|
||||
<KubeObjectStatusIcon object={hpa} />,
|
||||
hpa.getNs(),
|
||||
this.getTargets(hpa),
|
||||
hpa.getMinPods(),
|
||||
|
||||
@@ -87,8 +87,6 @@ export class ConfigMapDetails extends React.Component<Props> {
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
<KubeEventDetails object={configMap}/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -101,3 +99,14 @@ kubeObjectDetailRegistry.add({
|
||||
Details: (props) => <ConfigMapDetails {...props} />
|
||||
}
|
||||
})
|
||||
|
||||
kubeObjectDetailRegistry.add({
|
||||
kind: "ConfigMap",
|
||||
apiVersions: ["v1"],
|
||||
priority: 5,
|
||||
components: {
|
||||
Details: (props) => <KubeEventDetails {...props} />
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -4,6 +4,10 @@
|
||||
flex: 2;
|
||||
}
|
||||
|
||||
&.warning {
|
||||
@include table-cell-warning;
|
||||
}
|
||||
|
||||
&.keys {
|
||||
flex: 2.5;
|
||||
}
|
||||
|
||||
@@ -9,4 +9,4 @@ export class ConfigMapsStore extends KubeObjectStore<ConfigMap> {
|
||||
}
|
||||
|
||||
export const configMapsStore = new ConfigMapsStore();
|
||||
apiManager.registerStore(configMapApi, configMapsStore);
|
||||
apiManager.registerStore(configMapsStore);
|
||||
@@ -10,6 +10,7 @@ import { KubeObjectMenu, KubeObjectMenuProps } from "../kube-object/kube-object-
|
||||
import { KubeObjectListLayout } from "../kube-object";
|
||||
import { IConfigMapsRouteParams } from "./config-maps.route";
|
||||
import { apiManager } from "../../api/api-manager";
|
||||
import { KubeObjectStatusIcon } from "../kube-object-status-icon";
|
||||
|
||||
enum sortBy {
|
||||
name = "name",
|
||||
@@ -40,12 +41,14 @@ export class ConfigMaps extends React.Component<Props> {
|
||||
renderHeaderTitle={<Trans>Config Maps</Trans>}
|
||||
renderTableHeader={[
|
||||
{ title: <Trans>Name</Trans>, className: "name", sortBy: sortBy.name },
|
||||
{ className: "warning" },
|
||||
{ title: <Trans>Namespace</Trans>, className: "namespace", sortBy: sortBy.namespace },
|
||||
{ title: <Trans>Keys</Trans>, className: "keys", sortBy: sortBy.keys },
|
||||
{ title: <Trans>Age</Trans>, className: "age", sortBy: sortBy.age },
|
||||
]}
|
||||
renderTableContents={(configMap: ConfigMap) => [
|
||||
configMap.getName(),
|
||||
<KubeObjectStatusIcon object={configMap}/>,
|
||||
configMap.getNs(),
|
||||
configMap.getKeys().join(", "),
|
||||
configMap.getAge(),
|
||||
|
||||
@@ -4,6 +4,10 @@
|
||||
flex: 2;
|
||||
}
|
||||
|
||||
&.warning {
|
||||
@include table-cell-warning;
|
||||
}
|
||||
|
||||
&.keys {
|
||||
flex: 2.5;
|
||||
}
|
||||
|
||||
+1
-1
@@ -9,4 +9,4 @@ export class PodDisruptionBudgetsStore extends KubeObjectStore<PodDisruptionBudg
|
||||
}
|
||||
|
||||
export const podDisruptionBudgetsStore = new PodDisruptionBudgetsStore();
|
||||
apiManager.registerStore(pdbApi, podDisruptionBudgetsStore);
|
||||
apiManager.registerStore(podDisruptionBudgetsStore);
|
||||
@@ -10,6 +10,7 @@ import { KubeObjectMenu, KubeObjectMenuProps } from "../kube-object/kube-object-
|
||||
import { KubeObjectDetailsProps, KubeObjectListLayout } from "../kube-object";
|
||||
import { IPodDisruptionBudgetsRouteParams } from "./pod-disruption-budgets.route";
|
||||
import { apiManager } from "../../api/api-manager";
|
||||
import { KubeObjectStatusIcon } from "../kube-object-status-icon";
|
||||
|
||||
enum sortBy {
|
||||
name = "name",
|
||||
@@ -46,6 +47,7 @@ export class PodDisruptionBudgets extends React.Component<Props> {
|
||||
renderHeaderTitle={<Trans>Pod Disruption Budgets</Trans>}
|
||||
renderTableHeader={[
|
||||
{ title: <Trans>Name</Trans>, className: "name", sortBy: sortBy.name },
|
||||
{ className: "warning" },
|
||||
{ title: <Trans>Namespace</Trans>, className: "namespace", sortBy: sortBy.namespace },
|
||||
{ title: <Trans>Min Available</Trans>, className: "min-available", sortBy: sortBy.minAvailable },
|
||||
{ title: <Trans>Max Unavailable</Trans>, className: "max-unavailable", sortBy: sortBy.maxUnavailable },
|
||||
@@ -56,6 +58,7 @@ export class PodDisruptionBudgets extends React.Component<Props> {
|
||||
renderTableContents={(pdb: PodDisruptionBudget) => {
|
||||
return [
|
||||
pdb.getName(),
|
||||
<KubeObjectStatusIcon object={pdb} />,
|
||||
pdb.getNs(),
|
||||
pdb.getMinAvailable(),
|
||||
pdb.getMaxUnavailable(),
|
||||
|
||||
@@ -1,2 +1,7 @@
|
||||
.ResourceQuotas {
|
||||
.TableCell {
|
||||
&.warning {
|
||||
@include table-cell-warning;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,4 +9,4 @@ export class ResourceQuotasStore extends KubeObjectStore<ResourceQuota> {
|
||||
}
|
||||
|
||||
export const resourceQuotaStore = new ResourceQuotasStore();
|
||||
apiManager.registerStore(resourceQuotaApi, resourceQuotaStore);
|
||||
apiManager.registerStore(resourceQuotaStore);
|
||||
@@ -11,6 +11,7 @@ import { AddQuotaDialog } from "./add-quota-dialog";
|
||||
import { resourceQuotaStore } from "./resource-quotas.store";
|
||||
import { IResourceQuotaRouteParams } from "./resource-quotas.route";
|
||||
import { apiManager } from "../../api/api-manager";
|
||||
import { KubeObjectStatusIcon } from "../kube-object-status-icon";
|
||||
|
||||
enum sortBy {
|
||||
name = "name",
|
||||
@@ -40,11 +41,13 @@ export class ResourceQuotas extends React.Component<Props> {
|
||||
renderHeaderTitle={<Trans>Resource Quotas</Trans>}
|
||||
renderTableHeader={[
|
||||
{ title: <Trans>Name</Trans>, className: "name", sortBy: sortBy.name },
|
||||
{ className: "warning" },
|
||||
{ title: <Trans>Namespace</Trans>, className: "namespace", sortBy: sortBy.namespace },
|
||||
{ title: <Trans>Age</Trans>, className: "age", sortBy: sortBy.age },
|
||||
]}
|
||||
renderTableContents={(resourceQuota: ResourceQuota) => [
|
||||
resourceQuota.getName(),
|
||||
<KubeObjectStatusIcon object={resourceQuota}/>,
|
||||
resourceQuota.getNs(),
|
||||
resourceQuota.getAge(),
|
||||
]}
|
||||
|
||||
@@ -4,6 +4,10 @@
|
||||
flex: 1.5;
|
||||
}
|
||||
|
||||
&.warning {
|
||||
@include table-cell-warning;
|
||||
}
|
||||
|
||||
&.labels {
|
||||
@include table-cell-labels-offsets;
|
||||
}
|
||||
|
||||
@@ -9,4 +9,4 @@ export class SecretsStore extends KubeObjectStore<Secret> {
|
||||
}
|
||||
|
||||
export const secretsStore = new SecretsStore();
|
||||
apiManager.registerStore(secretsApi, secretsStore);
|
||||
apiManager.registerStore(secretsStore);
|
||||
@@ -12,6 +12,7 @@ import { KubeObjectListLayout } from "../kube-object";
|
||||
import { Badge } from "../badge";
|
||||
import { secretsStore } from "./secrets.store";
|
||||
import { apiManager } from "../../api/api-manager";
|
||||
import { KubeObjectStatusIcon } from "../kube-object-status-icon";
|
||||
|
||||
enum sortBy {
|
||||
name = "name",
|
||||
@@ -47,6 +48,7 @@ export class Secrets extends React.Component<Props> {
|
||||
renderHeaderTitle={<Trans>Secrets</Trans>}
|
||||
renderTableHeader={[
|
||||
{ title: <Trans>Name</Trans>, className: "name", sortBy: sortBy.name },
|
||||
{ className: "warning" },
|
||||
{ title: <Trans>Namespace</Trans>, className: "namespace", sortBy: sortBy.namespace },
|
||||
{ title: <Trans>Labels</Trans>, className: "labels", sortBy: sortBy.labels },
|
||||
{ title: <Trans>Keys</Trans>, className: "keys", sortBy: sortBy.keys },
|
||||
@@ -55,6 +57,7 @@ export class Secrets extends React.Component<Props> {
|
||||
]}
|
||||
renderTableContents={(secret: Secret) => [
|
||||
secret.getName(),
|
||||
<KubeObjectStatusIcon object={secret} />,
|
||||
secret.getNs(),
|
||||
secret.getLabels().map(label => <Badge key={label} label={label}/>),
|
||||
secret.getKeys().join(", "),
|
||||
|
||||
@@ -5,7 +5,7 @@ import { configMapsURL } from "../+config-maps/config-maps.route";
|
||||
|
||||
export const configRoute: RouteProps = {
|
||||
get path() {
|
||||
return Config.tabRoutes.map(({ path }) => path).flat()
|
||||
return Config.tabRoutes.map(({ routePath }) => routePath).flat()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,33 +1,26 @@
|
||||
import React from "react";
|
||||
import { observer } from "mobx-react";
|
||||
import { Redirect, Route, Switch } from "react-router";
|
||||
import { Trans } from "@lingui/macro";
|
||||
import { TabLayout, TabRoute } from "../layout/tab-layout";
|
||||
import { TabLayout, TabLayoutRoute } from "../layout/tab-layout";
|
||||
import { ConfigMaps, configMapsRoute, configMapsURL } from "../+config-maps";
|
||||
import { Secrets, secretsRoute, secretsURL } from "../+config-secrets";
|
||||
import { namespaceStore } from "../+namespaces/namespace.store";
|
||||
import { resourceQuotaRoute, ResourceQuotas, resourceQuotaURL } from "../+config-resource-quotas";
|
||||
import { PodDisruptionBudgets, pdbRoute, pdbURL } from "../+config-pod-disruption-budgets";
|
||||
import { configURL } from "./config.route";
|
||||
import { pdbRoute, pdbURL, PodDisruptionBudgets } from "../+config-pod-disruption-budgets";
|
||||
import { HorizontalPodAutoscalers, hpaRoute, hpaURL } from "../+config-autoscalers";
|
||||
import { isAllowedResource } from "../../../common/rbac"
|
||||
import { buildURL } from "../../../common/utils/buildUrl";
|
||||
|
||||
export const certificatesURL = buildURL("/certificates");
|
||||
export const issuersURL = buildURL("/issuers");
|
||||
export const clusterIssuersURL = buildURL("/clusterissuers");
|
||||
|
||||
@observer
|
||||
export class Config extends React.Component {
|
||||
static get tabRoutes(): TabRoute[] {
|
||||
static get tabRoutes(): TabLayoutRoute[] {
|
||||
const query = namespaceStore.getContextParams()
|
||||
const routes: TabRoute[] = []
|
||||
const routes: TabLayoutRoute[] = []
|
||||
if (isAllowedResource("configmaps")) {
|
||||
routes.push({
|
||||
title: <Trans>ConfigMaps</Trans>,
|
||||
component: ConfigMaps,
|
||||
url: configMapsURL({ query }),
|
||||
path: configMapsRoute.path,
|
||||
routePath: configMapsRoute.path.toString(),
|
||||
})
|
||||
}
|
||||
if (isAllowedResource("secrets")) {
|
||||
@@ -35,7 +28,7 @@ export class Config extends React.Component {
|
||||
title: <Trans>Secrets</Trans>,
|
||||
component: Secrets,
|
||||
url: secretsURL({ query }),
|
||||
path: secretsRoute.path,
|
||||
routePath: secretsRoute.path.toString(),
|
||||
})
|
||||
}
|
||||
if (isAllowedResource("resourcequotas")) {
|
||||
@@ -43,7 +36,7 @@ export class Config extends React.Component {
|
||||
title: <Trans>Resource Quotas</Trans>,
|
||||
component: ResourceQuotas,
|
||||
url: resourceQuotaURL({ query }),
|
||||
path: resourceQuotaRoute.path,
|
||||
routePath: resourceQuotaRoute.path.toString(),
|
||||
})
|
||||
}
|
||||
if (isAllowedResource("horizontalpodautoscalers")) {
|
||||
@@ -51,7 +44,7 @@ export class Config extends React.Component {
|
||||
title: <Trans>HPA</Trans>,
|
||||
component: HorizontalPodAutoscalers,
|
||||
url: hpaURL({ query }),
|
||||
path: hpaRoute.path,
|
||||
routePath: hpaRoute.path.toString(),
|
||||
})
|
||||
}
|
||||
if (isAllowedResource("poddisruptionbudgets")) {
|
||||
@@ -59,21 +52,15 @@ export class Config extends React.Component {
|
||||
title: <Trans>Pod Disruption Budgets</Trans>,
|
||||
component: PodDisruptionBudgets,
|
||||
url: pdbURL({ query }),
|
||||
path: pdbRoute.path,
|
||||
routePath: pdbRoute.path.toString(),
|
||||
})
|
||||
}
|
||||
return routes;
|
||||
}
|
||||
|
||||
render() {
|
||||
const tabRoutes = Config.tabRoutes;
|
||||
return (
|
||||
<TabLayout className="Config" tabs={tabRoutes}>
|
||||
<Switch>
|
||||
{tabRoutes.map((route, index) => <Route key={index} {...route}/>)}
|
||||
<Redirect to={configURL({ query: namespaceStore.getContextParams() })}/>
|
||||
</Switch>
|
||||
</TabLayout>
|
||||
<TabLayout className="Config" tabs={Config.tabRoutes}/>
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -12,67 +12,83 @@ import { KubeObjectDetailsProps } from "../kube-object";
|
||||
import { crdStore } from "./crd.store";
|
||||
import { KubeObjectMeta } from "../kube-object/kube-object-meta";
|
||||
import { Input } from "../input";
|
||||
import { CustomResourceDefinition } from "../../api/endpoints/crd.api";
|
||||
import { AdditionalPrinterColumnsV1, CustomResourceDefinition } from "../../api/endpoints/crd.api";
|
||||
|
||||
interface Props extends KubeObjectDetailsProps<CustomResourceDefinition> {
|
||||
}
|
||||
|
||||
function CrdColumnValue({ value }: { value: any[] | {} | string }) {
|
||||
function convertSpecValue(value: any): any {
|
||||
if (Array.isArray(value)) {
|
||||
return <>{value.map((item, index) => <CrdColumnValue key={index} value={item} />)}</>
|
||||
return value.map(convertSpecValue)
|
||||
}
|
||||
if (typeof(value) === 'object') return (
|
||||
<Input
|
||||
readOnly
|
||||
multiLine
|
||||
theme="round-black"
|
||||
className="box grow"
|
||||
value={JSON.stringify(value, null, 2)}
|
||||
/>
|
||||
);
|
||||
return <span>{value}</span>;
|
||||
|
||||
if (typeof value === "object") {
|
||||
return (
|
||||
<Input
|
||||
readOnly
|
||||
multiLine
|
||||
theme="round-black"
|
||||
className="box grow"
|
||||
value={JSON.stringify(value, null, 2)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
@observer
|
||||
export class CrdResourceDetails extends React.Component<Props> {
|
||||
@computed get crd() {
|
||||
return crdStore.getByObject(this.props.object);
|
||||
}
|
||||
|
||||
renderAdditionalColumns(crd: CustomResourceDefinition, columns: AdditionalPrinterColumnsV1[]) {
|
||||
return columns.map(({ name, jsonPath: jp }) => (
|
||||
<DrawerItem key={name} name={name} renderBoolean>
|
||||
{convertSpecValue(jsonPath.value(crd, jp.slice(1)))}
|
||||
</DrawerItem>
|
||||
))
|
||||
}
|
||||
|
||||
renderStatus(crd: CustomResourceDefinition, columns: AdditionalPrinterColumnsV1[]) {
|
||||
const showStatus = !columns.find(column => column.name == "Status") && crd.status?.conditions;
|
||||
if (!showStatus) {
|
||||
return null
|
||||
}
|
||||
|
||||
const conditions = crd.status.conditions
|
||||
.filter(({ type, reason }) => type || reason)
|
||||
.map(({ type, reason, message, status }) => ({ kind: type || reason, message, status }))
|
||||
.map(({ kind, message, status }, index) => (
|
||||
<Badge
|
||||
key={kind + index} label={kind}
|
||||
className={cssNames({ disabled: status === "False" }, kind.toLowerCase())}
|
||||
tooltip={message}
|
||||
/>
|
||||
))
|
||||
|
||||
return (
|
||||
<DrawerItem name={<Trans>Status</Trans>} className="status" labelsOnly>
|
||||
{conditions}
|
||||
</DrawerItem>
|
||||
)
|
||||
}
|
||||
|
||||
render() {
|
||||
const { object } = this.props;
|
||||
const { crd } = this;
|
||||
if (!object || !crd) return null;
|
||||
const { props: { object }, crd } = this;
|
||||
if (!object || !crd) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const className = cssNames("CrdResourceDetails", crd.getResourceKind());
|
||||
const extraColumns = crd.getPrinterColumns();
|
||||
const showStatus = !extraColumns.find(column => column.name == "Status") && object.status?.conditions;
|
||||
|
||||
return (
|
||||
<div className={className}>
|
||||
<KubeObjectMeta object={object}/>
|
||||
{extraColumns.map(column => {
|
||||
const { name } = column;
|
||||
const value = jsonPath.query(object, (column.jsonPath).slice(1));
|
||||
return (
|
||||
<DrawerItem key={name} name={name}>
|
||||
<CrdColumnValue value={value} />
|
||||
</DrawerItem>
|
||||
)
|
||||
})}
|
||||
{showStatus && (
|
||||
<DrawerItem name={<Trans>Status</Trans>} className="status" labelsOnly>
|
||||
{object.status.conditions.map((condition, index) => {
|
||||
const { type, reason, message, status } = condition;
|
||||
const kind = type || reason;
|
||||
if (!kind) return null;
|
||||
return (
|
||||
<Badge
|
||||
key={kind + index} label={kind}
|
||||
className={cssNames({ disabled: status === "False" }, kind.toLowerCase())}
|
||||
tooltip={message}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</DrawerItem>
|
||||
)}
|
||||
<KubeObjectMeta object={object} />
|
||||
{this.renderAdditionalColumns(object, extraColumns)}
|
||||
{this.renderStatus(object, extraColumns)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ import { KubeObject } from "../../api/kube-object";
|
||||
import { ICRDRouteParams } from "./crd.route";
|
||||
import { autorun, computed } from "mobx";
|
||||
import { crdStore } from "./crd.store";
|
||||
import { SortingCallback } from "../table";
|
||||
import { TableSortCallback } from "../table";
|
||||
import { apiManager } from "../../api/api-manager";
|
||||
|
||||
interface Props extends RouteComponentProps<ICRDRouteParams> {
|
||||
@@ -50,17 +50,17 @@ export class CrdResources extends React.Component<Props> {
|
||||
if (!crd) return null;
|
||||
const isNamespaced = crd.isNamespaced();
|
||||
const extraColumns = crd.getPrinterColumns(false); // Cols with priority bigger than 0 are shown in details
|
||||
const sortingCallbacks: { [sortBy: string]: SortingCallback } = {
|
||||
const sortingCallbacks: { [sortBy: string]: TableSortCallback } = {
|
||||
[sortBy.name]: (item: KubeObject) => item.getName(),
|
||||
[sortBy.namespace]: (item: KubeObject) => item.getNs(),
|
||||
[sortBy.age]: (item: KubeObject) => item.metadata.creationTimestamp,
|
||||
}
|
||||
extraColumns.forEach(column => {
|
||||
sortingCallbacks[column.name] = (item: KubeObject) => jsonPath.query(item, column.jsonPath.slice(1))
|
||||
sortingCallbacks[column.name] = (item: KubeObject) => jsonPath.value(item, column.jsonPath.slice(1))
|
||||
})
|
||||
const ListView = KubeObjectListLayout;
|
||||
|
||||
return (
|
||||
<ListView
|
||||
<KubeObjectListLayout
|
||||
className="CrdResources"
|
||||
isClusterScoped={!isNamespaced}
|
||||
store={store}
|
||||
@@ -85,9 +85,10 @@ export class CrdResources extends React.Component<Props> {
|
||||
renderTableContents={(crdInstance: KubeObject) => [
|
||||
crdInstance.getName(),
|
||||
isNamespaced && crdInstance.getNs(),
|
||||
...extraColumns.map(column => {
|
||||
return jsonPath.query(crdInstance, (column.jsonPath).slice(1))
|
||||
}),
|
||||
...extraColumns.map(column => ({
|
||||
renderBoolean: true,
|
||||
children: jsonPath.value(crdInstance, column.jsonPath.slice(1)),
|
||||
})),
|
||||
crdInstance.getAge(),
|
||||
]}
|
||||
/>
|
||||
|
||||
@@ -14,7 +14,7 @@ function initStore(crd: CustomResourceDefinition) {
|
||||
const api = apiManager.getApi(apiBase) || new KubeApi({ apiBase, kind, isNamespaced });
|
||||
|
||||
if (!apiManager.getStore(api)) {
|
||||
apiManager.registerStore(api, new CRDResourceStore(api));
|
||||
apiManager.registerStore(new CRDResourceStore(api));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -64,4 +64,4 @@ export class CRDStore extends KubeObjectStore<CustomResourceDefinition> {
|
||||
|
||||
export const crdStore = new CRDStore();
|
||||
|
||||
apiManager.registerStore(crdApi, crdStore);
|
||||
apiManager.registerStore(crdStore);
|
||||
@@ -2,23 +2,20 @@ import React from "react";
|
||||
import { observer } from "mobx-react";
|
||||
import { Redirect, Route, Switch } from "react-router";
|
||||
import { Trans } from "@lingui/macro";
|
||||
import { TabLayout, TabRoute } from "../layout/tab-layout";
|
||||
import { TabLayout, TabLayoutRoute } from "../layout/tab-layout";
|
||||
import { crdResourcesRoute, crdRoute, crdURL, crdDefinitionsRoute } from "./crd.route";
|
||||
import { CrdList } from "./crd-list";
|
||||
import { CrdResources } from "./crd-resources";
|
||||
|
||||
// todo: next steps - customization via plugins
|
||||
// todo: list views (rows content), full details view and if possible chart/prometheus hooks
|
||||
|
||||
@observer
|
||||
export class CustomResources extends React.Component {
|
||||
static get tabRoutes(): TabRoute[] {
|
||||
static get tabRoutes(): TabLayoutRoute[] {
|
||||
return [
|
||||
{
|
||||
title: <Trans>Definitions</Trans>,
|
||||
component: CustomResources,
|
||||
url: crdURL(),
|
||||
path: crdRoute.path,
|
||||
routePath: crdRoute.path.toString(),
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -49,4 +49,4 @@ export class EventStore extends KubeObjectStore<KubeEvent> {
|
||||
}
|
||||
|
||||
export const eventStore = new EventStore();
|
||||
apiManager.registerStore(eventApi, eventStore);
|
||||
apiManager.registerStore(eventStore);
|
||||
@@ -6,15 +6,14 @@ import { Trans } from "@lingui/macro";
|
||||
import { KubeObject } from "../../api/kube-object";
|
||||
import { DrawerItem, DrawerTitle } from "../drawer";
|
||||
import { cssNames } from "../../utils";
|
||||
import { Icon } from "../icon";
|
||||
import { eventStore } from "./event.store";
|
||||
|
||||
interface Props {
|
||||
export interface KubeEventDetailsProps {
|
||||
object: KubeObject;
|
||||
}
|
||||
|
||||
@observer
|
||||
export class KubeEventDetails extends React.Component<Props> {
|
||||
export class KubeEventDetails extends React.Component<KubeEventDetailsProps> {
|
||||
async componentDidMount() {
|
||||
eventStore.loadAll();
|
||||
}
|
||||
@@ -30,7 +29,7 @@ export class KubeEventDetails extends React.Component<Props> {
|
||||
)
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<div>
|
||||
<DrawerTitle className="flex gaps align-center">
|
||||
<span><Trans>Events</Trans></span>
|
||||
</DrawerTitle>
|
||||
@@ -58,7 +57,7 @@ export class KubeEventDetails extends React.Component<Props> {
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { RouteProps } from "react-router";
|
||||
import { buildURL } from "../../../common/utils/buildUrl";
|
||||
|
||||
export const extensionsRoute: RouteProps = {
|
||||
path: "/extensions"
|
||||
}
|
||||
|
||||
export const extensionsURL = buildURL(extensionsRoute.path)
|
||||
@@ -0,0 +1,41 @@
|
||||
.Extensions {
|
||||
--width: 100%;
|
||||
--max-width: auto;
|
||||
|
||||
.extension-list {
|
||||
.extension {
|
||||
--flex-gap: $padding / 3;
|
||||
padding: $padding $padding * 2;
|
||||
background: $colorVague;
|
||||
border-radius: $radius;
|
||||
|
||||
&:not(:first-of-type) {
|
||||
margin-top: $padding * 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.extensions-path {
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.WizardLayout {
|
||||
padding: 0;
|
||||
|
||||
.info-col {
|
||||
flex: 0.6;
|
||||
align-self: flex-start;
|
||||
}
|
||||
}
|
||||
|
||||
.SearchInput {
|
||||
margin-top: $margin / 2;
|
||||
margin-bottom: $margin * 2;
|
||||
max-width: none;
|
||||
|
||||
> label {
|
||||
padding: $padding $padding * 2;
|
||||
border-radius: $radius;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import "./extensions.scss";
|
||||
import { shell } from "electron";
|
||||
import React from "react";
|
||||
import { computed, observable } from "mobx";
|
||||
import { observer } from "mobx-react";
|
||||
import { t, Trans } from "@lingui/macro";
|
||||
import { _i18n } from "../../i18n";
|
||||
import { Button } from "../button";
|
||||
import { WizardLayout } from "../layout/wizard-layout";
|
||||
import { Input } from "../input";
|
||||
import { Icon } from "../icon";
|
||||
import { PageLayout } from "../layout/page-layout";
|
||||
import { extensionLoader } from "../../../extensions/extension-loader";
|
||||
import { extensionManager } from "../../../extensions/extension-manager";
|
||||
|
||||
@observer
|
||||
export class Extensions extends React.Component {
|
||||
@observable search = ""
|
||||
|
||||
@computed get extensions() {
|
||||
const searchText = this.search.toLowerCase();
|
||||
return Array.from(extensionLoader.userExtensions.values()).filter(ext => {
|
||||
const { name, description } = ext.manifest;
|
||||
return [
|
||||
name.toLowerCase().includes(searchText),
|
||||
description.toLowerCase().includes(searchText),
|
||||
].some(v => v)
|
||||
})
|
||||
}
|
||||
|
||||
get extensionsPath() {
|
||||
return extensionManager.localFolderPath;
|
||||
}
|
||||
|
||||
renderInfo() {
|
||||
return (
|
||||
<div className="flex column gaps">
|
||||
<h2>Lens Extension API</h2>
|
||||
<div>
|
||||
The Extensions API in Lens allows users to customize and enhance the Lens experience by creating their own menus or page content that is extended from the existing pages. Many of the core
|
||||
features of Lens are built as extensions and use the same Extension API.
|
||||
</div>
|
||||
<div>
|
||||
Extensions loaded from:
|
||||
<div className="extensions-path flex inline">
|
||||
<code>{this.extensionsPath}</code>
|
||||
<Icon
|
||||
material="folder"
|
||||
tooltip="Open folder"
|
||||
onClick={() => shell.openPath(this.extensionsPath)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
Check out documentation to <a href="https://docs.k8slens.dev/" target="_blank">learn more</a>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
renderExtensions() {
|
||||
const { extensions, extensionsPath, search } = this;
|
||||
if (!extensions.length) {
|
||||
return (
|
||||
<div className="flex align-center box grow justify-center gaps">
|
||||
{search && <Trans>No search results found</Trans>}
|
||||
{!search && <p><Trans>There are no extensions in</Trans> <code>{extensionsPath}</code></p>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
return extensions.map(ext => {
|
||||
const { manifestPath: extId, isEnabled, manifest } = ext;
|
||||
const { name, description } = manifest;
|
||||
return (
|
||||
<div key={extId} className="extension flex gaps align-center">
|
||||
<div className="box grow flex column gaps">
|
||||
<div className="package">
|
||||
Name: <code className="name">{name}</code>
|
||||
</div>
|
||||
<div>
|
||||
Description: <span className="text-secondary">{description}</span>
|
||||
</div>
|
||||
</div>
|
||||
{!isEnabled && (
|
||||
<Button plain active onClick={() => ext.isEnabled = true}>Enable</Button>
|
||||
)}
|
||||
{isEnabled && (
|
||||
<Button accent onClick={() => ext.isEnabled = false}>Disable</Button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<PageLayout showOnTop className="Extensions" header={<h2>Extensions</h2>}>
|
||||
<WizardLayout infoPanel={this.renderInfo()}>
|
||||
<Input
|
||||
autoFocus
|
||||
theme="round-black"
|
||||
className="SearchInput"
|
||||
placeholder={_i18n._(t`Search extensions`)}
|
||||
value={this.search}
|
||||
onChange={(value) => this.search = value}
|
||||
/>
|
||||
<div className="extension-list">
|
||||
{this.renderExtensions()}
|
||||
</div>
|
||||
</WizardLayout>
|
||||
</PageLayout>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from "./extensions.route"
|
||||
export * from "./extensions"
|
||||
@@ -1,4 +1,5 @@
|
||||
.LandingPage {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
text-align: center;
|
||||
z-index: 0;
|
||||
|
||||
@@ -95,4 +95,4 @@ export class NamespaceStore extends KubeObjectStore<Namespace> {
|
||||
}
|
||||
|
||||
export const namespaceStore = new NamespaceStore();
|
||||
apiManager.registerStore(namespacesApi, namespaceStore);
|
||||
apiManager.registerStore(namespaceStore);
|
||||
Loaded 100 of 372 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user