mirror of
https://github.com/lensapp/lens.git
synced 2025-05-20 05:10:56 +00:00
Merge branch 'master' into improve-dock-tabs-ux
This commit is contained in:
commit
00121fd044
76 files changed
+8535
-12202
No files matched your search
+2
-10
@@ -3,19 +3,11 @@
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
import { getInjectable, lifecycleEnum } from "@ogre-tools/injectable";
|
||||
import path from "path";
|
||||
import isDevelopmentInjectable from "../../vars/is-development.injectable";
|
||||
import contextDirInjectable from "../../vars/context-dir.injectable";
|
||||
import { baseBinariesDir } from "../../vars";
|
||||
|
||||
const directoryForBundledBinariesInjectable = getInjectable({
|
||||
id: "directory-for-bundled-binaries",
|
||||
instantiate: (di) => {
|
||||
if (di.inject(isDevelopmentInjectable)) {
|
||||
return path.join(di.inject(contextDirInjectable), "binaries");
|
||||
}
|
||||
|
||||
return process.resourcesPath;
|
||||
},
|
||||
instantiate: () => baseBinariesDir.get(),
|
||||
lifecycle: lifecycleEnum.singleton,
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
|
||||
export const setNativeThemeChannel = "theme:set-native-theme";
|
||||
export const getNativeThemeChannel = "theme:get-native-theme";
|
||||
@@ -36,13 +36,6 @@ describe("HelmChart tests", () => {
|
||||
version: "!",
|
||||
repo: "!",
|
||||
} as any)).toThrowError('"created" is required');
|
||||
expect(() => HelmChart.create({
|
||||
apiVersion: "!",
|
||||
name: "!",
|
||||
version: "!",
|
||||
repo: "!",
|
||||
created: "!",
|
||||
} as any)).toThrowError('"digest" is required');
|
||||
});
|
||||
|
||||
it("should throw on fields being wrong type", () => {
|
||||
@@ -62,6 +55,14 @@ describe("HelmChart tests", () => {
|
||||
created: "!",
|
||||
digest: "!",
|
||||
} as any)).toThrowError('"name" must be a string');
|
||||
expect(() => HelmChart.create({
|
||||
apiVersion: "!",
|
||||
name: "!",
|
||||
version: "!",
|
||||
repo: "!",
|
||||
created: "!",
|
||||
digest: 1,
|
||||
} as any)).toThrowError('"digest" must be a string');
|
||||
expect(() => HelmChart.create({
|
||||
apiVersion: "1",
|
||||
name: "",
|
||||
|
||||
@@ -32,7 +32,7 @@ export class ApiManager {
|
||||
return iter.find(this.apis.values(), api => api.kind === kind && api.apiVersionWithGroup === apiVersion);
|
||||
}
|
||||
|
||||
registerApi(apiBase: string, api: KubeApi<KubeObject>) {
|
||||
registerApi<K extends KubeObject>(apiBase: string, api: KubeApi<K>) {
|
||||
if (!api.apiBase) return;
|
||||
|
||||
if (!this.apis.has(apiBase)) {
|
||||
@@ -46,13 +46,13 @@ export class ApiManager {
|
||||
}
|
||||
}
|
||||
|
||||
protected resolveApi<K extends KubeObject>(api?: string | KubeApi<K>): KubeApi<K> | undefined {
|
||||
protected resolveApi(api?: string | KubeApi<KubeObject>): KubeApi<KubeObject> | undefined {
|
||||
if (!api) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (typeof api === "string") {
|
||||
return this.getApi(api) as KubeApi<K>;
|
||||
return this.getApi(api) as KubeApi<KubeObject>;
|
||||
}
|
||||
|
||||
return api;
|
||||
@@ -69,7 +69,7 @@ export class ApiManager {
|
||||
}
|
||||
|
||||
@action
|
||||
registerStore(store: KubeObjectStore<KubeObject>, apis: KubeApi<KubeObject>[] = [store.api]) {
|
||||
registerStore<K extends KubeObject>(store: KubeObjectStore<K>, apis: KubeApi<K>[] = [store.api]) {
|
||||
apis.filter(Boolean).forEach(api => {
|
||||
if (api.apiBase) this.stores.set(api.apiBase, store);
|
||||
});
|
||||
|
||||
@@ -75,7 +75,7 @@ export interface RawHelmChart {
|
||||
version: string;
|
||||
repo: string;
|
||||
created: string;
|
||||
digest: string;
|
||||
digest?: string;
|
||||
kubeVersion?: string;
|
||||
description?: string;
|
||||
home?: string;
|
||||
@@ -142,7 +142,7 @@ const helmChartValidator = Joi.object<HelmChart, true, RawHelmChart>({
|
||||
.required(),
|
||||
digest: Joi
|
||||
.string()
|
||||
.required(),
|
||||
.optional(),
|
||||
kubeVersion: Joi
|
||||
.string()
|
||||
.optional(),
|
||||
@@ -247,22 +247,22 @@ export interface HelmChart {
|
||||
name: string;
|
||||
version: string;
|
||||
repo: string;
|
||||
kubeVersion?: string;
|
||||
created: string;
|
||||
description: string;
|
||||
digest: string;
|
||||
keywords: string[];
|
||||
home?: string;
|
||||
sources: string[];
|
||||
urls: string[];
|
||||
annotations: Record<string, string>;
|
||||
dependencies: HelmChartDependency[];
|
||||
maintainers: HelmChartMaintainer[];
|
||||
deprecated: boolean;
|
||||
kubeVersion?: string;
|
||||
digest?: string;
|
||||
home?: string;
|
||||
engine?: string;
|
||||
icon?: string;
|
||||
appVersion?: string;
|
||||
type?: string;
|
||||
deprecated: boolean;
|
||||
tillerVersion?: string;
|
||||
}
|
||||
|
||||
@@ -324,7 +324,11 @@ export class HelmChart {
|
||||
}
|
||||
|
||||
getId(): string {
|
||||
return `${this.repo}:${this.apiVersion}/${this.name}@${this.getAppVersion()}+${this.digest}`;
|
||||
const digestPart = this.digest
|
||||
? `+${this.digest}`
|
||||
: "";
|
||||
|
||||
return `${this.repo}:${this.apiVersion}/${this.name}@${this.getAppVersion()}${digestPart}`;
|
||||
}
|
||||
|
||||
getName(): string {
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
/**
|
||||
* A OnceCell is an object that wraps some function that produces a value.
|
||||
*
|
||||
* It then only calls the function on the first call to `get()` and returns the
|
||||
* same instance/value on every subsequent call.
|
||||
*/
|
||||
export interface LazyInitialized<T> {
|
||||
get(): T;
|
||||
}
|
||||
|
||||
/**
|
||||
* A function to make a `OnceCell<T>`
|
||||
*/
|
||||
export function lazyInitialized<T>(builder: () => T): LazyInitialized<T> {
|
||||
let value: T | undefined;
|
||||
let called = false;
|
||||
|
||||
return {
|
||||
get() {
|
||||
if (called) {
|
||||
return value;
|
||||
}
|
||||
|
||||
value = builder();
|
||||
called = true;
|
||||
|
||||
return value;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import path from "path";
|
||||
import { SemVer } from "semver";
|
||||
import packageInfo from "../../package.json";
|
||||
import { defineGlobal } from "./utils/defineGlobal";
|
||||
import { lazyInitialized } from "./utils/lazy-initialized";
|
||||
|
||||
export const isMac = process.platform === "darwin";
|
||||
export const isWindows = process.platform === "win32";
|
||||
@@ -29,6 +30,54 @@ export const defaultTheme = "lens-dark" as string;
|
||||
export const defaultFontSize = 12;
|
||||
export const defaultTerminalFontFamily = "RobotoMono";
|
||||
export const defaultEditorFontFamily = "RobotoMono";
|
||||
export const normalizedPlatform = (() => {
|
||||
switch (process.platform) {
|
||||
case "darwin":
|
||||
return "darwin";
|
||||
case "linux":
|
||||
return "linux";
|
||||
case "win32":
|
||||
return "windows";
|
||||
default:
|
||||
throw new Error(`platform=${process.platform} is unsupported`);
|
||||
}
|
||||
})();
|
||||
export const normalizedArch = (() => {
|
||||
switch (process.arch) {
|
||||
case "arm64":
|
||||
return "arm64";
|
||||
case "x64":
|
||||
case "amd64":
|
||||
return "x64";
|
||||
case "386":
|
||||
case "x32":
|
||||
case "ia32":
|
||||
return "ia32";
|
||||
default:
|
||||
throw new Error(`arch=${process.arch} is unsupported`);
|
||||
}
|
||||
})();
|
||||
|
||||
export function getBinaryName(name: string, { forPlatform = normalizedPlatform } = {}): string {
|
||||
if (forPlatform === "windows") {
|
||||
return `${name}.exe`;
|
||||
}
|
||||
|
||||
return name;
|
||||
}
|
||||
|
||||
const resourcesDir = lazyInitialized(() => (
|
||||
isProduction
|
||||
? process.resourcesPath
|
||||
: path.join(process.cwd(), "binaries", "client", normalizedPlatform)
|
||||
));
|
||||
|
||||
export const baseBinariesDir = lazyInitialized(() => path.join(resourcesDir.get(), normalizedArch));
|
||||
export const kubeAuthProxyBinaryName = getBinaryName("lens-k8s-proxy");
|
||||
export const helmBinaryName = getBinaryName("helm");
|
||||
export const helmBinaryPath = lazyInitialized(() => path.join(baseBinariesDir.get(), helmBinaryName));
|
||||
export const kubectlBinaryName = getBinaryName("kubectl");
|
||||
export const kubectlBinaryPath = lazyInitialized(() => path.join(baseBinariesDir.get(), kubectlBinaryName));
|
||||
|
||||
// Webpack build paths
|
||||
export const contextDir = process.cwd();
|
||||
|
||||
@@ -6,7 +6,7 @@ export type { StatusBarRegistration } from "../../renderer/components/status-bar
|
||||
export type { KubeObjectMenuRegistration, KubeObjectMenuComponents } from "../../renderer/components/kube-object-menu/dependencies/kube-object-menu-items/kube-object-menu-registration";
|
||||
export type { AppPreferenceRegistration, AppPreferenceComponents } from "../../renderer/components/+preferences/app-preferences/app-preference-registration";
|
||||
export type { KubeObjectDetailRegistration, KubeObjectDetailComponents } from "../registries/kube-object-detail-registry";
|
||||
export type { KubeObjectStatusRegistration } from "../registries/kube-object-status-registry";
|
||||
export type { KubeObjectStatusRegistration } from "../../renderer/components/kube-object-status-icon/kube-object-status-registration";
|
||||
export type { PageRegistration, RegisteredPage, PageParams, PageComponentProps, PageComponents, PageTarget } from "../registries/page-registry";
|
||||
export type { ClusterPageMenuRegistration, ClusterPageMenuComponents } from "../registries/page-menu-registry";
|
||||
export type { ProtocolHandlerRegistration, RouteParams as ProtocolRouteParams, RouteHandler as ProtocolRouteHandler } from "../registries/protocol-handler";
|
||||
|
||||
@@ -277,8 +277,6 @@ export class ExtensionLoader {
|
||||
registries.ClusterPageRegistry.getInstance().add(extension.clusterPages, extension),
|
||||
registries.ClusterPageMenuRegistry.getInstance().add(extension.clusterPageMenus, extension),
|
||||
registries.KubeObjectDetailRegistry.getInstance().add(extension.kubeObjectDetailItems),
|
||||
registries.KubeObjectStatusRegistry.getInstance().add(extension.kubeObjectStatusTexts),
|
||||
registries.WorkloadsOverviewDetailRegistry.getInstance().add(extension.kubeWorkloadsOverviewItems),
|
||||
];
|
||||
|
||||
this.events.on("remove", (removedExtension: LensRendererExtension) => {
|
||||
|
||||
@@ -20,18 +20,20 @@ import type { AdditionalCategoryColumnRegistration } from "../renderer/component
|
||||
import type { CustomCategoryViewRegistration } from "../renderer/components/+catalog/custom-views";
|
||||
import type { StatusBarRegistration } from "../renderer/components/status-bar/status-bar-registration";
|
||||
import type { KubeObjectMenuRegistration } from "../renderer/components/kube-object-menu/dependencies/kube-object-menu-items/kube-object-menu-registration";
|
||||
import type { WorkloadsOverviewDetailRegistration } from "../renderer/components/+workloads-overview/workloads-overview-detail-registration";
|
||||
import type { KubeObjectStatusRegistration } from "../renderer/components/kube-object-status-icon/kube-object-status-registration";
|
||||
|
||||
export class LensRendererExtension extends LensExtension {
|
||||
globalPages: registries.PageRegistration[] = [];
|
||||
clusterPages: registries.PageRegistration[] = [];
|
||||
clusterPageMenus: registries.ClusterPageMenuRegistration[] = [];
|
||||
kubeObjectStatusTexts: registries.KubeObjectStatusRegistration[] = [];
|
||||
kubeObjectStatusTexts: KubeObjectStatusRegistration[] = [];
|
||||
appPreferences: AppPreferenceRegistration[] = [];
|
||||
entitySettings: registries.EntitySettingRegistration[] = [];
|
||||
statusBarItems: StatusBarRegistration[] = [];
|
||||
kubeObjectDetailItems: registries.KubeObjectDetailRegistration[] = [];
|
||||
kubeObjectMenuItems: KubeObjectMenuRegistration[] = [];
|
||||
kubeWorkloadsOverviewItems: registries.WorkloadsOverviewDetailRegistration[] = [];
|
||||
kubeWorkloadsOverviewItems: WorkloadsOverviewDetailRegistration[] = [];
|
||||
commands: CommandRegistration[] = [];
|
||||
welcomeMenus: WelcomeMenuRegistration[] = [];
|
||||
welcomeBanners: WelcomeBannerRegistration[] = [];
|
||||
|
||||
@@ -29,6 +29,10 @@ jest.mock("electron", () => ({
|
||||
on: jest.fn(),
|
||||
handle: jest.fn(),
|
||||
},
|
||||
ipcRenderer: {
|
||||
on: jest.fn(),
|
||||
invoke: jest.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
console = new Console(stdout, stderr);
|
||||
|
||||
@@ -8,8 +8,6 @@
|
||||
export * from "./page-registry";
|
||||
export * from "./page-menu-registry";
|
||||
export * from "./kube-object-detail-registry";
|
||||
export * from "./kube-object-status-registry";
|
||||
export * from "./entity-setting-registry";
|
||||
export * from "./catalog-entity-detail-registry";
|
||||
export * from "./workloads-overview-detail-registry";
|
||||
export * from "./protocol-handler";
|
||||
@@ -1,29 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import type { 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) => (
|
||||
item.kind === kind
|
||||
&& item.apiVersions.includes(apiVersion)
|
||||
));
|
||||
}
|
||||
|
||||
getItemsForObject(src: KubeObject) {
|
||||
return this.getItemsForKind(src.kind, src.apiVersion)
|
||||
.map(item => item.resolve(src))
|
||||
.filter(Boolean);
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import { orderBy } from "lodash";
|
||||
import type React from "react";
|
||||
import { BaseRegistry } from "./base-registry";
|
||||
|
||||
export interface WorkloadsOverviewDetailComponents {
|
||||
Details: React.ComponentType<{}>;
|
||||
}
|
||||
|
||||
export interface WorkloadsOverviewDetailRegistration {
|
||||
components: WorkloadsOverviewDetailComponents;
|
||||
priority?: number;
|
||||
}
|
||||
|
||||
type RegisteredWorkloadsOverviewDetail = Required<WorkloadsOverviewDetailRegistration>;
|
||||
|
||||
export class WorkloadsOverviewDetailRegistry extends BaseRegistry<WorkloadsOverviewDetailRegistration, RegisteredWorkloadsOverviewDetail> {
|
||||
getItems() {
|
||||
return orderBy(super.getItems(), "priority", "desc");
|
||||
}
|
||||
|
||||
protected getRegisteredItem(item: WorkloadsOverviewDetailRegistration): RegisteredWorkloadsOverviewDetail {
|
||||
const { priority = 50, ...rest } = item;
|
||||
|
||||
return { priority, ...rest };
|
||||
}
|
||||
}
|
||||
@@ -118,7 +118,7 @@ export class ContextHandler {
|
||||
await this.ensureServer();
|
||||
const path = this.clusterUrl.path !== "/" ? this.clusterUrl.path : "";
|
||||
|
||||
return `http://127.0.0.1:${this.kubeAuthProxy.port}${this.kubeAuthProxy.apiPrefix.slice(0, -1)}${path}`;
|
||||
return `http://127.0.0.1:${this.kubeAuthProxy.port}${this.kubeAuthProxy.apiPrefix}${path}`;
|
||||
}
|
||||
|
||||
async getApiTarget(isLongRunningRequest = false): Promise<httpProxy.ServerOptions> {
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import { promiseExecFile } from "../../common/utils/promise-exec";
|
||||
import type { BaseEncodingOptions } from "fs";
|
||||
import type { ExecFileOptions } from "child_process";
|
||||
import { helmBinaryPath } from "../../common/vars";
|
||||
|
||||
/**
|
||||
* ExecFile the bundled helm CLI
|
||||
* @returns STDOUT
|
||||
*/
|
||||
export async function execHelm(args: string[], options?: BaseEncodingOptions & ExecFileOptions): Promise<string> {
|
||||
try {
|
||||
const { stdout } = await promiseExecFile(helmBinaryPath.get(), args, options);
|
||||
|
||||
return stdout;
|
||||
} catch (error) {
|
||||
throw error?.stderr || error;
|
||||
}
|
||||
}
|
||||
@@ -8,10 +8,9 @@ import v8 from "v8";
|
||||
import * as yaml from "js-yaml";
|
||||
import type { HelmRepo } from "./helm-repo-manager";
|
||||
import logger from "../logger";
|
||||
import { promiseExecFile } from "../../common/utils/promise-exec";
|
||||
import { helmCli } from "./helm-cli";
|
||||
import type { RepoHelmChartList } from "../../common/k8s-api/endpoints/helm-charts.api";
|
||||
import { iter, sortCharts } from "../../common/utils";
|
||||
import { execHelm } from "./exec";
|
||||
|
||||
interface ChartCacheEntry {
|
||||
data: Buffer;
|
||||
@@ -49,21 +48,13 @@ export class HelmChartManager {
|
||||
}
|
||||
|
||||
private async executeCommand(args: string[], name: string, version?: string) {
|
||||
const helm = await helmCli.binaryPath();
|
||||
|
||||
args.push(`${this.repo.name}/${name}`);
|
||||
|
||||
if (version) {
|
||||
args.push("--version", version);
|
||||
}
|
||||
|
||||
try {
|
||||
const { stdout } = await promiseExecFile(helm, args);
|
||||
|
||||
return stdout;
|
||||
} catch (error) {
|
||||
throw error.stderr || error;
|
||||
}
|
||||
return execHelm(args);
|
||||
}
|
||||
|
||||
public async getReadme(name: string, version?: string) {
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import packageInfo from "../../../package.json";
|
||||
import path from "path";
|
||||
import { LensBinary, LensBinaryOpts } from "../lens-binary";
|
||||
import { isProduction } from "../../common/vars";
|
||||
|
||||
export class HelmCli extends LensBinary {
|
||||
|
||||
public constructor(baseDir: string, version: string) {
|
||||
const opts: LensBinaryOpts = {
|
||||
version,
|
||||
baseDir,
|
||||
originalBinaryName: "helm",
|
||||
newBinaryName: "helm3",
|
||||
};
|
||||
|
||||
super(opts);
|
||||
}
|
||||
|
||||
protected getTarName(): string | null {
|
||||
return `${this.binaryName}-v${this.binaryVersion}-${this.platformName}-${this.arch}.tar.gz`;
|
||||
}
|
||||
|
||||
protected getUrl() {
|
||||
return `https://get.helm.sh/helm-v${this.binaryVersion}-${this.platformName}-${this.arch}.tar.gz`;
|
||||
}
|
||||
|
||||
protected getBinaryPath() {
|
||||
return path.join(this.dirname, this.binaryName);
|
||||
}
|
||||
|
||||
protected getOriginalBinaryPath() {
|
||||
return path.join(this.dirname, `${this.platformName}-${this.arch}`, this.originalBinaryName);
|
||||
}
|
||||
}
|
||||
|
||||
const helmVersion = packageInfo.config.bundledHelmVersion;
|
||||
let baseDir = process.resourcesPath;
|
||||
|
||||
if (!isProduction) {
|
||||
baseDir = path.join(process.cwd(), "binaries", "client", process.arch);
|
||||
}
|
||||
|
||||
export const helmCli = new HelmCli(baseDir, helmVersion);
|
||||
|
||||
@@ -6,23 +6,9 @@
|
||||
import tempy from "tempy";
|
||||
import fse from "fs-extra";
|
||||
import * as yaml from "js-yaml";
|
||||
import { promiseExecFile } from "../../common/utils/promise-exec";
|
||||
import { helmCli } from "./helm-cli";
|
||||
import { toCamelCase } from "../../common/utils/camelCase";
|
||||
import type { BaseEncodingOptions } from "fs";
|
||||
import { execFile, ExecFileOptions } from "child_process";
|
||||
|
||||
async function execHelm(args: string[], options?: BaseEncodingOptions & ExecFileOptions): Promise<string> {
|
||||
const helmCliPath = await helmCli.binaryPath();
|
||||
|
||||
try {
|
||||
const { stdout } = await promiseExecFile(helmCliPath, args, options);
|
||||
|
||||
return stdout;
|
||||
} catch (error) {
|
||||
throw error?.stderr || error;
|
||||
}
|
||||
}
|
||||
import { execFile } from "child_process";
|
||||
import { execHelm } from "./exec";
|
||||
|
||||
export async function listReleases(pathToKubeconfig: string, namespace?: string): Promise<Record<string, any>[]> {
|
||||
const args = [
|
||||
|
||||
@@ -4,14 +4,12 @@
|
||||
*/
|
||||
|
||||
import yaml from "js-yaml";
|
||||
import { BaseEncodingOptions, readFile } from "fs-extra";
|
||||
import { promiseExecFile } from "../../common/utils/promise-exec";
|
||||
import { helmCli } from "./helm-cli";
|
||||
import { readFile } from "fs-extra";
|
||||
import { Singleton } from "../../common/utils/singleton";
|
||||
import { customRequestPromise } from "../../common/request";
|
||||
import orderBy from "lodash/orderBy";
|
||||
import logger from "../logger";
|
||||
import type { ExecFileOptions } from "child_process";
|
||||
import { execHelm } from "./exec";
|
||||
|
||||
export type HelmEnv = Record<string, string> & {
|
||||
HELM_REPOSITORY_CACHE?: string;
|
||||
@@ -34,18 +32,6 @@ export interface HelmRepo {
|
||||
password?: string;
|
||||
}
|
||||
|
||||
async function execHelm(args: string[], options?: BaseEncodingOptions & ExecFileOptions): Promise<string> {
|
||||
const helmCliPath = await helmCli.binaryPath();
|
||||
|
||||
try {
|
||||
const { stdout } = await promiseExecFile(helmCliPath, args, options);
|
||||
|
||||
return stdout;
|
||||
} catch (error) {
|
||||
throw error?.stderr || error;
|
||||
}
|
||||
}
|
||||
|
||||
export class HelmRepoManager extends Singleton {
|
||||
protected repos: HelmRepo[];
|
||||
protected helmEnv: HelmEnv;
|
||||
@@ -63,9 +49,6 @@ export class HelmRepoManager extends Singleton {
|
||||
}
|
||||
|
||||
private async ensureInitialized() {
|
||||
helmCli.setLogger(logger);
|
||||
await helmCli.ensureBinary();
|
||||
|
||||
this.helmEnv ??= await this.parseHelmEnv();
|
||||
|
||||
const repos = await this.list();
|
||||
|
||||
+6
-12
@@ -7,10 +7,11 @@
|
||||
|
||||
import { injectSystemCAs } from "../common/system-ca";
|
||||
import * as Mobx from "mobx";
|
||||
import httpProxy from "http-proxy";
|
||||
import * as LensExtensionsCommonApi from "../extensions/common-api";
|
||||
import * as LensExtensionsMainApi from "../extensions/main-api";
|
||||
import { app, autoUpdater, dialog, powerMonitor } from "electron";
|
||||
import { appName, isIntegrationTesting, isMac, isWindows, productName, isDevelopment } from "../common/vars";
|
||||
import { appName, isIntegrationTesting, isMac, isWindows, productName } from "../common/vars";
|
||||
import { LensProxy } from "./lens-proxy";
|
||||
import { WindowManager } from "./window-manager";
|
||||
import { ClusterManager } from "./cluster-manager";
|
||||
@@ -55,6 +56,7 @@ import routerInjectable from "./router/router.injectable";
|
||||
import shellApiRequestInjectable from "./proxy-functions/shell-api-request/shell-api-request.injectable";
|
||||
import userStoreInjectable from "../common/user-store/user-store.injectable";
|
||||
import trayMenuItemsInjectable from "./tray/tray-menu-items.injectable";
|
||||
import { broadcastNativeThemeOnUpdate } from "./native-theme";
|
||||
|
||||
const di = getDi();
|
||||
|
||||
@@ -108,6 +110,8 @@ di.runSetups().then(() => {
|
||||
}
|
||||
}
|
||||
|
||||
broadcastNativeThemeOnUpdate();
|
||||
|
||||
app.on("second-instance", (event, argv) => {
|
||||
logger.debug("second-instance message");
|
||||
|
||||
@@ -164,7 +168,7 @@ di.runSetups().then(() => {
|
||||
const router = di.inject(routerInjectable);
|
||||
const shellApiRequest = di.inject(shellApiRequestInjectable);
|
||||
|
||||
const lensProxy = LensProxy.createInstance(router, {
|
||||
const lensProxy = LensProxy.createInstance(router, httpProxy.createProxy(), {
|
||||
getClusterForRequest: (req) => ClusterManager.getInstance().getClusterForRequest(req),
|
||||
kubeApiRequest,
|
||||
shellApiRequest,
|
||||
@@ -227,16 +231,6 @@ di.runSetups().then(() => {
|
||||
|
||||
logger.info("🖥️ Starting WindowManager");
|
||||
const windowManager = WindowManager.createInstance();
|
||||
|
||||
// Override main content view url to local webpack-dev-server to support HMR / live-reload
|
||||
if (isDevelopment) {
|
||||
const { createDevServer } = await import("../../webpack.dev-server");
|
||||
const devServer = createDevServer(lensProxy.port);
|
||||
|
||||
await devServer.start();
|
||||
windowManager.mainContentUrl = `http://localhost:${devServer.options.port}`;
|
||||
}
|
||||
|
||||
const menuItems = di.inject(electronMenuItemsInjectable);
|
||||
const trayMenuItems = di.inject(trayMenuItemsInjectable);
|
||||
|
||||
|
||||
@@ -24,6 +24,8 @@ import { onLocationChange, handleWindowAction } from "../../ipc/window";
|
||||
import { openFilePickingDialogChannel } from "../../../common/ipc/dialog";
|
||||
import { showOpenDialog } from "../../ipc/dialog";
|
||||
import { windowActionHandleChannel, windowLocationChangedChannel, windowOpenAppMenuAsContextMenuChannel } from "../../../common/ipc/window";
|
||||
import { getNativeColorTheme } from "../../native-theme";
|
||||
import { getNativeThemeChannel } from "../../../common/ipc/native-theme";
|
||||
|
||||
interface Dependencies {
|
||||
electronMenuItems: IComputedValue<MenuRegistration[]>;
|
||||
@@ -158,4 +160,8 @@ export const initIpcMainHandlers = ({ electronMenuItems, directoryForLensLocalSt
|
||||
y: 20,
|
||||
});
|
||||
});
|
||||
|
||||
ipcMainHandle(getNativeThemeChannel, () => {
|
||||
return getNativeColorTheme();
|
||||
});
|
||||
};
|
||||
@@ -3,24 +3,24 @@
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
import { getInjectable } from "@ogre-tools/injectable";
|
||||
import { KubeAuthProxy } from "./kube-auth-proxy";
|
||||
import { KubeAuthProxy, KubeAuthProxyDependencies } from "./kube-auth-proxy";
|
||||
import type { Cluster } from "../../common/cluster/cluster";
|
||||
import path from "path";
|
||||
import { isDevelopment, isWindows } from "../../common/vars";
|
||||
import { getBinaryName } from "../../common/vars";
|
||||
import directoryForBundledBinariesInjectable from "../../common/app-paths/directory-for-bundled-binaries/directory-for-bundled-binaries.injectable";
|
||||
|
||||
const createKubeAuthProxyInjectable = getInjectable({
|
||||
id: "create-kube-auth-proxy",
|
||||
|
||||
instantiate: (di) => {
|
||||
const binaryName = isWindows ? "lens-k8s-proxy.exe" : "lens-k8s-proxy";
|
||||
const proxyPath = isDevelopment ? path.join("client", process.platform, process.arch) : process.arch;
|
||||
const dependencies = {
|
||||
proxyBinPath: path.join(di.inject(directoryForBundledBinariesInjectable), proxyPath, binaryName),
|
||||
const binaryName = getBinaryName("lens-k8s-proxy");
|
||||
const dependencies: KubeAuthProxyDependencies = {
|
||||
proxyBinPath: path.join(di.inject(directoryForBundledBinariesInjectable), binaryName),
|
||||
};
|
||||
|
||||
return (cluster: Cluster, environmentVariables: NodeJS.ProcessEnv) =>
|
||||
new KubeAuthProxy(dependencies, cluster, environmentVariables);
|
||||
return (cluster: Cluster, environmentVariables: NodeJS.ProcessEnv) => (
|
||||
new KubeAuthProxy(dependencies, cluster, environmentVariables)
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -13,12 +13,12 @@ import { makeObservable, observable, when } from "mobx";
|
||||
|
||||
const startingServeRegex = /starting to serve on (?<address>.+)/i;
|
||||
|
||||
interface Dependencies {
|
||||
export interface KubeAuthProxyDependencies {
|
||||
proxyBinPath: string;
|
||||
}
|
||||
|
||||
export class KubeAuthProxy {
|
||||
public readonly apiPrefix = `/${randomBytes(8).toString("hex")}/`;
|
||||
public readonly apiPrefix = `/${randomBytes(8).toString("hex")}`;
|
||||
|
||||
public get port(): number {
|
||||
return this._port;
|
||||
@@ -28,7 +28,7 @@ export class KubeAuthProxy {
|
||||
protected proxyProcess?: ChildProcess;
|
||||
@observable protected ready = false;
|
||||
|
||||
constructor(private dependencies: Dependencies, protected readonly cluster: Cluster, protected readonly env: NodeJS.ProcessEnv) {
|
||||
constructor(private dependencies: KubeAuthProxyDependencies, protected readonly cluster: Cluster, protected readonly env: NodeJS.ProcessEnv) {
|
||||
makeObservable(this);
|
||||
}
|
||||
|
||||
@@ -42,8 +42,8 @@ export class KubeAuthProxy {
|
||||
}
|
||||
|
||||
const proxyBin = this.dependencies.proxyBinPath;
|
||||
|
||||
this.proxyProcess = spawn(proxyBin, [], {
|
||||
|
||||
this.proxyProcess = spawn(proxyBin, [], {
|
||||
env: {
|
||||
...this.env,
|
||||
KUBECONFIG: this.cluster.kubeConfigPath,
|
||||
|
||||
@@ -9,9 +9,8 @@ import { promiseExecFile } from "../../common/utils/promise-exec";
|
||||
import logger from "../logger";
|
||||
import { ensureDir, pathExists } from "fs-extra";
|
||||
import * as lockFile from "proper-lockfile";
|
||||
import { helmCli } from "../helm/helm-cli";
|
||||
import { getBundledKubectlVersion } from "../../common/utils/app-version";
|
||||
import { isDevelopment, isWindows, isTestEnv } from "../../common/vars";
|
||||
import { normalizedPlatform, normalizedArch, kubectlBinaryName, kubectlBinaryPath, baseBinariesDir } from "../../common/vars";
|
||||
import { SemVer } from "semver";
|
||||
import { defaultPackageMirror, packageMirrors } from "../../common/user-store/preferences-helpers";
|
||||
import got from "got/dist/source";
|
||||
@@ -39,27 +38,8 @@ const kubectlMap: Map<string, string> = new Map([
|
||||
["1.22", "1.22.6"],
|
||||
["1.23", bundledVersion],
|
||||
]);
|
||||
let bundledPath: string;
|
||||
const initScriptVersionString = "# lens-initscript v3";
|
||||
|
||||
export function bundledKubectlPath(): string {
|
||||
if (bundledPath) { return bundledPath; }
|
||||
|
||||
if (isDevelopment || isTestEnv) {
|
||||
const platformName = isWindows ? "windows" : process.platform;
|
||||
|
||||
bundledPath = path.join(process.cwd(), "binaries", "client", platformName, process.arch, "kubectl");
|
||||
} else {
|
||||
bundledPath = path.join(process.resourcesPath, process.arch, "kubectl");
|
||||
}
|
||||
|
||||
if (isWindows) {
|
||||
bundledPath = `${bundledPath}.exe`;
|
||||
}
|
||||
|
||||
return bundledPath;
|
||||
}
|
||||
|
||||
interface Dependencies {
|
||||
directoryForKubectlBinaries: string;
|
||||
|
||||
@@ -102,27 +82,13 @@ export class Kubectl {
|
||||
logger.debug(`Set kubectl version ${this.kubectlVersion} for cluster version ${clusterVersion} using fallback`);
|
||||
}
|
||||
|
||||
let arch = null;
|
||||
|
||||
if (process.arch == "x64") {
|
||||
arch = "amd64";
|
||||
} else if (process.arch == "x86" || process.arch == "ia32") {
|
||||
arch = "386";
|
||||
} else {
|
||||
arch = process.arch;
|
||||
}
|
||||
|
||||
const platformName = isWindows ? "windows" : process.platform;
|
||||
const binaryName = isWindows ? "kubectl.exe" : "kubectl";
|
||||
|
||||
this.url = `${this.getDownloadMirror()}/v${this.kubectlVersion}/bin/${platformName}/${arch}/${binaryName}`;
|
||||
|
||||
this.url = `${this.getDownloadMirror()}/v${this.kubectlVersion}/bin/${normalizedPlatform}/${normalizedArch}/${kubectlBinaryName}`;
|
||||
this.dirname = path.normalize(path.join(this.getDownloadDir(), this.kubectlVersion));
|
||||
this.path = path.join(this.dirname, binaryName);
|
||||
this.path = path.join(this.dirname, kubectlBinaryName);
|
||||
}
|
||||
|
||||
public getBundledPath() {
|
||||
return bundledKubectlPath();
|
||||
return kubectlBinaryPath.get();
|
||||
}
|
||||
|
||||
public getPathFromPreferences() {
|
||||
@@ -316,7 +282,7 @@ export class Kubectl {
|
||||
? this.dirname
|
||||
: path.dirname(this.getPathFromPreferences());
|
||||
|
||||
const helmPath = helmCli.getBinaryDir();
|
||||
const binariesDir = baseBinariesDir.get();
|
||||
|
||||
const bashScriptPath = path.join(this.dirname, ".bash_set_path");
|
||||
const bashScript = [
|
||||
@@ -330,7 +296,7 @@ export class Kubectl {
|
||||
"elif test -f \"$HOME/.profile\"; then",
|
||||
" . \"$HOME/.profile\"",
|
||||
"fi",
|
||||
`export PATH="${helmPath}:${kubectlPath}:$PATH"`,
|
||||
`export PATH="${binariesDir}:${kubectlPath}:$PATH"`,
|
||||
'export KUBECONFIG="$tempkubeconfig"',
|
||||
`NO_PROXY=",\${NO_PROXY:-localhost},"`,
|
||||
`NO_PROXY="\${NO_PROXY//,localhost,/,}"`,
|
||||
@@ -356,12 +322,12 @@ export class Kubectl {
|
||||
|
||||
// voodoo to replace any previous occurrences of kubectl path in the PATH
|
||||
`kubectlpath="${kubectlPath}"`,
|
||||
`helmpath="${helmPath}"`,
|
||||
`binariesDir="${binariesDir}"`,
|
||||
"p=\":$kubectlpath:\"",
|
||||
"d=\":$PATH:\"",
|
||||
`d=\${d//$p/:}`,
|
||||
`d=\${d/#:/}`,
|
||||
`export PATH="$helmpath:$kubectlpath:\${d/%:/}"`,
|
||||
`export PATH="$binariesDir:$kubectlpath:\${d/%:/}"`,
|
||||
"export KUBECONFIG=\"$tempkubeconfig\"",
|
||||
`NO_PROXY=",\${NO_PROXY:-localhost},"`,
|
||||
`NO_PROXY="\${NO_PROXY//,localhost,/,}"`,
|
||||
|
||||
@@ -1,202 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import path from "path";
|
||||
import fs from "fs";
|
||||
import request from "request";
|
||||
import { ensureDir, pathExists } from "fs-extra";
|
||||
import * as tar from "tar";
|
||||
import { isWindows } from "../common/vars";
|
||||
import type winston from "winston";
|
||||
|
||||
export interface LensBinaryOpts {
|
||||
version: string;
|
||||
baseDir: string;
|
||||
originalBinaryName: string;
|
||||
newBinaryName?: string;
|
||||
requestOpts?: request.Options;
|
||||
}
|
||||
|
||||
export class LensBinary {
|
||||
|
||||
public binaryVersion: string;
|
||||
protected directory: string;
|
||||
protected url: string;
|
||||
protected path: string;
|
||||
protected tarPath: string;
|
||||
protected dirname: string;
|
||||
protected binaryName: string;
|
||||
protected platformName: string;
|
||||
protected arch: string;
|
||||
protected originalBinaryName: string;
|
||||
protected requestOpts: request.Options;
|
||||
protected logger: Console | winston.Logger;
|
||||
|
||||
constructor(opts: LensBinaryOpts) {
|
||||
const baseDir = opts.baseDir;
|
||||
|
||||
this.originalBinaryName = opts.originalBinaryName;
|
||||
this.binaryName = opts.newBinaryName || opts.originalBinaryName;
|
||||
this.binaryVersion = opts.version;
|
||||
this.requestOpts = opts.requestOpts;
|
||||
this.logger = console;
|
||||
let arch = null;
|
||||
|
||||
if (process.env.BINARY_ARCH) {
|
||||
arch = process.env.BINARY_ARCH;
|
||||
} else if (process.arch == "x64") {
|
||||
arch = "amd64";
|
||||
} else if (process.arch == "x86" || process.arch == "ia32") {
|
||||
arch = "386";
|
||||
} else {
|
||||
arch = process.arch;
|
||||
}
|
||||
this.arch = arch;
|
||||
this.platformName = isWindows ? "windows" : process.platform;
|
||||
this.dirname = path.normalize(path.join(baseDir, this.binaryName));
|
||||
|
||||
if (isWindows) {
|
||||
this.binaryName = `${this.binaryName}.exe`;
|
||||
this.originalBinaryName = `${this.originalBinaryName}.exe`;
|
||||
}
|
||||
const tarName = this.getTarName();
|
||||
|
||||
if (tarName) {
|
||||
this.tarPath = path.join(this.dirname, tarName);
|
||||
}
|
||||
}
|
||||
|
||||
public setLogger(logger: Console | winston.Logger) {
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
protected binaryDir() {
|
||||
throw new Error("binaryDir not implemented");
|
||||
}
|
||||
|
||||
public async binaryPath() {
|
||||
await this.ensureBinary();
|
||||
|
||||
return this.getBinaryPath();
|
||||
}
|
||||
|
||||
protected getTarName(): string | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
protected getUrl() {
|
||||
return "";
|
||||
}
|
||||
|
||||
protected getBinaryPath() {
|
||||
return "";
|
||||
}
|
||||
|
||||
protected getOriginalBinaryPath() {
|
||||
return "";
|
||||
}
|
||||
|
||||
public getBinaryDir() {
|
||||
return path.dirname(this.getBinaryPath());
|
||||
}
|
||||
|
||||
public async binDir() {
|
||||
try {
|
||||
await this.ensureBinary();
|
||||
|
||||
return this.dirname;
|
||||
} catch (err) {
|
||||
this.logger.error(err);
|
||||
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
protected async checkBinary() {
|
||||
const exists = await pathExists(this.getBinaryPath());
|
||||
|
||||
return exists;
|
||||
}
|
||||
|
||||
public async ensureBinary() {
|
||||
const isValid = await this.checkBinary();
|
||||
|
||||
if (!isValid) {
|
||||
await this.downloadBinary().catch((error) => {
|
||||
this.logger.error(error);
|
||||
});
|
||||
if (this.tarPath) await this.untarBinary();
|
||||
if (this.originalBinaryName != this.binaryName) await this.renameBinary();
|
||||
this.logger.info(`${this.originalBinaryName} has been downloaded to ${this.getBinaryPath()}`);
|
||||
}
|
||||
}
|
||||
|
||||
protected async untarBinary() {
|
||||
return new Promise<void>(resolve => {
|
||||
this.logger.debug(`Extracting ${this.originalBinaryName} binary`);
|
||||
tar.x({
|
||||
file: this.tarPath,
|
||||
cwd: this.dirname,
|
||||
}).then((() => {
|
||||
resolve();
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
protected async renameBinary() {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
this.logger.debug(`Renaming ${this.originalBinaryName} binary to ${this.binaryName}`);
|
||||
fs.rename(this.getOriginalBinaryPath(), this.getBinaryPath(), (err) => {
|
||||
if (err) {
|
||||
reject(err);
|
||||
}
|
||||
else {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
protected async downloadBinary() {
|
||||
const binaryPath = this.tarPath || this.getBinaryPath();
|
||||
|
||||
await ensureDir(this.getBinaryDir(), 0o755);
|
||||
|
||||
const file = fs.createWriteStream(binaryPath);
|
||||
const url = this.getUrl();
|
||||
|
||||
this.logger.info(`Downloading ${this.originalBinaryName} ${this.binaryVersion} from ${url} to ${binaryPath}`);
|
||||
const requestOpts: request.UriOptions & request.CoreOptions = {
|
||||
uri: url,
|
||||
gzip: true,
|
||||
...this.requestOpts,
|
||||
};
|
||||
const stream = request(requestOpts);
|
||||
|
||||
stream.on("complete", () => {
|
||||
this.logger.info(`Download of ${this.originalBinaryName} finished`);
|
||||
file.end();
|
||||
});
|
||||
|
||||
stream.on("error", (error) => {
|
||||
this.logger.error(error);
|
||||
fs.unlink(binaryPath, () => {
|
||||
// do nothing
|
||||
});
|
||||
throw(error);
|
||||
});
|
||||
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
file.on("close", () => {
|
||||
this.logger.debug(`${this.originalBinaryName} binary download closed`);
|
||||
if (!this.tarPath) fs.chmod(binaryPath, 0o755, (err) => {
|
||||
if (err) reject(err);
|
||||
});
|
||||
resolve();
|
||||
});
|
||||
stream.pipe(file);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@
|
||||
import type net from "net";
|
||||
import type http from "http";
|
||||
import spdy from "spdy";
|
||||
import httpProxy from "http-proxy";
|
||||
import type httpProxy from "http-proxy";
|
||||
import { apiPrefix, apiKubePrefix } from "../common/vars";
|
||||
import type { Router } from "./router";
|
||||
import type { ContextHandler } from "./context-handler/context-handler";
|
||||
@@ -57,14 +57,15 @@ export class LensProxy extends Singleton {
|
||||
protected proxyServer: http.Server;
|
||||
protected closed = false;
|
||||
protected retryCounters = new Map<string, number>();
|
||||
protected proxy = this.createProxy();
|
||||
protected getClusterForRequest: GetClusterForRequest;
|
||||
|
||||
public port: number;
|
||||
|
||||
constructor(protected router: Router, { shellApiRequest, kubeApiRequest, getClusterForRequest }: LensProxyFunctions) {
|
||||
constructor(protected router: Router, protected proxy: httpProxy, { shellApiRequest, kubeApiRequest, getClusterForRequest }: LensProxyFunctions) {
|
||||
super();
|
||||
|
||||
this.configureProxy(proxy);
|
||||
|
||||
this.getClusterForRequest = getClusterForRequest;
|
||||
|
||||
this.proxyServer = spdy.createServer({
|
||||
@@ -82,7 +83,9 @@ export class LensProxy extends Singleton {
|
||||
const cluster = getClusterForRequest(req);
|
||||
|
||||
if (!cluster) {
|
||||
return void logger.error(`[LENS-PROXY]: Could not find cluster for upgrade request from url=${req.url}`);
|
||||
logger.error(`[LENS-PROXY]: Could not find cluster for upgrade request from url=${req.url}`);
|
||||
|
||||
return socket.destroy();
|
||||
}
|
||||
|
||||
const reqHandler = isInternal ? shellApiRequest : kubeApiRequest;
|
||||
@@ -163,9 +166,7 @@ export class LensProxy extends Singleton {
|
||||
this.closed = true;
|
||||
}
|
||||
|
||||
protected createProxy(): httpProxy {
|
||||
const proxy = httpProxy.createProxyServer();
|
||||
|
||||
protected configureProxy(proxy: httpProxy): httpProxy {
|
||||
proxy.on("proxyRes", (proxyRes, req, res) => {
|
||||
const retryCounterId = this.getRequestId(req);
|
||||
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import { nativeTheme } from "electron";
|
||||
import { broadcastMessage } from "../common/ipc";
|
||||
import { setNativeThemeChannel } from "../common/ipc/native-theme";
|
||||
|
||||
export function broadcastNativeThemeOnUpdate() {
|
||||
nativeTheme.on("updated", () => {
|
||||
broadcastMessage(setNativeThemeChannel, getNativeColorTheme());
|
||||
});
|
||||
}
|
||||
|
||||
export function getNativeColorTheme() {
|
||||
return nativeTheme.shouldUseDarkColors ? "dark" : "light";
|
||||
}
|
||||
+20
-3
@@ -6,6 +6,7 @@
|
||||
import Call from "@hapi/call";
|
||||
import Subtext from "@hapi/subtext";
|
||||
import type http from "http";
|
||||
import type httpProxy from "http-proxy";
|
||||
import path from "path";
|
||||
import { readFile } from "fs-extra";
|
||||
import type { Cluster } from "../common/cluster/cluster";
|
||||
@@ -40,6 +41,7 @@ export interface LensApiRequest<P = any> {
|
||||
query: URLSearchParams;
|
||||
raw: {
|
||||
req: http.IncomingMessage;
|
||||
res: http.ServerResponse;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -62,6 +64,7 @@ function getMimeType(filename: string) {
|
||||
|
||||
interface Dependencies {
|
||||
routePortForward: (request: LensApiRequest) => Promise<void>;
|
||||
httpProxy?: httpProxy;
|
||||
}
|
||||
|
||||
export class Router {
|
||||
@@ -101,7 +104,7 @@ export class Router {
|
||||
cluster,
|
||||
path: url.pathname,
|
||||
raw: {
|
||||
req,
|
||||
req, res,
|
||||
},
|
||||
response: res,
|
||||
query: url.searchParams,
|
||||
@@ -140,12 +143,26 @@ export class Router {
|
||||
filePath = `${publicPath}/${appName}.html`;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
protected addRoutes() {
|
||||
// Static assets
|
||||
this.router.add({ method: "get", path: "/{path*}" }, Router.handleStaticFile);
|
||||
if (this.dependencies.httpProxy) {
|
||||
this.router.add({ method: "get", path: "/{path*}" }, (apiReq: LensApiRequest) => {
|
||||
const { req, res } = apiReq.raw;
|
||||
|
||||
if (req.url === "/" || !req.url.startsWith("/build/")) {
|
||||
req.url = `${publicPath}/${appName}.html`;
|
||||
}
|
||||
|
||||
this.dependencies.httpProxy.web(req, res, {
|
||||
target: "http://127.0.0.1:8080",
|
||||
});
|
||||
});
|
||||
} else {
|
||||
this.router.add({ method: "get", path: "/{path*}" }, Router.handleStaticFile);
|
||||
}
|
||||
|
||||
|
||||
this.router.add({ method: "get", path: "/version" }, VersionRoute.getVersion);
|
||||
this.router.add({ method: "get", path: `${apiPrefix}/kubeconfig/service-account/{namespace}/{account}` }, KubeconfigRoute.routeServiceAccountRoute);
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
import { getInjectable } from "@ogre-tools/injectable";
|
||||
import isDevelopmentInjectable from "../../common/vars/is-development.injectable";
|
||||
import httpProxy from "http-proxy";
|
||||
import { Router } from "../router";
|
||||
import routePortForwardInjectable
|
||||
from "../routes/port-forward/route-port-forward/route-port-forward.injectable";
|
||||
@@ -10,9 +12,15 @@ import routePortForwardInjectable
|
||||
const routerInjectable = getInjectable({
|
||||
id: "router",
|
||||
|
||||
instantiate: (di) => new Router({
|
||||
routePortForward: di.inject(routePortForwardInjectable),
|
||||
}),
|
||||
instantiate: (di) => {
|
||||
const isDevelopment = di.inject(isDevelopmentInjectable);
|
||||
const proxy = isDevelopment ? httpProxy.createProxy() : undefined;
|
||||
|
||||
return new Router({
|
||||
routePortForward: di.inject(routePortForwardInjectable),
|
||||
httpProxy: proxy,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
export default routerInjectable;
|
||||
@@ -5,12 +5,12 @@
|
||||
|
||||
import type WebSocket from "ws";
|
||||
import path from "path";
|
||||
import { helmCli } from "../../helm/helm-cli";
|
||||
import { UserStore } from "../../../common/user-store";
|
||||
import type { Cluster } from "../../../common/cluster/cluster";
|
||||
import type { ClusterId } from "../../../common/cluster-types";
|
||||
import { ShellSession } from "../shell-session";
|
||||
import type { Kubectl } from "../../kubectl/kubectl";
|
||||
import { baseBinariesDir } from "../../../common/vars";
|
||||
|
||||
export class LocalShellSession extends ShellSession {
|
||||
ShellType = "shell";
|
||||
@@ -18,9 +18,9 @@ export class LocalShellSession extends ShellSession {
|
||||
constructor(protected shellEnvModify: (clusterId: ClusterId, env: Record<string, string>) => Record<string, string>, kubectl: Kubectl, websocket: WebSocket, cluster: Cluster, terminalId: string) {
|
||||
super(kubectl, websocket, cluster, terminalId);
|
||||
}
|
||||
|
||||
|
||||
protected getPathEntries(): string[] {
|
||||
return [helmCli.getBinaryDir()];
|
||||
return [baseBinariesDir.get()];
|
||||
}
|
||||
|
||||
protected get cwd(): string | undefined {
|
||||
@@ -40,17 +40,16 @@ export class LocalShellSession extends ShellSession {
|
||||
}
|
||||
|
||||
protected async getShellArgs(shell: string): Promise<string[]> {
|
||||
const helmpath = helmCli.getBinaryDir();
|
||||
const pathFromPreferences = UserStore.getInstance().kubectlBinariesPath || this.kubectl.getBundledPath();
|
||||
const kubectlPathDir = UserStore.getInstance().downloadKubectlBinaries ? await this.kubectlBinDirP : path.dirname(pathFromPreferences);
|
||||
|
||||
switch(path.basename(shell)) {
|
||||
case "powershell.exe":
|
||||
return ["-NoExit", "-command", `& {$Env:PATH="${helmpath};${kubectlPathDir};$Env:PATH"}`];
|
||||
return ["-NoExit", "-command", `& {$Env:PATH="${baseBinariesDir.get()};${kubectlPathDir};$Env:PATH"}`];
|
||||
case "bash":
|
||||
return ["--init-file", path.join(await this.kubectlBinDirP, ".bash_set_path")];
|
||||
case "fish":
|
||||
return ["--login", "--init-command", `export PATH="${helmpath}:${kubectlPathDir}:$PATH"; export KUBECONFIG="${await this.kubeconfigPathP}"`];
|
||||
return ["--login", "--init-command", `export PATH="${baseBinariesDir.get()}:${kubectlPathDir}:$PATH"; export KUBECONFIG="${await this.kubeconfigPathP}"`];
|
||||
case "zsh":
|
||||
return ["--login"];
|
||||
default:
|
||||
|
||||
@@ -76,9 +76,6 @@ export async function bootstrap(di: DiContainer) {
|
||||
logger.info(`${logPrefix} initializing KubeObjectDetailRegistry`);
|
||||
initializers.initKubeObjectDetailRegistry();
|
||||
|
||||
logger.info(`${logPrefix} initializing WorkloadsOverviewDetailRegistry`);
|
||||
initializers.initWorkloadsOverviewDetailRegistry();
|
||||
|
||||
logger.info(`${logPrefix} initializing CatalogEntityDetailRegistry`);
|
||||
initializers.initCatalogEntityDetailRegistry();
|
||||
|
||||
|
||||
@@ -41,6 +41,10 @@ jest.mock("electron", () => ({
|
||||
on: jest.fn(),
|
||||
handle: jest.fn(),
|
||||
},
|
||||
ipcRenderer: {
|
||||
on: jest.fn(),
|
||||
invoke: jest.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
jest.mock("./hotbar-toggle-menu-item", () => ({
|
||||
|
||||
@@ -45,7 +45,10 @@ const NonInjectedApplication: React.FC<Dependencies> = ({ appPreferenceItems })
|
||||
<section id="appearance">
|
||||
<SubTitle title="Theme" />
|
||||
<Select
|
||||
options={themeStore.themeOptions}
|
||||
options={[
|
||||
{ label: "Sync with computer", value: "system" },
|
||||
...themeStore.themeOptions,
|
||||
]}
|
||||
value={userStore.colorTheme}
|
||||
onChange={({ value }) => userStore.colorTheme = value}
|
||||
themeName="lens"
|
||||
|
||||
@@ -8,13 +8,12 @@ import { observer } from "mobx-react";
|
||||
import { Input, InputValidators } from "../input";
|
||||
import { SubTitle } from "../layout/sub-title";
|
||||
import { UserStore } from "../../../common/user-store";
|
||||
import { bundledKubectlPath } from "../../../main/kubectl/kubectl";
|
||||
import { SelectOption, Select } from "../select";
|
||||
import { Switch } from "../switch";
|
||||
import { packageMirrors } from "../../../common/user-store/preferences-helpers";
|
||||
import directoryForBinariesInjectable
|
||||
from "../../../common/app-paths/directory-for-binaries/directory-for-binaries.injectable";
|
||||
import directoryForBinariesInjectable from "../../../common/app-paths/directory-for-binaries/directory-for-binaries.injectable";
|
||||
import { withInjectables } from "@ogre-tools/injectable-react";
|
||||
import { kubectlBinaryPath } from "../../../common/vars";
|
||||
|
||||
interface Dependencies {
|
||||
defaultPathForKubectlBinaries: string;
|
||||
@@ -80,7 +79,7 @@ const NonInjectedKubectlBinaries: React.FC<Dependencies> = observer(({ defaultPa
|
||||
<SubTitle title="Path to kubectl binary" />
|
||||
<Input
|
||||
theme="round-black"
|
||||
placeholder={bundledKubectlPath()}
|
||||
placeholder={kubectlBinaryPath.get()}
|
||||
value={binariesPath}
|
||||
validators={pathValidator}
|
||||
onChange={setBinariesPath}
|
||||
|
||||
@@ -15,7 +15,6 @@ import { Notifications } from "../notifications";
|
||||
import { cssNames } from "../../utils";
|
||||
import { Input } from "../input";
|
||||
import { systemName, maxLength } from "../input/input_validators";
|
||||
import type { KubeObjectMetadata } from "../../../common/k8s-api/kube-object";
|
||||
|
||||
export interface CronJobTriggerDialogProps extends Partial<DialogProps> {
|
||||
}
|
||||
@@ -80,6 +79,7 @@ export class CronJobTriggerDialog extends Component<CronJobTriggerDialogProps> {
|
||||
}, {
|
||||
spec: cronjobDefinition.spec.jobTemplate.spec,
|
||||
metadata: {
|
||||
annotations: { "cronjob.kubernetes.io/instantiate": "manual" },
|
||||
ownerReferences: [{
|
||||
apiVersion: cronjob.apiVersion,
|
||||
blockOwnerDeletion: true,
|
||||
@@ -88,7 +88,7 @@ export class CronJobTriggerDialog extends Component<CronJobTriggerDialogProps> {
|
||||
name: cronjob.metadata.name,
|
||||
uid: cronjob.metadata.uid,
|
||||
}],
|
||||
} as KubeObjectMetadata,
|
||||
},
|
||||
});
|
||||
|
||||
close();
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
import { getInjectable, lifecycleEnum } from "@ogre-tools/injectable";
|
||||
import { computed } from "mobx";
|
||||
import rendererExtensionsInjectable from "../../../extensions/renderer-extensions.injectable";
|
||||
import { OverviewStatuses } from "./overview-statuses";
|
||||
import { WorkloadEvents } from "../../initializers/workload-events";
|
||||
import { orderBy } from "lodash/fp";
|
||||
import type { WorkloadsOverviewDetailRegistration } from "./workloads-overview-detail-registration";
|
||||
|
||||
const detailComponentsInjectable = getInjectable({
|
||||
id: "workload-detail-components",
|
||||
|
||||
instantiate: (di) => {
|
||||
const extensions = di.inject(rendererExtensionsInjectable);
|
||||
|
||||
return computed(() => {
|
||||
const extensionRegistrations = extensions
|
||||
.get()
|
||||
.flatMap((extension) => extension.kubeWorkloadsOverviewItems);
|
||||
|
||||
const allRegistrations = [
|
||||
...coreRegistrations,
|
||||
...extensionRegistrations,
|
||||
];
|
||||
|
||||
return getRegistrationsInPriorityOrder(allRegistrations).map(
|
||||
(item) => item.components.Details,
|
||||
);
|
||||
});
|
||||
},
|
||||
|
||||
lifecycle: lifecycleEnum.singleton,
|
||||
});
|
||||
|
||||
const coreRegistrations = [
|
||||
{
|
||||
components: {
|
||||
Details: OverviewStatuses,
|
||||
},
|
||||
},
|
||||
{
|
||||
priority: 5,
|
||||
components: {
|
||||
Details: WorkloadEvents,
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const toRegistrationWithDefaultPriority = ({
|
||||
priority = 50,
|
||||
...rest
|
||||
}: WorkloadsOverviewDetailRegistration) => ({
|
||||
priority,
|
||||
...rest,
|
||||
});
|
||||
|
||||
const getRegistrationsInPriorityOrder = (
|
||||
allRegistrations: WorkloadsOverviewDetailRegistration[],
|
||||
) =>
|
||||
orderBy(
|
||||
"priority",
|
||||
"desc",
|
||||
|
||||
allRegistrations.map(toRegistrationWithDefaultPriority),
|
||||
);
|
||||
|
||||
export default detailComponentsInjectable;
|
||||
@@ -16,9 +16,8 @@ import { statefulSetStore } from "../+workloads-statefulsets/statefulset.store";
|
||||
import { replicaSetStore } from "../+workloads-replicasets/replicasets.store";
|
||||
import { jobStore } from "../+workloads-jobs/job.store";
|
||||
import { cronJobStore } from "../+workloads-cronjobs/cronjob.store";
|
||||
import { WorkloadsOverviewDetailRegistry } from "../../../extensions/registries";
|
||||
import type { WorkloadsOverviewRouteParams } from "../../../common/routes";
|
||||
import { makeObservable, observable, reaction } from "mobx";
|
||||
import { IComputedValue, makeObservable, observable, reaction } from "mobx";
|
||||
import { NamespaceSelectFilter } from "../+namespaces/namespace-select-filter";
|
||||
import { Icon } from "../icon";
|
||||
import { TooltipPosition } from "../tooltip";
|
||||
@@ -30,11 +29,13 @@ import type { KubeObject } from "../../../common/k8s-api/kube-object";
|
||||
import type { Disposer } from "../../../common/utils";
|
||||
import kubeWatchApiInjectable from "../../kube-watch-api/kube-watch-api.injectable";
|
||||
import type { KubeWatchSubscribeStoreOptions } from "../../kube-watch-api/kube-watch-api";
|
||||
import detailComponentsInjectable from "./detail-components.injectable";
|
||||
|
||||
export interface WorkloadsOverviewProps extends RouteComponentProps<WorkloadsOverviewRouteParams> {
|
||||
}
|
||||
|
||||
interface Dependencies {
|
||||
detailComponents: IComputedValue<React.ComponentType<{}>[]>;
|
||||
clusterFrameContext: ClusterFrameContext;
|
||||
subscribeStores: (stores: KubeObjectStore<KubeObject>[], options: KubeWatchSubscribeStoreOptions) => Disposer;
|
||||
}
|
||||
@@ -91,13 +92,6 @@ class NonInjectedWorkloadsOverview extends React.Component<WorkloadsOverviewProp
|
||||
}
|
||||
|
||||
render() {
|
||||
const items = WorkloadsOverviewDetailRegistry
|
||||
.getInstance()
|
||||
.getItems()
|
||||
.map(({ components: { Details }}, index) => (
|
||||
<Details key={`workload-overview-${index}`}/>
|
||||
));
|
||||
|
||||
return (
|
||||
<div className="WorkloadsOverview flex column gaps">
|
||||
<div className="header flex gaps align-center">
|
||||
@@ -105,7 +99,10 @@ class NonInjectedWorkloadsOverview extends React.Component<WorkloadsOverviewProp
|
||||
{this.renderLoadErrors()}
|
||||
<NamespaceSelectFilter />
|
||||
</div>
|
||||
{items}
|
||||
|
||||
{this.props.detailComponents.get().map((Details, index) => (
|
||||
<Details key={`workload-overview-${index}`} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -116,6 +113,7 @@ export const WorkloadsOverview = withInjectables<Dependencies, WorkloadsOverview
|
||||
|
||||
{
|
||||
getProps: (di, props) => ({
|
||||
detailComponents: di.inject(detailComponentsInjectable),
|
||||
clusterFrameContext: di.inject(clusterFrameContextInjectable),
|
||||
subscribeStores: di.inject(kubeWatchApiInjectable).subscribeStores,
|
||||
...props,
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
interface WorkloadsOverviewDetailComponents {
|
||||
Details: React.ComponentType<{}>;
|
||||
}
|
||||
|
||||
export interface WorkloadsOverviewDetailRegistration {
|
||||
components: WorkloadsOverviewDetailComponents;
|
||||
priority?: number;
|
||||
}
|
||||
@@ -33,6 +33,10 @@ jest.mock("electron", () => ({
|
||||
on: jest.fn(),
|
||||
handle: jest.fn(),
|
||||
},
|
||||
ipcRenderer: {
|
||||
on: jest.fn(),
|
||||
invoke: jest.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
const initialTabs: DockTab[] = [
|
||||
|
||||
@@ -36,6 +36,10 @@ jest.mock("electron", () => ({
|
||||
on: jest.fn(),
|
||||
handle: jest.fn(),
|
||||
},
|
||||
ipcRenderer: {
|
||||
on: jest.fn(),
|
||||
invoke: jest.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
function mockLogTabViewModel(tabId: TabId, deps: Partial<LogTabViewModelDependencies>): LogTabViewModel {
|
||||
|
||||
@@ -58,7 +58,7 @@ const NonInjectedLogControls = observer(({ openSaveFileDialog, model }: Dependen
|
||||
{since && (
|
||||
<span>
|
||||
Logs from{" "}
|
||||
<b>{new Date(since[0]).toLocaleString()}</b>
|
||||
<b>{new Date(since).toLocaleString()}</b>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -39,7 +39,7 @@ const NonInjectedLogsDockTab = observer(({ className, tab, model, subscribeStore
|
||||
model.reloadLogs();
|
||||
|
||||
return model.stopLoadingLogs;
|
||||
}, []);
|
||||
}, [tab.id]);
|
||||
useEffect(() => subscribeStores([
|
||||
podsStore,
|
||||
], {
|
||||
|
||||
@@ -26,6 +26,13 @@ const mockHotbars: { [id: string]: any } = {
|
||||
},
|
||||
};
|
||||
|
||||
jest.mock("electron", () => ({
|
||||
ipcRenderer: {
|
||||
on: jest.fn(),
|
||||
invoke: jest.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
describe("<HotbarRemoveCommand />", () => {
|
||||
let di: DiContainer;
|
||||
let render: DiRender;
|
||||
|
||||
@@ -68,67 +68,76 @@ export class ItemListLayoutContent<I extends ItemObject> extends React.Component
|
||||
return this.props.store.failedLoading;
|
||||
}
|
||||
|
||||
@boundMethod
|
||||
renderRow(item: I) {
|
||||
return this.getTableRow(item);
|
||||
}
|
||||
|
||||
getTableRow(item: I) {
|
||||
const {
|
||||
isSelectable, renderTableHeader, renderTableContents, renderItemMenu,
|
||||
store, hasDetailsView, onDetails,
|
||||
copyClassNameFromHeadCells, customizeTableRowProps, detailsItem,
|
||||
} = this.props;
|
||||
const { isSelected } = store;
|
||||
|
||||
return (
|
||||
<TableRow
|
||||
nowrap
|
||||
searchItem={item}
|
||||
sortItem={item}
|
||||
selected={detailsItem && detailsItem.getId() === item.getId()}
|
||||
onClick={hasDetailsView ? prevDefault(() => onDetails(item)) : undefined}
|
||||
{...customizeTableRowProps(item)}
|
||||
>
|
||||
{isSelectable && (
|
||||
<TableCell
|
||||
checkbox
|
||||
isChecked={isSelected(item)}
|
||||
onClick={prevDefault(() => store.toggleSelection(item))}
|
||||
/>
|
||||
)}
|
||||
{renderTableContents(item).map((content, index) => {
|
||||
const cellProps: TableCellProps = isReactNode(content)
|
||||
? { children: content }
|
||||
: content;
|
||||
const headCell = renderTableHeader?.[index];
|
||||
|
||||
if (copyClassNameFromHeadCells && headCell) {
|
||||
cellProps.className = cssNames(
|
||||
cellProps.className,
|
||||
headCell.className,
|
||||
);
|
||||
}
|
||||
|
||||
if (!headCell || this.showColumn(headCell)) {
|
||||
return <TableCell key={index} {...cellProps} />;
|
||||
}
|
||||
|
||||
return null;
|
||||
})}
|
||||
{renderItemMenu && (
|
||||
<TableCell className="menu">
|
||||
<div onClick={stopPropagation}>
|
||||
{renderItemMenu(item, store)}
|
||||
</div>
|
||||
</TableCell>
|
||||
)}
|
||||
</TableRow>
|
||||
);
|
||||
}
|
||||
|
||||
@boundMethod
|
||||
getRow(uid: string) {
|
||||
return (
|
||||
<div key={uid}>
|
||||
<Observer>
|
||||
{() => {
|
||||
const {
|
||||
isSelectable, renderTableHeader, renderTableContents, renderItemMenu,
|
||||
store, hasDetailsView, onDetails,
|
||||
copyClassNameFromHeadCells, customizeTableRowProps, detailsItem,
|
||||
} = this.props;
|
||||
const { isSelected } = store;
|
||||
const item = this.props.getItems().find(item => item.getId() == uid);
|
||||
const item = this.props.getItems().find(item => item.getId() === uid);
|
||||
|
||||
if (!item) return null;
|
||||
const itemId = item.getId();
|
||||
|
||||
return (
|
||||
<TableRow
|
||||
nowrap
|
||||
searchItem={item}
|
||||
sortItem={item}
|
||||
selected={detailsItem && detailsItem.getId() === itemId}
|
||||
onClick={hasDetailsView ? prevDefault(() => onDetails(item)) : undefined}
|
||||
{...customizeTableRowProps(item)}
|
||||
>
|
||||
{isSelectable && (
|
||||
<TableCell
|
||||
checkbox
|
||||
isChecked={isSelected(item)}
|
||||
onClick={prevDefault(() => store.toggleSelection(item))}
|
||||
/>
|
||||
)}
|
||||
{renderTableContents(item).map((content, index) => {
|
||||
const cellProps: TableCellProps = isReactNode(content)
|
||||
? { children: content }
|
||||
: content;
|
||||
const headCell = renderTableHeader?.[index];
|
||||
|
||||
if (copyClassNameFromHeadCells && headCell) {
|
||||
cellProps.className = cssNames(
|
||||
cellProps.className,
|
||||
headCell.className,
|
||||
);
|
||||
}
|
||||
|
||||
if (!headCell || this.showColumn(headCell)) {
|
||||
return <TableCell key={index} {...cellProps} />;
|
||||
}
|
||||
|
||||
return null;
|
||||
})}
|
||||
{renderItemMenu && (
|
||||
<TableCell className="menu">
|
||||
<div onClick={stopPropagation}>
|
||||
{renderItemMenu(item, store)}
|
||||
</div>
|
||||
</TableCell>
|
||||
)}
|
||||
</TableRow>
|
||||
);
|
||||
return this.getTableRow(item);
|
||||
}}
|
||||
</Observer>
|
||||
</div>
|
||||
@@ -248,6 +257,7 @@ export class ItemListLayoutContent<I extends ItemObject> extends React.Component
|
||||
selectable={hasDetailsView}
|
||||
sortable={sortingCallbacks}
|
||||
getTableRow={this.getRow}
|
||||
renderRow={virtual ? undefined : this.renderRow}
|
||||
items={items}
|
||||
selectedItemId={selectedItemId}
|
||||
noItems={this.renderNoItems()}
|
||||
|
||||
+332
@@ -0,0 +1,332 @@
|
||||
// Jest Snapshot v1, https://goo.gl/fbAQLP
|
||||
|
||||
exports[`kube-object-status-icon given info and warning statuses are present, when rendered, renders with statuses 1`] = `
|
||||
<body>
|
||||
<div>
|
||||
<i
|
||||
class="Icon KubeObjectStatusIcon warning material focusable"
|
||||
id="tooltip_target_5"
|
||||
>
|
||||
<span
|
||||
class="icon"
|
||||
data-icon-name="warning"
|
||||
>
|
||||
warning
|
||||
</span>
|
||||
<div />
|
||||
</i>
|
||||
</div>
|
||||
<div
|
||||
class="Tooltip narrow formatter"
|
||||
>
|
||||
<div
|
||||
class="KubeObjectStatusTooltip"
|
||||
>
|
||||
<div
|
||||
class="level warning"
|
||||
>
|
||||
<span
|
||||
class="title"
|
||||
>
|
||||
Warning
|
||||
</span>
|
||||
<div
|
||||
class="status msg"
|
||||
>
|
||||
-
|
||||
Some warning status for some-name
|
||||
|
||||
<span
|
||||
class="age"
|
||||
>
|
||||
·
|
||||
2d
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
class="level info"
|
||||
>
|
||||
<span
|
||||
class="title"
|
||||
>
|
||||
Info
|
||||
</span>
|
||||
<div
|
||||
class="status msg"
|
||||
>
|
||||
-
|
||||
Some info status for some-name
|
||||
|
||||
<span
|
||||
class="age"
|
||||
>
|
||||
·
|
||||
2d
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
`;
|
||||
|
||||
exports[`kube-object-status-icon given level "critical" status, when rendered, renders with status 1`] = `
|
||||
<body>
|
||||
<div>
|
||||
<i
|
||||
class="Icon KubeObjectStatusIcon error material focusable"
|
||||
id="tooltip_target_1"
|
||||
>
|
||||
<span
|
||||
class="icon"
|
||||
data-icon-name="error"
|
||||
>
|
||||
error
|
||||
</span>
|
||||
<div />
|
||||
</i>
|
||||
</div>
|
||||
<div
|
||||
class="Tooltip narrow formatter"
|
||||
>
|
||||
<div
|
||||
class="KubeObjectStatusTooltip"
|
||||
>
|
||||
<div
|
||||
class="level error"
|
||||
>
|
||||
<span
|
||||
class="title"
|
||||
>
|
||||
Critical
|
||||
</span>
|
||||
<div
|
||||
class="status msg"
|
||||
>
|
||||
-
|
||||
Some critical status for some-name
|
||||
|
||||
<span
|
||||
class="age"
|
||||
>
|
||||
·
|
||||
2d
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
`;
|
||||
|
||||
exports[`kube-object-status-icon given level "info" status, when rendered, renders with status 1`] = `
|
||||
<body>
|
||||
<div>
|
||||
<i
|
||||
class="Icon KubeObjectStatusIcon info material focusable"
|
||||
id="tooltip_target_2"
|
||||
>
|
||||
<span
|
||||
class="icon"
|
||||
data-icon-name="info"
|
||||
>
|
||||
info
|
||||
</span>
|
||||
<div />
|
||||
</i>
|
||||
</div>
|
||||
<div
|
||||
class="Tooltip narrow formatter"
|
||||
>
|
||||
<div
|
||||
class="KubeObjectStatusTooltip"
|
||||
>
|
||||
<div
|
||||
class="level info"
|
||||
>
|
||||
<span
|
||||
class="title"
|
||||
>
|
||||
Info
|
||||
</span>
|
||||
<div
|
||||
class="status msg"
|
||||
>
|
||||
-
|
||||
Some info status for some-name
|
||||
|
||||
<span
|
||||
class="age"
|
||||
>
|
||||
·
|
||||
2d
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
`;
|
||||
|
||||
exports[`kube-object-status-icon given level "warning" status, when rendered, renders with status 1`] = `
|
||||
<body>
|
||||
<div>
|
||||
<i
|
||||
class="Icon KubeObjectStatusIcon warning material focusable"
|
||||
id="tooltip_target_3"
|
||||
>
|
||||
<span
|
||||
class="icon"
|
||||
data-icon-name="warning"
|
||||
>
|
||||
warning
|
||||
</span>
|
||||
<div />
|
||||
</i>
|
||||
</div>
|
||||
<div
|
||||
class="Tooltip narrow formatter"
|
||||
>
|
||||
<div
|
||||
class="KubeObjectStatusTooltip"
|
||||
>
|
||||
<div
|
||||
class="level warning"
|
||||
>
|
||||
<span
|
||||
class="title"
|
||||
>
|
||||
Warning
|
||||
</span>
|
||||
<div
|
||||
class="status msg"
|
||||
>
|
||||
-
|
||||
Some warning status for some-name
|
||||
|
||||
<span
|
||||
class="age"
|
||||
>
|
||||
·
|
||||
2d
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
`;
|
||||
|
||||
exports[`kube-object-status-icon given no statuses, when rendered, renders as empty 1`] = `<div />`;
|
||||
|
||||
exports[`kube-object-status-icon given registration for wrong api version, when rendered, renders as empty 1`] = `
|
||||
<body>
|
||||
<div />
|
||||
</body>
|
||||
`;
|
||||
|
||||
exports[`kube-object-status-icon given registration for wrong kind, when rendered, renders as empty 1`] = `
|
||||
<body>
|
||||
<div />
|
||||
</body>
|
||||
`;
|
||||
|
||||
exports[`kube-object-status-icon given registration without status for exact kube object, when rendered, renders as empty 1`] = `
|
||||
<body>
|
||||
<div />
|
||||
</body>
|
||||
`;
|
||||
|
||||
exports[`kube-object-status-icon given status for all levels is present, when rendered, renders with statuses 1`] = `
|
||||
<body>
|
||||
<div>
|
||||
<i
|
||||
class="Icon KubeObjectStatusIcon error material focusable"
|
||||
id="tooltip_target_4"
|
||||
>
|
||||
<span
|
||||
class="icon"
|
||||
data-icon-name="error"
|
||||
>
|
||||
error
|
||||
</span>
|
||||
<div />
|
||||
</i>
|
||||
</div>
|
||||
<div
|
||||
class="Tooltip narrow formatter"
|
||||
>
|
||||
<div
|
||||
class="KubeObjectStatusTooltip"
|
||||
>
|
||||
<div
|
||||
class="level error"
|
||||
>
|
||||
<span
|
||||
class="title"
|
||||
>
|
||||
Critical
|
||||
</span>
|
||||
<div
|
||||
class="status msg"
|
||||
>
|
||||
-
|
||||
Some critical status for some-name
|
||||
|
||||
<span
|
||||
class="age"
|
||||
>
|
||||
·
|
||||
2d
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
class="level warning"
|
||||
>
|
||||
<span
|
||||
class="title"
|
||||
>
|
||||
Warning
|
||||
</span>
|
||||
<div
|
||||
class="status msg"
|
||||
>
|
||||
-
|
||||
Some warning status for some-name
|
||||
|
||||
<span
|
||||
class="age"
|
||||
>
|
||||
·
|
||||
2d
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
class="level info"
|
||||
>
|
||||
<span
|
||||
class="title"
|
||||
>
|
||||
Info
|
||||
</span>
|
||||
<div
|
||||
class="status msg"
|
||||
>
|
||||
-
|
||||
Some info status for some-name
|
||||
|
||||
<span
|
||||
class="age"
|
||||
>
|
||||
·
|
||||
2d
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
`;
|
||||
@@ -0,0 +1,263 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
import { getDiForUnitTesting } from "../../getDiForUnitTesting";
|
||||
import rendererExtensionsInjectable from "../../../extensions/renderer-extensions.injectable";
|
||||
import { DiRender, renderFor } from "../test-utils/renderFor";
|
||||
import { computed } from "mobx";
|
||||
import { LensRendererExtension } from "../../../extensions/lens-renderer-extension";
|
||||
import { KubeObjectStatusLevel } from "../../../extensions/renderer-api/kube-object-status";
|
||||
import { KubeObject } from "../../../common/k8s-api/kube-object";
|
||||
import { KubeObjectStatusIcon } from "./kube-object-status-icon";
|
||||
import React from "react";
|
||||
import type { KubeObjectStatusRegistration } from "./kube-object-status-registration";
|
||||
|
||||
describe("kube-object-status-icon", () => {
|
||||
let render: DiRender;
|
||||
let kubeObjectStatusRegistrations: KubeObjectStatusRegistration[];
|
||||
|
||||
beforeEach(async () => {
|
||||
// TODO: Make mocking of date in unit tests global
|
||||
global.Date.now = () => new Date("2015-10-21T07:28:00Z").getTime();
|
||||
|
||||
const di = getDiForUnitTesting({ doGeneralOverrides: true });
|
||||
|
||||
render = renderFor(di);
|
||||
|
||||
kubeObjectStatusRegistrations = [];
|
||||
|
||||
const someTestExtension = new SomeTestExtension(
|
||||
kubeObjectStatusRegistrations,
|
||||
);
|
||||
|
||||
di.override(rendererExtensionsInjectable, () =>
|
||||
computed(() => [someTestExtension]),
|
||||
);
|
||||
|
||||
await di.runSetups();
|
||||
});
|
||||
|
||||
it("given no statuses, when rendered, renders as empty", () => {
|
||||
const kubeObject = getKubeObjectStub("irrelevant", "irrelevant");
|
||||
|
||||
const { container } = render(<KubeObjectStatusIcon object={kubeObject} />);
|
||||
|
||||
expect(container).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('given level "critical" status, when rendered, renders with status', () => {
|
||||
const kubeObject = getKubeObjectStub("some-kind", "some-api-version");
|
||||
|
||||
const statusRegistration = getStatusRegistration(
|
||||
KubeObjectStatusLevel.CRITICAL,
|
||||
"critical",
|
||||
"some-kind",
|
||||
["some-api-version"],
|
||||
);
|
||||
|
||||
kubeObjectStatusRegistrations.push(statusRegistration);
|
||||
|
||||
const { baseElement } = render(
|
||||
<KubeObjectStatusIcon object={kubeObject} />,
|
||||
);
|
||||
|
||||
expect(baseElement).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('given level "info" status, when rendered, renders with status', () => {
|
||||
const kubeObject = getKubeObjectStub("some-kind", "some-api-version");
|
||||
|
||||
const statusRegistration = getStatusRegistration(
|
||||
KubeObjectStatusLevel.INFO,
|
||||
"info",
|
||||
"some-kind",
|
||||
["some-api-version"],
|
||||
);
|
||||
|
||||
kubeObjectStatusRegistrations.push(statusRegistration);
|
||||
|
||||
const { baseElement } = render(
|
||||
<KubeObjectStatusIcon object={kubeObject} />,
|
||||
);
|
||||
|
||||
expect(baseElement).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it('given level "warning" status, when rendered, renders with status', () => {
|
||||
const kubeObject = getKubeObjectStub("some-kind", "some-api-version");
|
||||
|
||||
const statusRegistration = getStatusRegistration(
|
||||
KubeObjectStatusLevel.WARNING,
|
||||
"warning",
|
||||
"some-kind",
|
||||
["some-api-version"],
|
||||
);
|
||||
|
||||
kubeObjectStatusRegistrations.push(statusRegistration);
|
||||
|
||||
const { baseElement } = render(
|
||||
<KubeObjectStatusIcon object={kubeObject} />,
|
||||
);
|
||||
|
||||
expect(baseElement).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it("given status for all levels is present, when rendered, renders with statuses", () => {
|
||||
const kubeObject = getKubeObjectStub("some-kind", "some-api-version");
|
||||
|
||||
const critical = getStatusRegistration(
|
||||
KubeObjectStatusLevel.CRITICAL,
|
||||
"critical",
|
||||
"some-kind",
|
||||
["some-api-version"],
|
||||
);
|
||||
|
||||
const warning = getStatusRegistration(
|
||||
KubeObjectStatusLevel.WARNING,
|
||||
"warning",
|
||||
"some-kind",
|
||||
["some-api-version"],
|
||||
);
|
||||
|
||||
const info = getStatusRegistration(
|
||||
KubeObjectStatusLevel.INFO,
|
||||
"info",
|
||||
"some-kind",
|
||||
["some-api-version"],
|
||||
);
|
||||
|
||||
kubeObjectStatusRegistrations.push(critical);
|
||||
kubeObjectStatusRegistrations.push(warning);
|
||||
kubeObjectStatusRegistrations.push(info);
|
||||
|
||||
const { baseElement } = render(
|
||||
<KubeObjectStatusIcon object={kubeObject} />,
|
||||
);
|
||||
|
||||
expect(baseElement).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it("given info and warning statuses are present, when rendered, renders with statuses", () => {
|
||||
const kubeObject = getKubeObjectStub("some-kind", "some-api-version");
|
||||
|
||||
const warning = getStatusRegistration(
|
||||
KubeObjectStatusLevel.WARNING,
|
||||
"warning",
|
||||
"some-kind",
|
||||
["some-api-version"],
|
||||
);
|
||||
|
||||
const info = getStatusRegistration(
|
||||
KubeObjectStatusLevel.INFO,
|
||||
"info",
|
||||
"some-kind",
|
||||
["some-api-version"],
|
||||
);
|
||||
|
||||
kubeObjectStatusRegistrations.push(warning);
|
||||
kubeObjectStatusRegistrations.push(info);
|
||||
|
||||
const { baseElement } = render(
|
||||
<KubeObjectStatusIcon object={kubeObject} />,
|
||||
);
|
||||
|
||||
expect(baseElement).toMatchSnapshot();
|
||||
});
|
||||
|
||||
|
||||
it("given registration for wrong api version, when rendered, renders as empty", () => {
|
||||
const kubeObject = getKubeObjectStub("some-kind", "some-api-version");
|
||||
|
||||
const statusRegistration = getStatusRegistration(
|
||||
KubeObjectStatusLevel.CRITICAL,
|
||||
"irrelevant",
|
||||
"some-kind",
|
||||
["some-other-api-version"],
|
||||
);
|
||||
|
||||
kubeObjectStatusRegistrations.push(statusRegistration);
|
||||
|
||||
const { baseElement } = render(
|
||||
<KubeObjectStatusIcon object={kubeObject} />,
|
||||
);
|
||||
|
||||
expect(baseElement).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it("given registration for wrong kind, when rendered, renders as empty", () => {
|
||||
const kubeObject = getKubeObjectStub("some-kind", "some-api-version");
|
||||
|
||||
const statusRegistration = getStatusRegistration(
|
||||
KubeObjectStatusLevel.CRITICAL,
|
||||
"irrelevant",
|
||||
"some-other-kind",
|
||||
["some-api-version"],
|
||||
);
|
||||
|
||||
kubeObjectStatusRegistrations.push(statusRegistration);
|
||||
|
||||
const { baseElement } = render(
|
||||
<KubeObjectStatusIcon object={kubeObject} />,
|
||||
);
|
||||
|
||||
expect(baseElement).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it("given registration without status for exact kube object, when rendered, renders as empty", () => {
|
||||
const kubeObject = getKubeObjectStub("some-kind", "some-api-version");
|
||||
|
||||
const statusRegistration = {
|
||||
apiVersions: ["some-api-version"],
|
||||
kind: "some-kind",
|
||||
resolve: (): void => {},
|
||||
};
|
||||
|
||||
// @ts-ignore
|
||||
kubeObjectStatusRegistrations.push(statusRegistration);
|
||||
|
||||
const { baseElement } = render(
|
||||
<KubeObjectStatusIcon object={kubeObject} />,
|
||||
);
|
||||
|
||||
expect(baseElement).toMatchSnapshot();
|
||||
|
||||
});
|
||||
});
|
||||
|
||||
const getKubeObjectStub = (kind: string, apiVersion: string) => KubeObject.create({
|
||||
apiVersion,
|
||||
kind,
|
||||
metadata: {
|
||||
uid: "some-uid",
|
||||
name: "some-name",
|
||||
resourceVersion: "some-resource-version",
|
||||
namespace: "some-namespace",
|
||||
},
|
||||
});
|
||||
|
||||
const getStatusRegistration = (level: KubeObjectStatusLevel, title: string, kind: string, apiVersions: string[]) => ({
|
||||
apiVersions,
|
||||
kind,
|
||||
resolve: (kubeObject: KubeObject) => ({
|
||||
level,
|
||||
text: `Some ${title} status for ${kubeObject.getName()}`,
|
||||
timestamp: "2015-10-19T07:28:00Z",
|
||||
}),
|
||||
});
|
||||
|
||||
class SomeTestExtension extends LensRendererExtension {
|
||||
constructor(kubeObjectStatusTexts: KubeObjectStatusRegistration[]) {
|
||||
super({
|
||||
id: "some-id",
|
||||
absolutePath: "irrelevant",
|
||||
isBundled: false,
|
||||
isCompatible: false,
|
||||
isEnabled: false,
|
||||
manifest: { name: "some-id", version: "some-version" },
|
||||
manifestPath: "irrelevant",
|
||||
});
|
||||
|
||||
this.kubeObjectStatusTexts = kubeObjectStatusTexts;
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,8 @@ import React from "react";
|
||||
import { Icon } from "../icon";
|
||||
import { cssNames, formatDuration } from "../../utils";
|
||||
import { KubeObject, KubeObjectStatus, KubeObjectStatusLevel } from "../../..//extensions/renderer-api/k8s-api";
|
||||
import { KubeObjectStatusRegistry } from "../../../extensions/registries";
|
||||
import { withInjectables } from "@ogre-tools/injectable-react";
|
||||
import statusesForKubeObjectInjectable from "./statuses-for-kube-object.injectable";
|
||||
|
||||
function statusClassName(level: KubeObjectStatusLevel): string {
|
||||
switch (level) {
|
||||
@@ -68,7 +69,11 @@ export interface KubeObjectStatusIconProps {
|
||||
object: KubeObject;
|
||||
}
|
||||
|
||||
export class KubeObjectStatusIcon extends React.Component<KubeObjectStatusIconProps> {
|
||||
interface Dependencies {
|
||||
statuses: KubeObjectStatus[];
|
||||
}
|
||||
|
||||
class NonInjectedKubeObjectStatusIcon extends React.Component<KubeObjectStatusIconProps & Dependencies> {
|
||||
renderStatuses(statuses: KubeObjectStatus[], level: number) {
|
||||
const filteredStatuses = statuses.filter((item) => item.level == level);
|
||||
|
||||
@@ -89,7 +94,7 @@ export class KubeObjectStatusIcon extends React.Component<KubeObjectStatusIconPr
|
||||
}
|
||||
|
||||
render() {
|
||||
const statuses = KubeObjectStatusRegistry.getInstance().getItemsForObject(this.props.object);
|
||||
const statuses = this.props.statuses;
|
||||
|
||||
if (statuses.length === 0) {
|
||||
return null;
|
||||
@@ -114,3 +119,14 @@ export class KubeObjectStatusIcon extends React.Component<KubeObjectStatusIconPr
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export const KubeObjectStatusIcon = withInjectables<Dependencies, KubeObjectStatusIconProps>(
|
||||
NonInjectedKubeObjectStatusIcon,
|
||||
|
||||
{
|
||||
getProps: (di, props) => ({
|
||||
statuses: di.inject(statusesForKubeObjectInjectable, props.object),
|
||||
...props,
|
||||
}),
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
import type { KubeObject } from "../../../common/k8s-api/kube-object";
|
||||
import type { KubeObjectStatus } from "../../../extensions/renderer-api/kube-object-status";
|
||||
|
||||
export interface KubeObjectStatusRegistration {
|
||||
kind: string;
|
||||
apiVersions: string[];
|
||||
resolve: (object: KubeObject) => KubeObjectStatus;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
import { getInjectable, lifecycleEnum } from "@ogre-tools/injectable";
|
||||
import { computed } from "mobx";
|
||||
import rendererExtensionsInjectable from "../../../extensions/renderer-extensions.injectable";
|
||||
|
||||
const statusRegistrationsInjectable = getInjectable({
|
||||
id: "status-registrations",
|
||||
|
||||
instantiate: (di) => {
|
||||
const extensions = di.inject(rendererExtensionsInjectable);
|
||||
|
||||
return computed(() =>
|
||||
extensions.get().flatMap((extension) => extension.kubeObjectStatusTexts),
|
||||
);
|
||||
},
|
||||
|
||||
lifecycle: lifecycleEnum.singleton,
|
||||
});
|
||||
|
||||
export default statusRegistrationsInjectable;
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
import { getInjectable, lifecycleEnum } from "@ogre-tools/injectable";
|
||||
import statusRegistrationsInjectable from "./status-registrations.injectable";
|
||||
import type { KubeObject } from "../../../common/k8s-api/kube-object";
|
||||
import { conforms, eq, includes } from "lodash/fp";
|
||||
import type { KubeObjectStatusRegistration } from "./kube-object-status-registration";
|
||||
|
||||
const statusesForKubeObjectInjectable = getInjectable({
|
||||
id: "statuses-for-kube-object",
|
||||
|
||||
instantiate: (di, kubeObject: KubeObject) =>
|
||||
di
|
||||
.inject(statusRegistrationsInjectable)
|
||||
.get()
|
||||
.filter(toKubeObjectRelated(kubeObject))
|
||||
.map(toStatus(kubeObject))
|
||||
.filter(Boolean),
|
||||
|
||||
lifecycle: lifecycleEnum.transient,
|
||||
});
|
||||
|
||||
const toKubeObjectRelated = (kubeObject: KubeObject) =>
|
||||
conforms({
|
||||
kind: eq(kubeObject.kind),
|
||||
apiVersions: includes(kubeObject.apiVersion),
|
||||
});
|
||||
|
||||
const toStatus =
|
||||
(kubeObject: KubeObject) => (item: KubeObjectStatusRegistration) =>
|
||||
item.resolve(kubeObject);
|
||||
|
||||
export default statusesForKubeObjectInjectable;
|
||||
@@ -0,0 +1,163 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
import React from "react";
|
||||
import "@testing-library/jest-dom/extend-expect";
|
||||
import { Select } from "./select";
|
||||
import { UserStore } from "../../../common/user-store";
|
||||
import { ThemeStore } from "../../theme.store";
|
||||
import { getDiForUnitTesting } from "../../getDiForUnitTesting";
|
||||
import type { DiContainer } from "@ogre-tools/injectable";
|
||||
import { DiRender, renderFor } from "../test-utils/renderFor";
|
||||
import mockFs from "mock-fs";
|
||||
import directoryForUserDataInjectable
|
||||
from "../../../common/app-paths/directory-for-user-data/directory-for-user-data.injectable";
|
||||
import rendererExtensionsInjectable from "../../../extensions/renderer-extensions.injectable";
|
||||
import { computed } from "mobx";
|
||||
import type { LensRendererExtension } from "../../../extensions/lens-renderer-extension";
|
||||
|
||||
jest.mock("electron", () => ({
|
||||
ipcRenderer: {
|
||||
on: jest.fn(),
|
||||
invoke: jest.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
describe("<Select />", () => {
|
||||
let di: DiContainer;
|
||||
let render: DiRender;
|
||||
|
||||
beforeEach(async () => {
|
||||
|
||||
di = getDiForUnitTesting({ doGeneralOverrides: true });
|
||||
render = renderFor(di);
|
||||
|
||||
mockFs();
|
||||
|
||||
await di.runSetups();
|
||||
di.override(directoryForUserDataInjectable, () => "some-directory-for-user-data");
|
||||
di.override(rendererExtensionsInjectable, () => computed(() => [] as LensRendererExtension[]));
|
||||
|
||||
UserStore.createInstance();
|
||||
ThemeStore.createInstance();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
ThemeStore.resetInstance();
|
||||
UserStore.resetInstance();
|
||||
|
||||
mockFs.restore();
|
||||
});
|
||||
|
||||
it("should render the select", async () => {
|
||||
const options = [
|
||||
{
|
||||
label: "Option one label",
|
||||
value: "optionOneValue",
|
||||
},
|
||||
{
|
||||
label: "Option two label",
|
||||
value: "optionTwoValue",
|
||||
},
|
||||
];
|
||||
|
||||
const onChange = jest.fn();
|
||||
|
||||
const { container } = render(<Select onChange={onChange} options={options} />);
|
||||
|
||||
expect(container).toBeInstanceOf(HTMLElement);
|
||||
});
|
||||
|
||||
it("should show selected option", async () => {
|
||||
const options = [
|
||||
{
|
||||
label: "Option one label",
|
||||
value: "optionOneValue",
|
||||
},
|
||||
{
|
||||
label: "Option two label",
|
||||
value: "optionTwoValue",
|
||||
},
|
||||
];
|
||||
|
||||
const onChange = jest.fn();
|
||||
|
||||
const { container } = render(<Select value={options[0].value} onChange={onChange} options={options} />);
|
||||
const selectedValueContainer = container.querySelector(".Select__single-value");
|
||||
|
||||
expect(selectedValueContainer.textContent).toBe(options[0].label);
|
||||
});
|
||||
|
||||
it("should reflect to change value", async () => {
|
||||
const options = [
|
||||
{
|
||||
label: "Option one label",
|
||||
value: "optionOneValue",
|
||||
},
|
||||
{
|
||||
label: "Option two label",
|
||||
value: "optionTwoValue",
|
||||
},
|
||||
];
|
||||
|
||||
const onChange = jest.fn();
|
||||
|
||||
const { container, rerender } = render(<Select value={options[0].value} onChange={onChange} options={options} />);
|
||||
const selectedValueContainer = container.querySelector(".Select__single-value");
|
||||
|
||||
expect(selectedValueContainer.textContent).toBe(options[0].label);
|
||||
|
||||
rerender(<Select value={options[1].value} onChange={onChange} options={options} />);
|
||||
|
||||
expect(container.querySelector(".Select__single-value").textContent).toBe(options[1].label);
|
||||
});
|
||||
|
||||
it("should unselect value if null is passed as a value", async () => {
|
||||
const options = [
|
||||
{
|
||||
label: "Option one label",
|
||||
value: "optionOneValue",
|
||||
},
|
||||
{
|
||||
label: "Option two label",
|
||||
value: "optionTwoValue",
|
||||
},
|
||||
];
|
||||
|
||||
const onChange = jest.fn();
|
||||
|
||||
const { container, rerender } = render(<Select value={options[0].value} onChange={onChange} options={options} />);
|
||||
const selectedValueContainer = container.querySelector(".Select__single-value");
|
||||
|
||||
expect(selectedValueContainer.textContent).toBe(options[0].label);
|
||||
|
||||
rerender(<Select value={null} onChange={onChange} options={options} />);
|
||||
|
||||
expect(container.querySelector(".Select__single-value")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("should unselect value if undefined is passed as a value", async () => {
|
||||
const options = [
|
||||
{
|
||||
label: "Option one label",
|
||||
value: "optionOneValue",
|
||||
},
|
||||
{
|
||||
label: "Option two label",
|
||||
value: "optionTwoValue",
|
||||
},
|
||||
];
|
||||
|
||||
const onChange = jest.fn();
|
||||
|
||||
const { container, rerender } = render(<Select value={options[0].value} onChange={onChange} options={options} />);
|
||||
const selectedValueContainer = container.querySelector(".Select__single-value");
|
||||
|
||||
expect(selectedValueContainer.textContent).toBe(options[0].label);
|
||||
|
||||
rerender(<Select value={undefined} onChange={onChange} options={options} />);
|
||||
|
||||
expect(container.querySelector(".Select__single-value")).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -80,7 +80,7 @@ export class Select extends React.Component<SelectProps> {
|
||||
});
|
||||
}
|
||||
|
||||
return this.options.find(opt => opt === value || opt.value === value);
|
||||
return this.options.find(opt => opt === value || opt.value === value) || null;
|
||||
}
|
||||
|
||||
@computed get options(): SelectOption[] {
|
||||
|
||||
@@ -75,10 +75,6 @@ export const initClusterFrame =
|
||||
});
|
||||
});
|
||||
|
||||
window.addEventListener("online", () => {
|
||||
window.location.reload();
|
||||
});
|
||||
|
||||
window.onbeforeunload = () => {
|
||||
logger.info(
|
||||
`${logPrefix} Unload dashboard, clusterId=${(hostedCluster.id)}, frameId=${frameRoutingId}`,
|
||||
|
||||
@@ -9,5 +9,4 @@ export * from "./entity-settings-registry";
|
||||
export * from "./ipc";
|
||||
export * from "./kube-object-detail-registry";
|
||||
export * from "./registries";
|
||||
export * from "./workloads-overview-detail-registry";
|
||||
export * from "./catalog-category-registry";
|
||||
@@ -12,6 +12,4 @@ export function initRegistries() {
|
||||
registries.EntitySettingRegistry.createInstance();
|
||||
registries.GlobalPageRegistry.createInstance();
|
||||
registries.KubeObjectDetailRegistry.createInstance();
|
||||
registries.KubeObjectStatusRegistry.createInstance();
|
||||
registries.WorkloadsOverviewDetailRegistry.createInstance();
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import { WorkloadsOverviewDetailRegistry } from "../../extensions/registries";
|
||||
import { OverviewStatuses } from "../components/+workloads-overview/overview-statuses";
|
||||
import { WorkloadEvents } from "./workload-events";
|
||||
|
||||
export function initWorkloadsOverviewDetailRegistry() {
|
||||
WorkloadsOverviewDetailRegistry.getInstance()
|
||||
.add([
|
||||
{
|
||||
components: {
|
||||
Details: OverviewStatuses,
|
||||
},
|
||||
},
|
||||
{
|
||||
priority: 5,
|
||||
components: {
|
||||
Details: WorkloadEvents,
|
||||
},
|
||||
},
|
||||
]);
|
||||
}
|
||||
@@ -13,6 +13,8 @@ import type { SelectOption } from "./components/select";
|
||||
import type { MonacoEditorProps } from "./components/monaco-editor";
|
||||
import { defaultTheme } from "../common/vars";
|
||||
import { camelCase } from "lodash";
|
||||
import { ipcRenderer } from "electron";
|
||||
import { getNativeThemeChannel, setNativeThemeChannel } from "../common/ipc/native-theme";
|
||||
|
||||
export type ThemeId = string;
|
||||
|
||||
@@ -34,6 +36,8 @@ export class ThemeStore extends Singleton {
|
||||
"lens-light": lensLightThemeJson as Theme,
|
||||
});
|
||||
|
||||
@observable osNativeTheme: "dark" | "light" | undefined;
|
||||
|
||||
@computed get activeThemeId(): ThemeId {
|
||||
return UserStore.getInstance().colorTheme;
|
||||
}
|
||||
@@ -43,7 +47,7 @@ export class ThemeStore extends Singleton {
|
||||
}
|
||||
|
||||
@computed get activeTheme(): Theme {
|
||||
return this.themes.get(this.activeThemeId) ?? this.themes.get(defaultTheme);
|
||||
return this.systemTheme ?? this.themes.get(this.activeThemeId) ?? this.themes.get(defaultTheme);
|
||||
}
|
||||
|
||||
@computed get terminalColors(): [string, string][] {
|
||||
@@ -72,11 +76,25 @@ export class ThemeStore extends Singleton {
|
||||
}));
|
||||
}
|
||||
|
||||
@computed get systemTheme() {
|
||||
if (this.activeThemeId == "system" && this.osNativeTheme) {
|
||||
return this.themes.get(`lens-${this.osNativeTheme}`);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
|
||||
makeObservable(this);
|
||||
autoBind(this);
|
||||
this.init();
|
||||
}
|
||||
|
||||
async init() {
|
||||
await this.setNativeTheme();
|
||||
this.bindNativeThemeUpdateEvent();
|
||||
|
||||
// auto-apply active theme
|
||||
reaction(() => ({
|
||||
@@ -95,12 +113,26 @@ export class ThemeStore extends Singleton {
|
||||
});
|
||||
}
|
||||
|
||||
bindNativeThemeUpdateEvent() {
|
||||
ipcRenderer.on(setNativeThemeChannel, (event, theme: "dark" | "light") => {
|
||||
this.osNativeTheme = theme;
|
||||
this.applyTheme(theme);
|
||||
});
|
||||
}
|
||||
|
||||
async setNativeTheme() {
|
||||
const theme: "dark" | "light" = await ipcRenderer.invoke(getNativeThemeChannel);
|
||||
|
||||
this.osNativeTheme = theme;
|
||||
}
|
||||
|
||||
getThemeById(themeId: ThemeId): Theme {
|
||||
return this.themes.get(themeId);
|
||||
}
|
||||
|
||||
protected applyTheme(themeId: ThemeId) {
|
||||
const theme = this.getThemeById(themeId);
|
||||
const theme = this.systemTheme ?? this.getThemeById(themeId);
|
||||
|
||||
const colors = Object.entries({
|
||||
...theme.colors,
|
||||
...Object.fromEntries(this.terminalColors),
|
||||
|
||||
Reference in new issue
Block a user