mirror of
https://github.com/lensapp/lens.git
synced 2025-05-20 05:10:56 +00:00
Merge branch 'master' into pages-url-params
# Conflicts: # src/renderer/components/app.tsx
This commit is contained in:
commit
a9d0af1656
39 files changed
+1452
-259
No files matched your search
@@ -26,6 +26,11 @@ export interface WorkspaceState {
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Workspace
|
||||
*
|
||||
* @beta
|
||||
*/
|
||||
export class Workspace implements WorkspaceModel, WorkspaceState {
|
||||
/**
|
||||
* Unique id for workspace
|
||||
@@ -78,23 +83,39 @@ export class Workspace implements WorkspaceModel, WorkspaceState {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Is workspace managed by an extension
|
||||
*/
|
||||
get isManaged(): boolean {
|
||||
return !!this.ownerRef;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get workspace state
|
||||
*
|
||||
*/
|
||||
getState(): WorkspaceState {
|
||||
return toJS({
|
||||
enabled: this.enabled
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Push state
|
||||
*
|
||||
* @interal
|
||||
* @param state workspace state
|
||||
*/
|
||||
pushState(state = this.getState()) {
|
||||
logger.silly("[WORKSPACE] pushing state", {...state, id: this.id});
|
||||
broadcastMessage("workspace:state", this.id, toJS(state));
|
||||
}
|
||||
|
||||
@action
|
||||
setState(state: WorkspaceState) {
|
||||
/**
|
||||
*
|
||||
* @param state workspace state
|
||||
*/
|
||||
@action setState(state: WorkspaceState) {
|
||||
Object.assign(this, state);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
export { ExtensionStore } from "../extension-store";
|
||||
|
||||
export { clusterStore, Cluster } from "../stores/cluster-store";
|
||||
export { clusterStore, Cluster, ClusterStore } from "../stores/cluster-store";
|
||||
export type { ClusterModel, ClusterId } from "../stores/cluster-store";
|
||||
|
||||
export { workspaceStore, Workspace } from "../stores/workspace-store";
|
||||
export { workspaceStore, Workspace, WorkspaceStore } from "../stores/workspace-store";
|
||||
export type { WorkspaceId, WorkspaceModel } from "../stores/workspace-store";
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import chokidar from "chokidar";
|
||||
import { ipcRenderer } from "electron";
|
||||
import { EventEmitter } from "events";
|
||||
import fs from "fs-extra";
|
||||
import { observable, reaction, toJS, when } from "mobx";
|
||||
import os from "os";
|
||||
import path from "path";
|
||||
import { broadcastMessage, handleRequest, requestMain, subscribeToBroadcast } from "../common/ipc";
|
||||
import { getBundledExtensions } from "../common/utils/app-version";
|
||||
import logger from "../main/logger";
|
||||
import { extensionInstaller, PackageJson } from "./extension-installer";
|
||||
@@ -28,6 +31,10 @@ const logModule = "[EXTENSION-DISCOVERY]";
|
||||
|
||||
export const manifestFilename = "package.json";
|
||||
|
||||
interface ExtensionDiscoveryChannelMessage {
|
||||
isLoaded: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the lstat is for a directory-like file (e.g. isDirectory or symbolic link)
|
||||
* @param lstat the stats to compare
|
||||
@@ -49,22 +56,16 @@ export class ExtensionDiscovery {
|
||||
|
||||
private loadStarted = false;
|
||||
|
||||
// This promise is resolved when .load() is finished.
|
||||
// This allows operations to be added after .load() success.
|
||||
private loaded: Promise<void>;
|
||||
// True if extensions have been loaded from the disk after app startup
|
||||
@observable isLoaded = false;
|
||||
whenLoaded = when(() => this.isLoaded);
|
||||
|
||||
// These are called to either resolve or reject this.loaded promise
|
||||
private resolveLoaded: () => void;
|
||||
private rejectLoaded: (error: any) => void;
|
||||
// IPC channel to broadcast changes to extension-discovery from main
|
||||
protected static readonly extensionDiscoveryChannel = "extension-discovery:main";
|
||||
|
||||
public events: EventEmitter;
|
||||
|
||||
constructor() {
|
||||
this.loaded = new Promise((resolve, reject) => {
|
||||
this.resolveLoaded = resolve;
|
||||
this.rejectLoaded = reject;
|
||||
});
|
||||
|
||||
this.events = new EventEmitter();
|
||||
}
|
||||
|
||||
@@ -98,8 +99,32 @@ export class ExtensionDiscovery {
|
||||
/**
|
||||
* Initializes the class and setups the file watcher for added/removed local extensions.
|
||||
*/
|
||||
init() {
|
||||
async init() {
|
||||
if (ipcRenderer) {
|
||||
await this.initRenderer();
|
||||
} else {
|
||||
await this.initMain();
|
||||
}
|
||||
}
|
||||
|
||||
async initRenderer() {
|
||||
const onMessage = ({ isLoaded }: ExtensionDiscoveryChannelMessage) => {
|
||||
this.isLoaded = isLoaded;
|
||||
};
|
||||
|
||||
requestMain(ExtensionDiscovery.extensionDiscoveryChannel).then(onMessage);
|
||||
subscribeToBroadcast(ExtensionDiscovery.extensionDiscoveryChannel, (_event, message: ExtensionDiscoveryChannelMessage) => {
|
||||
onMessage(message);
|
||||
});
|
||||
}
|
||||
|
||||
async initMain() {
|
||||
this.watchExtensions();
|
||||
handleRequest(ExtensionDiscovery.extensionDiscoveryChannel, () => this.toJSON());
|
||||
|
||||
reaction(() => this.toJSON(), () => {
|
||||
this.broadcast();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -110,7 +135,7 @@ export class ExtensionDiscovery {
|
||||
logger.info(`${logModule} watching extension add/remove in ${this.localFolderPath}`);
|
||||
|
||||
// Wait until .load() has been called and has been resolved
|
||||
await this.loaded;
|
||||
await this.whenLoaded;
|
||||
|
||||
// chokidar works better than fs.watch
|
||||
chokidar.watch(this.localFolderPath, {
|
||||
@@ -208,36 +233,31 @@ export class ExtensionDiscovery {
|
||||
|
||||
this.loadStarted = true;
|
||||
|
||||
try {
|
||||
logger.info(`${logModule} loading extensions from ${extensionInstaller.extensionPackagesRoot}`);
|
||||
logger.info(`${logModule} loading extensions from ${extensionInstaller.extensionPackagesRoot}`);
|
||||
|
||||
if (fs.existsSync(path.join(extensionInstaller.extensionPackagesRoot, "package-lock.json"))) {
|
||||
await fs.remove(path.join(extensionInstaller.extensionPackagesRoot, "package-lock.json"));
|
||||
}
|
||||
|
||||
try {
|
||||
await fs.access(this.inTreeFolderPath, fs.constants.W_OK);
|
||||
this.bundledFolderPath = this.inTreeFolderPath;
|
||||
} catch {
|
||||
// we need to copy in-tree extensions so that we can symlink them properly on "npm install"
|
||||
await fs.remove(this.inTreeTargetPath);
|
||||
await fs.ensureDir(this.inTreeTargetPath);
|
||||
await fs.copy(this.inTreeFolderPath, this.inTreeTargetPath);
|
||||
this.bundledFolderPath = this.inTreeTargetPath;
|
||||
}
|
||||
|
||||
await fs.ensureDir(this.nodeModulesPath);
|
||||
await fs.ensureDir(this.localFolderPath);
|
||||
|
||||
const extensions = await this.loadExtensions();
|
||||
|
||||
// resolve the loaded promise
|
||||
this.resolveLoaded();
|
||||
|
||||
return extensions;
|
||||
} catch (error) {
|
||||
this.rejectLoaded(error);
|
||||
if (fs.existsSync(path.join(extensionInstaller.extensionPackagesRoot, "package-lock.json"))) {
|
||||
await fs.remove(path.join(extensionInstaller.extensionPackagesRoot, "package-lock.json"));
|
||||
}
|
||||
|
||||
try {
|
||||
await fs.access(this.inTreeFolderPath, fs.constants.W_OK);
|
||||
this.bundledFolderPath = this.inTreeFolderPath;
|
||||
} catch {
|
||||
// we need to copy in-tree extensions so that we can symlink them properly on "npm install"
|
||||
await fs.remove(this.inTreeTargetPath);
|
||||
await fs.ensureDir(this.inTreeTargetPath);
|
||||
await fs.copy(this.inTreeFolderPath, this.inTreeTargetPath);
|
||||
this.bundledFolderPath = this.inTreeTargetPath;
|
||||
}
|
||||
|
||||
await fs.ensureDir(this.nodeModulesPath);
|
||||
await fs.ensureDir(this.localFolderPath);
|
||||
|
||||
const extensions = await this.loadExtensions();
|
||||
|
||||
this.isLoaded = true;
|
||||
|
||||
return extensions;
|
||||
}
|
||||
|
||||
protected async getByManifest(manifestPath: string, { isBundled = false }: {
|
||||
@@ -356,6 +376,18 @@ export class ExtensionDiscovery {
|
||||
|
||||
return this.getByManifest(manifestPath, { isBundled });
|
||||
}
|
||||
|
||||
toJSON(): ExtensionDiscoveryChannelMessage {
|
||||
return toJS({
|
||||
isLoaded: this.isLoaded
|
||||
}, {
|
||||
recurseEverything: true
|
||||
});
|
||||
}
|
||||
|
||||
broadcast() {
|
||||
broadcastMessage(ExtensionDiscovery.extensionDiscoveryChannel, this.toJSON());
|
||||
}
|
||||
}
|
||||
|
||||
export const extensionDiscovery = new ExtensionDiscovery();
|
||||
@@ -17,6 +17,7 @@
|
||||
"email": "info@k8slens.dev"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^14.14.6"
|
||||
"@types/node": "^14.14.6",
|
||||
"conf": "^7.0.1"
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,8 @@ export type { ClusterModel, ClusterId } from "../../common/cluster-store";
|
||||
|
||||
/**
|
||||
* Store for all added clusters
|
||||
*
|
||||
* @beta
|
||||
*/
|
||||
export class ClusterStore extends Singleton {
|
||||
|
||||
|
||||
@@ -7,6 +7,8 @@ export type { WorkspaceId, WorkspaceModel } from "../../common/workspace-store";
|
||||
|
||||
/**
|
||||
* Stores all workspaces
|
||||
*
|
||||
* @beta
|
||||
*/
|
||||
export class WorkspaceStore extends Singleton {
|
||||
/**
|
||||
|
||||
@@ -60,6 +60,10 @@ export class DistributionDetector extends BaseClusterDetector {
|
||||
return { value: "custom", accuracy: 10};
|
||||
}
|
||||
|
||||
if (await this.isOpenshift()) {
|
||||
return { value: "openshift", accuracy: 90};
|
||||
}
|
||||
|
||||
return { value: "unknown", accuracy: 10};
|
||||
}
|
||||
|
||||
@@ -122,4 +126,14 @@ export class DistributionDetector extends BaseClusterDetector {
|
||||
protected isK3s() {
|
||||
return this.version.includes("+k3s");
|
||||
}
|
||||
|
||||
protected async isOpenshift() {
|
||||
try {
|
||||
const response = await this.k8sRequest("");
|
||||
|
||||
return response.paths?.includes("/apis/project.openshift.io");
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
+224
-22
@@ -49,10 +49,31 @@ export interface ClusterState {
|
||||
allowedResources: string[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Cluster
|
||||
*
|
||||
* @beta
|
||||
*/
|
||||
export class Cluster implements ClusterModel, ClusterState {
|
||||
/** Unique id for a cluster */
|
||||
public id: ClusterId;
|
||||
/**
|
||||
* Kubectl
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
public kubeCtl: Kubectl;
|
||||
/**
|
||||
* Context handler
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
public contextHandler: ContextHandler;
|
||||
/**
|
||||
* Owner reference
|
||||
*
|
||||
* If extension sets this it needs to also mark cluster as enabled on activate (or when added to a store)
|
||||
*/
|
||||
public ownerRef: string;
|
||||
protected kubeconfigManager: KubeconfigManager;
|
||||
protected eventDisposers: Function[] = [];
|
||||
@@ -61,34 +82,147 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
whenInitialized = when(() => this.initialized);
|
||||
whenReady = when(() => this.ready);
|
||||
|
||||
/**
|
||||
* Is cluster object initialized
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
@observable initialized = false;
|
||||
/**
|
||||
* Kubeconfig context name
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
@observable contextName: string;
|
||||
/**
|
||||
* Workspace id
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
@observable workspace: WorkspaceId;
|
||||
/**
|
||||
* Path to kubeconfig
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
@observable kubeConfigPath: string;
|
||||
/**
|
||||
* Kubernetes API server URL
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
@observable apiUrl: string; // cluster server url
|
||||
/**
|
||||
* Internal authentication proxy URL
|
||||
*
|
||||
* @observable
|
||||
* @internal
|
||||
*/
|
||||
@observable kubeProxyUrl: string; // lens-proxy to kube-api url
|
||||
/**
|
||||
* Is cluster instance enabled (disabled clusters are currently hidden)
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
@observable enabled = false; // only enabled clusters are visible to users
|
||||
/**
|
||||
* Is cluster online
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
@observable online = false; // describes if we can detect that cluster is online
|
||||
/**
|
||||
* Can user access cluster resources
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
@observable accessible = false; // if user is able to access cluster resources
|
||||
/**
|
||||
* Is cluster instance in usable state
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
@observable ready = false; // cluster is in usable state
|
||||
/**
|
||||
* Is cluster currently reconnecting
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
@observable reconnecting = false;
|
||||
@observable disconnected = true; // false if user has selected to connect
|
||||
/**
|
||||
* Is cluster disconnected. False if user has selected to connect.
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
@observable disconnected = true;
|
||||
/**
|
||||
* Connection failure reason
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
@observable failureReason: string;
|
||||
/**
|
||||
* Does user have admin like access
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
@observable isAdmin = false;
|
||||
/**
|
||||
* Preferences
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
@observable preferences: ClusterPreferences = {};
|
||||
/**
|
||||
* Metadata
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
@observable metadata: ClusterMetadata = {};
|
||||
/**
|
||||
* List of allowed namespaces
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
@observable allowedNamespaces: string[] = [];
|
||||
/**
|
||||
* List of allowed resources
|
||||
*
|
||||
* @observable
|
||||
* @internal
|
||||
*/
|
||||
@observable allowedResources: string[] = [];
|
||||
/**
|
||||
* List of accessible namespaces
|
||||
*
|
||||
* @observable
|
||||
*/
|
||||
@observable accessibleNamespaces: string[] = [];
|
||||
|
||||
/**
|
||||
* Is cluster available
|
||||
*
|
||||
* @computed
|
||||
*/
|
||||
@computed get available() {
|
||||
return this.accessible && !this.disconnected;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cluster name
|
||||
*
|
||||
* @computed
|
||||
*/
|
||||
@computed get name() {
|
||||
return this.preferences.clusterName || this.contextName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prometheus preferences
|
||||
*
|
||||
* @computed
|
||||
* @internal
|
||||
*/
|
||||
@computed get prometheusPreferences(): ClusterPrometheusPreferences {
|
||||
const { prometheus, prometheusProvider } = this.preferences;
|
||||
|
||||
@@ -97,6 +231,9 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Kubernetes version
|
||||
*/
|
||||
get version(): string {
|
||||
return String(this.metadata?.version) || "";
|
||||
}
|
||||
@@ -110,17 +247,29 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Is cluster managed by an extension
|
||||
*/
|
||||
get isManaged(): boolean {
|
||||
return !!this.ownerRef;
|
||||
}
|
||||
|
||||
@action
|
||||
updateModel(model: ClusterModel) {
|
||||
/**
|
||||
* Update cluster data model
|
||||
*
|
||||
* @param model
|
||||
*/
|
||||
@action updateModel(model: ClusterModel) {
|
||||
Object.assign(this, model);
|
||||
}
|
||||
|
||||
@action
|
||||
async init(port: number) {
|
||||
/**
|
||||
* Initialize a cluster (can be done only in main process)
|
||||
*
|
||||
* @param port port where internal auth proxy is listening
|
||||
* @internal
|
||||
*/
|
||||
@action async init(port: number) {
|
||||
try {
|
||||
this.contextHandler = new ContextHandler(this);
|
||||
this.kubeconfigManager = await KubeconfigManager.create(this, this.contextHandler, port);
|
||||
@@ -139,6 +288,9 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
protected bindEvents() {
|
||||
logger.info(`[CLUSTER]: bind events`, this.getMeta());
|
||||
const refreshTimer = setInterval(() => !this.disconnected && this.refresh(), 30000); // every 30s
|
||||
@@ -156,14 +308,20 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* internal
|
||||
*/
|
||||
protected unbindEvents() {
|
||||
logger.info(`[CLUSTER]: unbind events`, this.getMeta());
|
||||
this.eventDisposers.forEach(dispose => dispose());
|
||||
this.eventDisposers.length = 0;
|
||||
}
|
||||
|
||||
@action
|
||||
async activate(force = false) {
|
||||
/**
|
||||
* @param force force activation
|
||||
* @internal
|
||||
*/
|
||||
@action async activate(force = false) {
|
||||
if (this.activated && !force) {
|
||||
return this.pushState();
|
||||
}
|
||||
@@ -190,22 +348,29 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
return this.pushState();
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
protected async ensureKubectl() {
|
||||
this.kubeCtl = new Kubectl(this.version);
|
||||
|
||||
return this.kubeCtl.ensureKubectl(); // download kubectl in background, so it's not blocking dashboard
|
||||
}
|
||||
|
||||
@action
|
||||
async reconnect() {
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
@action async reconnect() {
|
||||
logger.info(`[CLUSTER]: reconnect`, this.getMeta());
|
||||
this.contextHandler?.stopServer();
|
||||
await this.contextHandler?.ensureServer();
|
||||
this.disconnected = false;
|
||||
}
|
||||
|
||||
@action
|
||||
disconnect() {
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
@action disconnect() {
|
||||
logger.info(`[CLUSTER]: disconnect`, this.getMeta());
|
||||
this.unbindEvents();
|
||||
this.contextHandler?.stopServer();
|
||||
@@ -217,8 +382,11 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
this.pushState();
|
||||
}
|
||||
|
||||
@action
|
||||
async refresh(opts: ClusterRefreshOptions = {}) {
|
||||
/**
|
||||
* @internal
|
||||
* @param opts refresh options
|
||||
*/
|
||||
@action async refresh(opts: ClusterRefreshOptions = {}) {
|
||||
logger.info(`[CLUSTER]: refresh`, this.getMeta());
|
||||
await this.whenInitialized;
|
||||
await this.refreshConnectionStatus();
|
||||
@@ -235,8 +403,10 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
this.pushState();
|
||||
}
|
||||
|
||||
@action
|
||||
async refreshMetadata() {
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
@action async refreshMetadata() {
|
||||
logger.info(`[CLUSTER]: refreshMetadata`, this.getMeta());
|
||||
const metadata = await detectorRegistry.detectForCluster(this);
|
||||
const existingMetadata = this.metadata;
|
||||
@@ -244,16 +414,20 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
this.metadata = Object.assign(existingMetadata, metadata);
|
||||
}
|
||||
|
||||
@action
|
||||
async refreshConnectionStatus() {
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
@action async refreshConnectionStatus() {
|
||||
const connectionStatus = await this.getConnectionStatus();
|
||||
|
||||
this.online = connectionStatus > ClusterStatus.Offline;
|
||||
this.accessible = connectionStatus == ClusterStatus.AccessGranted;
|
||||
}
|
||||
|
||||
@action
|
||||
async refreshAllowedResources() {
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
@action async refreshAllowedResources() {
|
||||
this.allowedNamespaces = await this.getAllowedNamespaces();
|
||||
this.allowedResources = await this.getAllowedResources();
|
||||
}
|
||||
@@ -262,10 +436,16 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
return loadConfig(this.kubeConfigPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
getProxyKubeconfig(): KubeConfig {
|
||||
return loadConfig(this.getProxyKubeconfigPath());
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
getProxyKubeconfigPath(): string {
|
||||
return this.kubeconfigManager.getPath();
|
||||
}
|
||||
@@ -279,6 +459,12 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
return request(this.kubeProxyUrl + path, options);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param prometheusPath path to prometheus service
|
||||
* @param queryParams query parameters
|
||||
* @internal
|
||||
*/
|
||||
getMetrics(prometheusPath: string, queryParams: IMetricsReqParams & { query: string }) {
|
||||
const prometheusPrefix = this.preferences.prometheus?.prefix || "";
|
||||
const metricsPath = `/api/v1/namespaces/${prometheusPath}/proxy${prometheusPrefix}/api/v1/query_range`;
|
||||
@@ -329,6 +515,10 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
* @param resourceAttributes resource attributes
|
||||
*/
|
||||
async canI(resourceAttributes: V1ResourceAttributes): Promise<boolean> {
|
||||
const authApi = this.getProxyKubeconfig().makeApiClient(AuthorizationV1Api);
|
||||
|
||||
@@ -347,6 +537,9 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
async isClusterAdmin(): Promise<boolean> {
|
||||
return this.canI({
|
||||
namespace: "kube-system",
|
||||
@@ -372,7 +565,9 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
});
|
||||
}
|
||||
|
||||
// serializable cluster-state used for sync btw main <-> renderer
|
||||
/**
|
||||
* Serializable cluster-state used for sync btw main <-> renderer
|
||||
*/
|
||||
getState(): ClusterState {
|
||||
const state: ClusterState = {
|
||||
initialized: this.initialized,
|
||||
@@ -393,11 +588,18 @@ export class Cluster implements ClusterModel, ClusterState {
|
||||
});
|
||||
}
|
||||
|
||||
@action
|
||||
setState(state: ClusterState) {
|
||||
/**
|
||||
* @internal
|
||||
* @param state cluster state
|
||||
*/
|
||||
@action setState(state: ClusterState) {
|
||||
Object.assign(this, state);
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
* @param state cluster state
|
||||
*/
|
||||
pushState(state = this.getState()) {
|
||||
logger.silly(`[CLUSTER]: push-state`, state);
|
||||
broadcastMessage("cluster:state", this.id, state);
|
||||
|
||||
@@ -88,7 +88,9 @@ export class WindowManager extends Singleton {
|
||||
await this.mainWindow.loadURL(this.mainUrl);
|
||||
this.mainWindow.show();
|
||||
this.splashWindow?.close();
|
||||
appEventBus.emit({ name: "app", action: "start" });
|
||||
setTimeout(() => {
|
||||
appEventBus.emit({ name: "app", action: "start" });
|
||||
}, 1000);
|
||||
} catch (err) {
|
||||
dialog.showErrorBox("ERROR!", err.toString());
|
||||
}
|
||||
|
||||
@@ -3,19 +3,20 @@ import "./components/app.scss";
|
||||
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";
|
||||
import { workspaceStore } from "../common/workspace-store";
|
||||
import { clusterStore } from "../common/cluster-store";
|
||||
import { i18nStore } from "./i18n";
|
||||
import { themeStore } from "./theme.store";
|
||||
import { extensionsStore } from "../extensions/extensions-store";
|
||||
import { userStore } from "../common/user-store";
|
||||
import { isMac } from "../common/vars";
|
||||
import { workspaceStore } from "../common/workspace-store";
|
||||
import * as LensExtensions from "../extensions/extension-api";
|
||||
import { extensionDiscovery } from "../extensions/extension-discovery";
|
||||
import { extensionLoader } from "../extensions/extension-loader";
|
||||
import { extensionsStore } from "../extensions/extensions-store";
|
||||
import { filesystemProvisionerStore } from "../main/extension-filesystem";
|
||||
import { App } from "./components/app";
|
||||
import { i18nStore } from "./i18n";
|
||||
import { LensApp } from "./lens-app";
|
||||
import { themeStore } from "./theme.store";
|
||||
|
||||
type AppComponent = React.ComponentType & {
|
||||
init?(): Promise<void>;
|
||||
@@ -34,6 +35,7 @@ export async function bootstrap(App: AppComponent) {
|
||||
rootElem.classList.toggle("is-mac", isMac);
|
||||
|
||||
extensionLoader.init();
|
||||
extensionDiscovery.init();
|
||||
|
||||
// preload common stores
|
||||
await Promise.all([
|
||||
|
||||
@@ -12,6 +12,7 @@ import { apiManager } from "../../api/api-manager";
|
||||
export class EventStore extends KubeObjectStore<KubeEvent> {
|
||||
api = eventApi;
|
||||
limit = 1000;
|
||||
saveLimit = 50000;
|
||||
|
||||
protected bindWatchEventsUpdater() {
|
||||
return super.bindWatchEventsUpdater(5000);
|
||||
|
||||
@@ -5,6 +5,7 @@ import React from "react";
|
||||
import { extensionDiscovery } from "../../../../extensions/extension-discovery";
|
||||
import { ConfirmDialog } from "../../confirm-dialog";
|
||||
import { Notifications } from "../../notifications";
|
||||
import { ExtensionStateStore } from "../extension-install.store";
|
||||
import { Extensions } from "../extensions";
|
||||
|
||||
jest.mock("fs-extra");
|
||||
@@ -21,7 +22,8 @@ jest.mock("../../../../extensions/extension-discovery", () => ({
|
||||
...jest.requireActual("../../../../extensions/extension-discovery"),
|
||||
extensionDiscovery: {
|
||||
localFolderPath: "/fake/path",
|
||||
uninstallExtension: jest.fn(() => Promise.resolve())
|
||||
uninstallExtension: jest.fn(() => Promise.resolve()),
|
||||
isLoaded: true
|
||||
}
|
||||
}));
|
||||
|
||||
@@ -51,6 +53,10 @@ jest.mock("../../notifications", () => ({
|
||||
}));
|
||||
|
||||
describe("Extensions", () => {
|
||||
beforeEach(() => {
|
||||
ExtensionStateStore.resetInstance();
|
||||
});
|
||||
|
||||
it("disables uninstall and disable buttons while uninstalling", async () => {
|
||||
render(<><Extensions /><ConfirmDialog/></>);
|
||||
|
||||
@@ -61,14 +67,14 @@ describe("Extensions", () => {
|
||||
|
||||
// Approve confirm dialog
|
||||
fireEvent.click(screen.getByText("Yes"));
|
||||
|
||||
|
||||
expect(extensionDiscovery.uninstallExtension).toHaveBeenCalledWith("/absolute/path");
|
||||
expect(screen.getByText("Disable").closest("button")).toBeDisabled();
|
||||
expect(screen.getByText("Uninstall").closest("button")).toBeDisabled();
|
||||
});
|
||||
|
||||
it("displays error notification on uninstall error", () => {
|
||||
(extensionDiscovery.uninstallExtension as any).mockImplementationOnce(() =>
|
||||
(extensionDiscovery.uninstallExtension as any).mockImplementationOnce(() =>
|
||||
Promise.reject()
|
||||
);
|
||||
render(<><Extensions /><ConfirmDialog/></>);
|
||||
@@ -107,4 +113,17 @@ describe("Extensions", () => {
|
||||
expect(Notifications.error).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it("displays spinner while extensions are loading", () => {
|
||||
extensionDiscovery.isLoaded = false;
|
||||
const { container } = render(<Extensions />);
|
||||
|
||||
expect(container.querySelector(".Spinner")).toBeInTheDocument();
|
||||
|
||||
extensionDiscovery.isLoaded = true;
|
||||
|
||||
waitFor(() =>
|
||||
expect(container.querySelector(".Spinner")).not.toBeInTheDocument()
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
import { observable } from "mobx";
|
||||
import { autobind, Singleton } from "../../utils";
|
||||
|
||||
interface ExtensionState {
|
||||
displayName: string;
|
||||
// Possible states the extension can be
|
||||
state: "installing" | "uninstalling";
|
||||
}
|
||||
|
||||
@autobind()
|
||||
export class ExtensionStateStore extends Singleton {
|
||||
extensionState = observable.map<string, ExtensionState>();
|
||||
}
|
||||
@@ -37,6 +37,11 @@
|
||||
font-weight: bold;
|
||||
}
|
||||
}
|
||||
|
||||
> .spinner-wrapper {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
}
|
||||
|
||||
.SearchInput {
|
||||
|
||||
@@ -21,7 +21,9 @@ import { DropFileInput, Input, InputValidator, InputValidators, SearchInput } fr
|
||||
import { PageLayout } from "../layout/page-layout";
|
||||
import { SubTitle } from "../layout/sub-title";
|
||||
import { Notifications } from "../notifications";
|
||||
import { Spinner } from "../spinner/spinner";
|
||||
import { TooltipPosition } from "../tooltip";
|
||||
import { ExtensionStateStore } from "./extension-install.store";
|
||||
import "./extensions.scss";
|
||||
|
||||
interface InstallRequest {
|
||||
@@ -39,25 +41,20 @@ interface InstallRequestValidated extends InstallRequestPreloaded {
|
||||
tempFile: string; // temp system path to packed extension for unpacking
|
||||
}
|
||||
|
||||
interface ExtensionState {
|
||||
displayName: string;
|
||||
// Possible states the extension can be
|
||||
state: "installing" | "uninstalling";
|
||||
}
|
||||
|
||||
@observer
|
||||
export class Extensions extends React.Component {
|
||||
private supportedFormats = ["tar", "tgz"];
|
||||
private static supportedFormats = ["tar", "tgz"];
|
||||
|
||||
private installPathValidator: InputValidator = {
|
||||
private static installPathValidator: InputValidator = {
|
||||
message: <Trans>Invalid URL or absolute path</Trans>,
|
||||
validate(value: string) {
|
||||
return InputValidators.isUrl.validate(value) || InputValidators.isPath.validate(value);
|
||||
}
|
||||
};
|
||||
|
||||
@observable
|
||||
extensionState = observable.map<string, ExtensionState>();
|
||||
get extensionStateStore() {
|
||||
return ExtensionStateStore.getInstance<ExtensionStateStore>();
|
||||
}
|
||||
|
||||
@observable search = "";
|
||||
@observable installPath = "";
|
||||
@@ -69,18 +66,24 @@ export class Extensions extends React.Component {
|
||||
* Extensions that were removed from extensions but are still in "uninstalling" state
|
||||
*/
|
||||
@computed get removedUninstalling() {
|
||||
return Array.from(this.extensionState.entries()).filter(([id, extension]) =>
|
||||
extension.state === "uninstalling" && !this.extensions.find(extension => extension.id === id)
|
||||
).map(([id, extension]) => ({ ...extension, id }));
|
||||
return Array.from(this.extensionStateStore.extensionState.entries())
|
||||
.filter(([id, extension]) =>
|
||||
extension.state === "uninstalling"
|
||||
&& !this.extensions.find(extension => extension.id === id)
|
||||
)
|
||||
.map(([id, extension]) => ({ ...extension, id }));
|
||||
}
|
||||
|
||||
/**
|
||||
* Extensions that were added to extensions but are still in "installing" state
|
||||
*/
|
||||
@computed get addedInstalling() {
|
||||
return Array.from(this.extensionState.entries()).filter(([id, extension]) =>
|
||||
extension.state === "installing" && this.extensions.find(extension => extension.id === id)
|
||||
).map(([id, extension]) => ({ ...extension, id }));
|
||||
return Array.from(this.extensionStateStore.extensionState.entries())
|
||||
.filter(([id, extension]) =>
|
||||
extension.state === "installing"
|
||||
&& this.extensions.find(extension => extension.id === id)
|
||||
)
|
||||
.map(([id, extension]) => ({ ...extension, id }));
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
@@ -90,7 +93,7 @@ export class Extensions extends React.Component {
|
||||
Notifications.ok(
|
||||
<p>Extension <b>{displayName}</b> successfully uninstalled!</p>
|
||||
);
|
||||
this.extensionState.delete(id);
|
||||
this.extensionStateStore.extensionState.delete(id);
|
||||
});
|
||||
|
||||
this.addedInstalling.forEach(({ id, displayName }) => {
|
||||
@@ -103,7 +106,7 @@ export class Extensions extends React.Component {
|
||||
Notifications.ok(
|
||||
<p>Extension <b>{displayName}</b> successfully installed!</p>
|
||||
);
|
||||
this.extensionState.delete(id);
|
||||
this.extensionStateStore.extensionState.delete(id);
|
||||
this.installPath = "";
|
||||
|
||||
// Enable installed extensions by default.
|
||||
@@ -116,14 +119,11 @@ export class Extensions extends React.Component {
|
||||
@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(value => value);
|
||||
});
|
||||
return Array.from(extensionLoader.userExtensions.values())
|
||||
.filter(({ manifest: { name, description }}) => (
|
||||
name.toLowerCase().includes(searchText)
|
||||
|| description?.toLowerCase().includes(searchText)
|
||||
));
|
||||
}
|
||||
|
||||
get extensionsPath() {
|
||||
@@ -143,10 +143,10 @@ export class Extensions extends React.Component {
|
||||
const { canceled, filePaths } = await dialog.showOpenDialog(BrowserWindow.getFocusedWindow(), {
|
||||
defaultPath: app.getPath("downloads"),
|
||||
properties: ["openFile", "multiSelections"],
|
||||
message: _i18n._(t`Select extensions to install (formats: ${this.supportedFormats.join(", ")}), `),
|
||||
message: _i18n._(t`Select extensions to install (formats: ${Extensions.supportedFormats.join(", ")}), `),
|
||||
buttonLabel: _i18n._(t`Use configuration`),
|
||||
filters: [
|
||||
{ name: "tarball", extensions: this.supportedFormats }
|
||||
{ name: "tarball", extensions: Extensions.supportedFormats }
|
||||
]
|
||||
});
|
||||
|
||||
@@ -346,7 +346,9 @@ export class Extensions extends React.Component {
|
||||
const displayName = extensionDisplayName(name, version);
|
||||
const extensionId = path.join(extensionDiscovery.nodeModulesPath, name, "package.json");
|
||||
|
||||
this.extensionState.set(extensionId, {
|
||||
logger.info(`Unpacking extension ${displayName}`, { fileName, tempFile });
|
||||
|
||||
this.extensionStateStore.extensionState.set(extensionId, {
|
||||
state: "installing",
|
||||
displayName
|
||||
});
|
||||
@@ -381,8 +383,8 @@ export class Extensions extends React.Component {
|
||||
);
|
||||
|
||||
// Remove install state on install failure
|
||||
if (this.extensionState.get(extensionId)?.state === "installing") {
|
||||
this.extensionState.delete(extensionId);
|
||||
if (this.extensionStateStore.extensionState.get(extensionId)?.state === "installing") {
|
||||
this.extensionStateStore.extensionState.delete(extensionId);
|
||||
}
|
||||
} finally {
|
||||
// clean up
|
||||
@@ -406,7 +408,7 @@ export class Extensions extends React.Component {
|
||||
const displayName = extensionDisplayName(extension.manifest.name, extension.manifest.version);
|
||||
|
||||
try {
|
||||
this.extensionState.set(extension.id, {
|
||||
this.extensionStateStore.extensionState.set(extension.id, {
|
||||
state: "uninstalling",
|
||||
displayName
|
||||
});
|
||||
@@ -418,8 +420,8 @@ export class Extensions extends React.Component {
|
||||
);
|
||||
|
||||
// Remove uninstall state on uninstall failure
|
||||
if (this.extensionState.get(extension.id)?.state === "uninstalling") {
|
||||
this.extensionState.delete(extension.id);
|
||||
if (this.extensionStateStore.extensionState.get(extension.id)?.state === "uninstalling") {
|
||||
this.extensionStateStore.extensionState.delete(extension.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -445,7 +447,7 @@ export class Extensions extends React.Component {
|
||||
return extensions.map(extension => {
|
||||
const { id, isEnabled, manifest } = extension;
|
||||
const { name, description } = manifest;
|
||||
const isUninstalling = this.extensionState.get(id)?.state === "uninstalling";
|
||||
const isUninstalling = this.extensionStateStore.extensionState.get(id)?.state === "uninstalling";
|
||||
|
||||
return (
|
||||
<div key={id} className="extension flex gaps align-center">
|
||||
@@ -481,7 +483,7 @@ export class Extensions extends React.Component {
|
||||
* True if at least one extension is in installing state
|
||||
*/
|
||||
@computed get isInstalling() {
|
||||
return this.startingInstall || [...this.extensionState.values()].some(extension => extension.state === "installing");
|
||||
return [...this.extensionStateStore.extensionState.values()].some(extension => extension.state === "installing");
|
||||
}
|
||||
|
||||
render() {
|
||||
@@ -504,9 +506,9 @@ export class Extensions extends React.Component {
|
||||
className="box grow"
|
||||
theme="round-black"
|
||||
disabled={this.isInstalling}
|
||||
placeholder={`Path or URL to an extension package (${this.supportedFormats.join(", ")})`}
|
||||
placeholder={`Path or URL to an extension package (${Extensions.supportedFormats.join(", ")})`}
|
||||
showErrorsAsTooltip={{ preferredPositions: TooltipPosition.BOTTOM }}
|
||||
validators={installPath ? this.installPathValidator : undefined}
|
||||
validators={installPath ? Extensions.installPathValidator : undefined}
|
||||
value={installPath}
|
||||
onChange={value => this.installPath = value}
|
||||
onSubmit={this.installFromUrlOrPath}
|
||||
@@ -524,7 +526,7 @@ export class Extensions extends React.Component {
|
||||
<Button
|
||||
primary
|
||||
label="Install"
|
||||
disabled={this.isInstalling || !this.installPathValidator.validate(installPath)}
|
||||
disabled={this.isInstalling || !Extensions.installPathValidator.validate(installPath)}
|
||||
waiting={this.isInstalling}
|
||||
onClick={this.installFromUrlOrPath}
|
||||
/>
|
||||
@@ -540,7 +542,7 @@ export class Extensions extends React.Component {
|
||||
value={this.search}
|
||||
onChange={(value) => this.search = value}
|
||||
/>
|
||||
{this.renderExtensions()}
|
||||
{extensionDiscovery.isLoaded ? this.renderExtensions() : <div className="spinner-wrapper"><Spinner/></div>}
|
||||
</div>
|
||||
</PageLayout>
|
||||
</DropFileInput>
|
||||
|
||||
@@ -61,12 +61,14 @@ export class App extends React.Component {
|
||||
await requestMain(clusterSetFrameIdHandler, clusterId, frameId);
|
||||
await getHostedCluster().whenReady; // cluster.activate() is done at this point
|
||||
extensionLoader.loadOnClusterRenderer();
|
||||
appEventBus.emit({
|
||||
name: "cluster",
|
||||
action: "open",
|
||||
params: {
|
||||
clusterId
|
||||
}
|
||||
setTimeout(() => {
|
||||
appEventBus.emit({
|
||||
name: "cluster",
|
||||
action: "open",
|
||||
params: {
|
||||
clusterId
|
||||
}
|
||||
});
|
||||
});
|
||||
window.addEventListener("online", () => {
|
||||
window.location.reload();
|
||||
@@ -154,9 +156,7 @@ export class App extends React.Component {
|
||||
const page = clusterPageRegistry.getByPageTarget(menu.target);
|
||||
|
||||
if (page) {
|
||||
const pageComponent = () => <page.components.Page/>;
|
||||
|
||||
return <Route key={`extension-tab-layout-route-${index}`} path={page.url} component={pageComponent}/>;
|
||||
return <Route key={`extension-tab-layout-route-${index}`} path={page.url} component={page.components.Page}/>;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
jest.mock("../../../../common/ipc");
|
||||
|
||||
import React from "react";
|
||||
import { fireEvent, render } from "@testing-library/react";
|
||||
import "@testing-library/jest-dom/extend-expect";
|
||||
|
||||
import { MainLayoutHeader } from "../main-layout-header";
|
||||
import { Cluster } from "../../../../main/cluster";
|
||||
import { workspaceStore } from "../../../../common/workspace-store";
|
||||
import { broadcastMessage } from "../../../../common/ipc";
|
||||
|
||||
const mockBroadcastIpc = broadcastMessage as jest.MockedFunction<typeof broadcastMessage>;
|
||||
|
||||
const cluster: Cluster = new Cluster({
|
||||
id: "foo",
|
||||
contextName: "minikube",
|
||||
kubeConfigPath: "minikube-config.yml",
|
||||
workspace: workspaceStore.currentWorkspaceId
|
||||
});
|
||||
|
||||
describe("<MainLayoutHeader />", () => {
|
||||
it("renders w/o errors", () => {
|
||||
const { container } = render(<MainLayoutHeader cluster={cluster} />);
|
||||
|
||||
expect(container).toBeInstanceOf(HTMLElement);
|
||||
});
|
||||
|
||||
it("renders gear icon", () => {
|
||||
const { container } = render(<MainLayoutHeader cluster={cluster} />);
|
||||
const icon = container.querySelector(".Icon .icon");
|
||||
|
||||
expect(icon).toBeInstanceOf(HTMLElement);
|
||||
expect(icon).toHaveTextContent("settings");
|
||||
});
|
||||
|
||||
it("navigates to cluster settings", () => {
|
||||
const { container } = render(<MainLayoutHeader cluster={cluster} />);
|
||||
const icon = container.querySelector(".Icon");
|
||||
|
||||
fireEvent.click(icon);
|
||||
expect(mockBroadcastIpc).toBeCalledWith("renderer:navigate", "/cluster/foo/settings");
|
||||
});
|
||||
|
||||
it("renders cluster name", async () => {
|
||||
const { getByText } = render(<MainLayoutHeader cluster={cluster} />);
|
||||
|
||||
expect(await getByText("minikube")).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
import React from "react";
|
||||
import { Trans } from "@lingui/macro";
|
||||
|
||||
import { clusterSettingsURL } from "../+cluster-settings";
|
||||
import { broadcastMessage } from "../../../common/ipc";
|
||||
import { Cluster } from "../../../main/cluster";
|
||||
import { cssNames } from "../../utils";
|
||||
import { Icon } from "../icon";
|
||||
|
||||
interface Props {
|
||||
cluster: Cluster
|
||||
className?: string
|
||||
}
|
||||
|
||||
export function MainLayoutHeader({ cluster, className }: Props) {
|
||||
return (
|
||||
<header className={cssNames("flex gaps align-center justify-space-between", className)}>
|
||||
<span className="cluster">{cluster.name}</span>
|
||||
<Icon
|
||||
material="settings"
|
||||
tooltip={<Trans>Open cluster settings</Trans>}
|
||||
interactive
|
||||
onClick={() => {
|
||||
broadcastMessage("renderer:navigate", clusterSettingsURL({
|
||||
params: {
|
||||
clusterId: cluster.id
|
||||
}
|
||||
}));
|
||||
}}
|
||||
/>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
@@ -14,15 +14,6 @@
|
||||
grid-area: header;
|
||||
background: $layoutBackground;
|
||||
padding: $padding $padding * 2;
|
||||
|
||||
span + .lens-version {
|
||||
margin-left: $margin;
|
||||
}
|
||||
|
||||
.lens-version {
|
||||
font-size: x-small;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
}
|
||||
|
||||
> aside {
|
||||
|
||||
@@ -3,12 +3,13 @@ import "./main-layout.scss";
|
||||
import React from "react";
|
||||
import { observable, reaction } from "mobx";
|
||||
import { disposeOnUnmount, observer } from "mobx-react";
|
||||
import { autobind, createStorage, cssNames } from "../../utils";
|
||||
import { Sidebar } from "./sidebar";
|
||||
import { ErrorBoundary } from "../error-boundary";
|
||||
import { Dock } from "../dock";
|
||||
import { getHostedCluster } from "../../../common/cluster-store";
|
||||
import { autobind, createStorage, cssNames } from "../../utils";
|
||||
import { Dock } from "../dock";
|
||||
import { ErrorBoundary } from "../error-boundary";
|
||||
import { ResizeDirection, ResizeGrowthDirection, ResizeSide, ResizingAnchor } from "../resizing-anchor";
|
||||
import { MainLayoutHeader } from "./main-layout-header";
|
||||
import { Sidebar } from "./sidebar";
|
||||
|
||||
export interface MainLayoutProps {
|
||||
className?: any;
|
||||
@@ -66,9 +67,7 @@ export class MainLayout extends React.Component<MainLayoutProps> {
|
||||
|
||||
return (
|
||||
<div className={cssNames("MainLayout", className)} style={this.getSidebarSize() as any}>
|
||||
<header className={cssNames("flex gaps align-center", headerClass)}>
|
||||
<span className="cluster">{cluster.name}</span>
|
||||
</header>
|
||||
<MainLayoutHeader className={headerClass} cluster={cluster} />
|
||||
|
||||
<aside className={cssNames("flex column", { pinned: this.isPinned, accessible: this.isAccessible })}>
|
||||
<Sidebar className="box grow" isPinned={this.isPinned} toggle={this.toggleSidebar} />
|
||||
|
||||
@@ -279,7 +279,9 @@ class SidebarNavItem extends React.Component<SidebarNavItemProps> {
|
||||
public context: SidebarContextValue;
|
||||
|
||||
get itemId() {
|
||||
return this.props.url;
|
||||
const url = new URL(this.props.url, `${window.location.protocol}//${window.location.host}`);
|
||||
|
||||
return url.pathname; // pathname without get params
|
||||
}
|
||||
|
||||
@computed get isExpanded() {
|
||||
|
||||
@@ -11,7 +11,8 @@ import { getHostedCluster } from "../common/cluster-store";
|
||||
@autobind()
|
||||
export abstract class KubeObjectStore<T extends KubeObject = any> extends ItemStore<T> {
|
||||
abstract api: KubeApi<T>;
|
||||
public limit: number;
|
||||
public readonly limit?: number;
|
||||
public readonly bufferSize: number = 50000;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
@@ -19,6 +20,16 @@ export abstract class KubeObjectStore<T extends KubeObject = any> extends ItemSt
|
||||
kubeWatchApi.addListener(this, this.onWatchApiEvent);
|
||||
}
|
||||
|
||||
get query(): IKubeApiQueryParams {
|
||||
const { limit } = this;
|
||||
|
||||
if (!limit) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return { limit };
|
||||
}
|
||||
|
||||
getStatuses?(items: T[]): Record<string, number>;
|
||||
|
||||
getAllByNs(namespace: string | string[], strict = false): T[] {
|
||||
@@ -62,10 +73,7 @@ export abstract class KubeObjectStore<T extends KubeObject = any> extends ItemSt
|
||||
|
||||
protected async loadItems(allowedNamespaces?: string[]): Promise<T[]> {
|
||||
if (!this.api.isNamespaced || !allowedNamespaces) {
|
||||
const { limit } = this;
|
||||
const query: IKubeApiQueryParams = limit ? { limit } : {};
|
||||
|
||||
return this.api.list({}, query);
|
||||
return this.api.list({}, this.query);
|
||||
} else {
|
||||
return Promise
|
||||
.all(allowedNamespaces.map(namespace => this.api.list({ namespace })))
|
||||
@@ -179,9 +187,9 @@ export abstract class KubeObjectStore<T extends KubeObject = any> extends ItemSt
|
||||
return;
|
||||
}
|
||||
// create latest non-observable copy of items to apply updates in one action (==single render)
|
||||
let items = this.items.toJS();
|
||||
const items = this.items.toJS();
|
||||
|
||||
this.eventsBuffer.clear().forEach(({ type, object }) => {
|
||||
for (const {type, object} of this.eventsBuffer.clear()) {
|
||||
const { uid, selfLink } = object.metadata;
|
||||
const index = items.findIndex(item => item.getId() === uid);
|
||||
const item = items[index];
|
||||
@@ -204,14 +212,9 @@ export abstract class KubeObjectStore<T extends KubeObject = any> extends ItemSt
|
||||
}
|
||||
break;
|
||||
}
|
||||
});
|
||||
|
||||
// slice to max allowed items
|
||||
if (this.limit && items.length > this.limit) {
|
||||
items = items.slice(-this.limit);
|
||||
}
|
||||
|
||||
// update items
|
||||
this.items.replace(this.sortItems(items));
|
||||
this.items.replace(this.sortItems(items.slice(-this.bufferSize)));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user