mirror of
https://github.com/lensapp/lens.git
synced 2025-05-20 05:10:56 +00:00
Merge branch 'master' into issue-3498
Signed-off-by: Sebastian Malton <sebastian@malton.name>
This commit is contained in:
commit
528384d2d9
106 files changed
+6261
-1930
No files matched your search
@@ -53,10 +53,16 @@ export abstract class BaseStore<T extends object> {
|
||||
|
||||
readonly displayName = kebabCase(this.params.configName).toUpperCase();
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
protected readonly dependencies: BaseStoreDependencies;
|
||||
|
||||
protected constructor(
|
||||
protected readonly dependencies: BaseStoreDependencies,
|
||||
dependencies: BaseStoreDependencies,
|
||||
protected readonly params: BaseStoreParams<T>,
|
||||
) {
|
||||
this.dependencies = dependencies;
|
||||
makeObservable(this);
|
||||
}
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ import type { CatalogEntityMetadata, CatalogEntitySpec, CatalogEntityStatus } fr
|
||||
import type { CatalogEntityActionContext } from "../catalog/catalog-entity";
|
||||
import { CatalogCategory, CatalogEntity, categoryVersion } from "../catalog/catalog-entity";
|
||||
|
||||
interface GeneralEntitySpec extends CatalogEntitySpec {
|
||||
export interface GeneralEntitySpec extends CatalogEntitySpec {
|
||||
path: string;
|
||||
icon?: {
|
||||
material?: string;
|
||||
|
||||
@@ -9,7 +9,9 @@ import { observable, makeObservable } from "mobx";
|
||||
import { once } from "lodash";
|
||||
import type { Disposer } from "../utils";
|
||||
import { iter } from "../utils";
|
||||
import type { CategoryColumnRegistration } from "../../renderer/components/+catalog/custom-category-columns";
|
||||
import type { CategoryColumnRegistration, TitleCellProps } from "../../renderer/components/+catalog/custom-category-columns";
|
||||
|
||||
export type { CategoryColumnRegistration, TitleCellProps };
|
||||
|
||||
export type CatalogEntityDataFor<Entity> = Entity extends CatalogEntity<infer Metadata, infer Status, infer Spec>
|
||||
? CatalogEntityData<Metadata, Status, Spec>
|
||||
|
||||
@@ -157,7 +157,7 @@ export enum ClusterStatus {
|
||||
*/
|
||||
export interface KubeAuthUpdate {
|
||||
message: string;
|
||||
isError: boolean;
|
||||
level: "info" | "warning" | "error";
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -356,7 +356,7 @@ export class Cluster implements ClusterModel {
|
||||
this.broadcastConnectUpdate("Starting connection ...");
|
||||
await this.reconnect();
|
||||
} catch (error) {
|
||||
this.broadcastConnectUpdate(`Failed to start connection: ${error}`, true);
|
||||
this.broadcastConnectUpdate(`Failed to start connection: ${error}`, "error");
|
||||
|
||||
return;
|
||||
}
|
||||
@@ -366,7 +366,7 @@ export class Cluster implements ClusterModel {
|
||||
this.broadcastConnectUpdate("Refreshing connection status ...");
|
||||
await this.refreshConnectionStatus();
|
||||
} catch (error) {
|
||||
this.broadcastConnectUpdate(`Failed to connection status: ${error}`, true);
|
||||
this.broadcastConnectUpdate(`Failed to connection status: ${error}`, "error");
|
||||
|
||||
return;
|
||||
}
|
||||
@@ -376,7 +376,7 @@ export class Cluster implements ClusterModel {
|
||||
this.broadcastConnectUpdate("Refreshing cluster accessibility ...");
|
||||
await this.refreshAccessibility();
|
||||
} catch (error) {
|
||||
this.broadcastConnectUpdate(`Failed to refresh accessibility: ${error}`, true);
|
||||
this.broadcastConnectUpdate(`Failed to refresh accessibility: ${error}`, "error");
|
||||
|
||||
return;
|
||||
}
|
||||
@@ -484,9 +484,20 @@ export class Cluster implements ClusterModel {
|
||||
resource: "*",
|
||||
});
|
||||
this.allowedNamespaces.replace(await this.requestAllowedNamespaces(proxyConfig));
|
||||
this.knownResources.replace(await this.dependencies.requestApiResources(this));
|
||||
|
||||
const knownResources = await this.dependencies.requestApiResources(this);
|
||||
|
||||
if (knownResources.callWasSuccessful) {
|
||||
this.knownResources.replace(knownResources.response);
|
||||
} else if (this.knownResources.length > 0) {
|
||||
this.dependencies.logger.warn(`[CLUSTER]: failed to list KUBE resources, sticking with previous list`);
|
||||
} else {
|
||||
this.dependencies.logger.warn(`[CLUSTER]: failed to list KUBE resources for the first time, blocking connection to cluster...`);
|
||||
this.broadcastConnectUpdate("Failed to list kube API resources, please reconnect...", "error");
|
||||
}
|
||||
|
||||
this.allowedResources.replace(await this.getAllowedResources(requestNamespaceListPermissions));
|
||||
this.ready = true;
|
||||
this.ready = this.knownResources.length > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -536,37 +547,37 @@ export class Cluster implements ClusterModel {
|
||||
if (isRequestError(error)) {
|
||||
if (error.statusCode) {
|
||||
if (error.statusCode >= 400 && error.statusCode < 500) {
|
||||
this.broadcastConnectUpdate("Invalid credentials", true);
|
||||
this.broadcastConnectUpdate("Invalid credentials", "error");
|
||||
|
||||
return ClusterStatus.AccessDenied;
|
||||
}
|
||||
|
||||
const message = String(error.error || error.message) || String(error);
|
||||
|
||||
this.broadcastConnectUpdate(message, true);
|
||||
this.broadcastConnectUpdate(message, "error");
|
||||
|
||||
return ClusterStatus.Offline;
|
||||
}
|
||||
|
||||
if (error.failed === true) {
|
||||
if (error.timedOut === true) {
|
||||
this.broadcastConnectUpdate("Connection timed out", true);
|
||||
this.broadcastConnectUpdate("Connection timed out", "error");
|
||||
|
||||
return ClusterStatus.Offline;
|
||||
}
|
||||
|
||||
this.broadcastConnectUpdate("Failed to fetch credentials", true);
|
||||
this.broadcastConnectUpdate("Failed to fetch credentials", "error");
|
||||
|
||||
return ClusterStatus.AccessDenied;
|
||||
}
|
||||
|
||||
const message = String(error.error || error.message) || String(error);
|
||||
|
||||
this.broadcastConnectUpdate(message, true);
|
||||
this.broadcastConnectUpdate(message, "error");
|
||||
} else if (error instanceof Error || typeof error === "string") {
|
||||
this.broadcastConnectUpdate(`${error}`, true);
|
||||
this.broadcastConnectUpdate(`${error}`, "error");
|
||||
} else {
|
||||
this.broadcastConnectUpdate("Unknown error has occurred", true);
|
||||
this.broadcastConnectUpdate("Unknown error has occurred", "error");
|
||||
}
|
||||
|
||||
return ClusterStatus.Offline;
|
||||
@@ -636,8 +647,8 @@ export class Cluster implements ClusterModel {
|
||||
* broadcast an authentication update concerning this cluster
|
||||
* @internal
|
||||
*/
|
||||
broadcastConnectUpdate(message: string, isError = false): void {
|
||||
const update: KubeAuthUpdate = { message, isError };
|
||||
broadcastConnectUpdate(message: string, level: KubeAuthUpdate["level"] = "info"): void {
|
||||
const update: KubeAuthUpdate = { message, level };
|
||||
|
||||
this.dependencies.logger.debug(`[CLUSTER]: broadcasting connection update`, { ...update, meta: this.getMeta() });
|
||||
this.dependencies.broadcastMessage(`cluster:${this.id}:connection-update`, update);
|
||||
@@ -668,7 +679,7 @@ export class Cluster implements ClusterModel {
|
||||
}
|
||||
|
||||
protected async getAllowedResources(requestNamespaceListPermissions: RequestNamespaceListPermissions) {
|
||||
if (!this.allowedNamespaces.length) {
|
||||
if (!this.allowedNamespaces.length || !this.knownResources.length) {
|
||||
return [];
|
||||
}
|
||||
|
||||
|
||||
@@ -5,23 +5,23 @@
|
||||
|
||||
// Custom event emitter
|
||||
|
||||
interface Options {
|
||||
export interface EventEmitterOptions {
|
||||
once?: boolean; // call once and remove
|
||||
prepend?: boolean; // put listener to the beginning
|
||||
}
|
||||
|
||||
type Callback<D extends [...any[]]> = (...data: D) => void | boolean;
|
||||
export type EventEmitterCallback<D extends any[]> = (...data: D) => void | boolean;
|
||||
|
||||
export class EventEmitter<D extends [...any[]]> {
|
||||
protected listeners: [Callback<D>, Options][] = [];
|
||||
export class EventEmitter<D extends any[]> {
|
||||
protected listeners: [EventEmitterCallback<D>, EventEmitterOptions][] = [];
|
||||
|
||||
addListener(callback: Callback<D>, options: Options = {}) {
|
||||
addListener(callback: EventEmitterCallback<D>, options: EventEmitterOptions = {}) {
|
||||
const fn = options.prepend ? "unshift" : "push";
|
||||
|
||||
this.listeners[fn]([callback, options]);
|
||||
}
|
||||
|
||||
removeListener(callback: Callback<D>) {
|
||||
removeListener(callback: EventEmitterCallback<D>) {
|
||||
this.listeners = this.listeners.filter(([cb]) => cb !== callback);
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
import { getInjectable } from "@ogre-tools/injectable";
|
||||
import type { RequestInit, Response } from "node-fetch";
|
||||
import type { RequestInit, Response } from "@k8slens/node-fetch";
|
||||
import type { AsyncResult } from "../utils/async-result";
|
||||
import fetchInjectable from "./fetch.injectable";
|
||||
|
||||
@@ -22,7 +22,6 @@ const downloadBinaryInjectable = getInjectable({
|
||||
let result: Response;
|
||||
|
||||
try {
|
||||
// TODO: upgrade node-fetch once we switch to ESM
|
||||
result = await fetch(url, opts as RequestInit);
|
||||
} catch (error) {
|
||||
return {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
*/
|
||||
import type { AsyncResult } from "../../utils/async-result";
|
||||
import type { Fetch } from "../fetch.injectable";
|
||||
import type { RequestInit, Response } from "node-fetch";
|
||||
import type { RequestInit, Response } from "@k8slens/node-fetch";
|
||||
|
||||
export interface DownloadJsonOptions {
|
||||
signal?: AbortSignal | null | undefined;
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
import { getInjectable } from "@ogre-tools/injectable";
|
||||
import type * as FetchModule from "node-fetch";
|
||||
|
||||
const { NodeFetch } = require("../../../build/webpack/node-fetch.bundle") as { NodeFetch: typeof FetchModule };
|
||||
|
||||
/**
|
||||
* NOTE: while using this module can cause side effects, this specific injectable is not marked as
|
||||
* such since sometimes the request can be wholely within the perview of unit test
|
||||
*/
|
||||
const nodeFetchModuleInjectable = getInjectable({
|
||||
id: "node-fetch-module",
|
||||
instantiate: () => NodeFetch,
|
||||
});
|
||||
|
||||
export default nodeFetchModuleInjectable;
|
||||
@@ -3,18 +3,14 @@
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
import { getInjectable } from "@ogre-tools/injectable";
|
||||
import type { RequestInit, Response } from "node-fetch";
|
||||
import nodeFetchModuleInjectable from "./fetch-module.injectable";
|
||||
import type { RequestInit, Response } from "@k8slens/node-fetch";
|
||||
import fetch from "@k8slens/node-fetch";
|
||||
|
||||
export type Fetch = (url: string, init?: RequestInit) => Promise<Response>;
|
||||
|
||||
const fetchInjectable = getInjectable({
|
||||
id: "fetch",
|
||||
instantiate: (di): Fetch => {
|
||||
const { default: fetch } = di.inject(nodeFetchModuleInjectable);
|
||||
|
||||
return (url, init) => fetch(url, init);
|
||||
},
|
||||
instantiate: () => fetch as Fetch,
|
||||
causesSideEffects: true,
|
||||
});
|
||||
|
||||
|
||||
@@ -4,10 +4,10 @@
|
||||
*/
|
||||
import { getInjectable } from "@ogre-tools/injectable";
|
||||
import { Agent } from "https";
|
||||
import type { RequestInit, Response } from "node-fetch";
|
||||
import type { RequestInit, Response } from "@k8slens/node-fetch";
|
||||
import lensProxyPortInjectable from "../../main/lens-proxy/lens-proxy-port.injectable";
|
||||
import lensProxyCertificateInjectable from "../certificate/lens-proxy-certificate.injectable";
|
||||
import nodeFetchModuleInjectable from "./fetch-module.injectable";
|
||||
import fetch from "@k8slens/node-fetch";
|
||||
|
||||
export type LensRequestInit = Omit<RequestInit, "agent">;
|
||||
|
||||
@@ -16,7 +16,6 @@ export type LensFetch = (pathnameAndQuery: string, init?: LensRequestInit) => Pr
|
||||
const lensFetchInjectable = getInjectable({
|
||||
id: "lens-fetch",
|
||||
instantiate: (di): LensFetch => {
|
||||
const { default: fetch } = di.inject(nodeFetchModuleInjectable);
|
||||
const lensProxyPort = di.inject(lensProxyPortInjectable);
|
||||
const lensProxyCertificate = di.inject(lensProxyCertificateInjectable);
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
*/
|
||||
import type { ApiManager } from "../api-manager";
|
||||
import type { IngressApi } from "../endpoints";
|
||||
import { Ingress } from "../endpoints";
|
||||
import { Ingress, HorizontalPodAutoscalerApi } from "../endpoints";
|
||||
import { getDiForUnitTesting } from "../../../renderer/getDiForUnitTesting";
|
||||
import type { Fetch } from "../../fetch/fetch.injectable";
|
||||
import fetchInjectable from "../../fetch/fetch.injectable";
|
||||
@@ -21,6 +21,8 @@ import directoryForKubeConfigsInjectable from "../../app-paths/directory-for-kub
|
||||
import apiManagerInjectable from "../api-manager/manager.injectable";
|
||||
import type { DiContainer } from "@ogre-tools/injectable";
|
||||
import ingressApiInjectable from "../endpoints/ingress.api.injectable";
|
||||
import loggerInjectable from "../../logger.injectable";
|
||||
import maybeKubeApiInjectable from "../maybe-kube-api.injectable";
|
||||
|
||||
describe("KubeApi", () => {
|
||||
let fetchMock: AsyncFnMock<Fetch>;
|
||||
@@ -705,4 +707,125 @@ describe("KubeApi", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("on first call to HorizontalPodAutoscalerApi.get()", () => {
|
||||
let horizontalPodAutoscalerApi: HorizontalPodAutoscalerApi;
|
||||
|
||||
beforeEach(async () => {
|
||||
horizontalPodAutoscalerApi = new HorizontalPodAutoscalerApi({
|
||||
logger: di.inject(loggerInjectable),
|
||||
maybeKubeApi: di.inject(maybeKubeApiInjectable),
|
||||
}, {
|
||||
allowedUsableVersions: {
|
||||
autoscaling: [
|
||||
"v2",
|
||||
"v2beta2",
|
||||
"v2beta1",
|
||||
"v1",
|
||||
],
|
||||
},
|
||||
});
|
||||
horizontalPodAutoscalerApi.get({
|
||||
name: "foo",
|
||||
namespace: "default",
|
||||
});
|
||||
|
||||
// This is needed because of how JS promises work
|
||||
await flushPromises();
|
||||
});
|
||||
|
||||
it("requests version list from the api group from the initial apiBase", () => {
|
||||
expect(fetchMock.mock.lastCall).toMatchObject([
|
||||
"https://127.0.0.1:12345/api-kube/apis/autoscaling",
|
||||
{
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
},
|
||||
method: "get",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
describe("when the version list from the api group resolves with preferredVersion in allowed version", () => {
|
||||
beforeEach(async () => {
|
||||
await fetchMock.resolveSpecific(
|
||||
["https://127.0.0.1:12345/api-kube/apis/autoscaling"],
|
||||
createMockResponseFromString("https://127.0.0.1:12345/api-kube/apis/autoscaling", JSON.stringify({
|
||||
apiVersion: "v1",
|
||||
kind: "APIGroup",
|
||||
name: "autoscaling",
|
||||
versions: [
|
||||
{
|
||||
groupVersion: "autoscaling/v1",
|
||||
version: "v1",
|
||||
},
|
||||
{
|
||||
groupVersion: "autoscaling/v1beta1",
|
||||
version: "v2beta1",
|
||||
},
|
||||
],
|
||||
preferredVersion: {
|
||||
groupVersion: "autoscaling/v1",
|
||||
version: "v1",
|
||||
},
|
||||
})),
|
||||
);
|
||||
});
|
||||
|
||||
it("requests resources from the preferred version api group from the initial apiBase", () => {
|
||||
expect(fetchMock.mock.lastCall).toMatchObject([
|
||||
"https://127.0.0.1:12345/api-kube/apis/autoscaling/v1",
|
||||
{
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
},
|
||||
method: "get",
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("when the version list from the api group resolves with preferredVersion not allowed version", () => {
|
||||
beforeEach(async () => {
|
||||
await fetchMock.resolveSpecific(
|
||||
["https://127.0.0.1:12345/api-kube/apis/autoscaling"],
|
||||
createMockResponseFromString("https://127.0.0.1:12345/api-kube/apis/autoscaling", JSON.stringify({
|
||||
apiVersion: "v1",
|
||||
kind: "APIGroup",
|
||||
name: "autoscaling",
|
||||
versions: [
|
||||
{
|
||||
groupVersion: "autoscaling/v2",
|
||||
version: "v2",
|
||||
},
|
||||
{
|
||||
groupVersion: "autoscaling/v2beta1",
|
||||
version: "v2beta1",
|
||||
},
|
||||
{
|
||||
groupVersion: "autoscaling/v3",
|
||||
version: "v3",
|
||||
},
|
||||
],
|
||||
preferredVersion: {
|
||||
groupVersion: "autoscaling/v3",
|
||||
version: "v3",
|
||||
},
|
||||
})),
|
||||
);
|
||||
});
|
||||
|
||||
it("requests resources from the non preferred version from the initial apiBase", () => {
|
||||
expect(fetchMock.mock.lastCall).toMatchObject([
|
||||
"https://127.0.0.1:12345/api-kube/apis/autoscaling/v2",
|
||||
{
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
},
|
||||
method: "get",
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -4,7 +4,7 @@
|
||||
*/
|
||||
import { getInjectable } from "@ogre-tools/injectable";
|
||||
import { Agent } from "https";
|
||||
import type { RequestInit } from "node-fetch";
|
||||
import type { RequestInit } from "@k8slens/node-fetch";
|
||||
import lensProxyCertificateInjectable from "../certificate/lens-proxy-certificate.injectable";
|
||||
import fetchInjectable from "../fetch/fetch.injectable";
|
||||
import loggerInjectable from "../logger.injectable";
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
import { getInjectable } from "@ogre-tools/injectable";
|
||||
import type { AgentOptions } from "https";
|
||||
import { Agent } from "https";
|
||||
import type { RequestInit } from "node-fetch";
|
||||
import type { RequestInit } from "@k8slens/node-fetch";
|
||||
import loggerInjectable from "../logger.injectable";
|
||||
import isDevelopmentInjectable from "../vars/is-development.injectable";
|
||||
import createKubeJsonApiInjectable from "./create-kube-json-api.injectable";
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
*/
|
||||
import { getInjectable } from "@ogre-tools/injectable";
|
||||
import { Agent } from "https";
|
||||
import type { RequestInit } from "node-fetch";
|
||||
import type { RequestInit } from "@k8slens/node-fetch";
|
||||
import lensProxyCertificateInjectable from "../certificate/lens-proxy-certificate.injectable";
|
||||
import fetchInjectable from "../fetch/fetch.injectable";
|
||||
import loggerInjectable from "../logger.injectable";
|
||||
|
||||
@@ -371,6 +371,14 @@ export class HorizontalPodAutoscaler extends KubeObject<
|
||||
export class HorizontalPodAutoscalerApi extends KubeApi<HorizontalPodAutoscaler> {
|
||||
constructor(deps: KubeApiDependencies, opts?: DerivedKubeApiOptions) {
|
||||
super(deps, {
|
||||
allowedUsableVersions: {
|
||||
autoscaling: [
|
||||
"v2",
|
||||
"v2beta2",
|
||||
"v2beta1",
|
||||
"v1",
|
||||
],
|
||||
},
|
||||
...opts ?? {},
|
||||
objectConstructor: HorizontalPodAutoscaler,
|
||||
checkPreferredVersion: true,
|
||||
|
||||
@@ -18,6 +18,14 @@ const podDisruptionBudgetApiInjectable = getInjectable({
|
||||
return new PodDisruptionBudgetApi({
|
||||
logger: di.inject(loggerInjectable),
|
||||
maybeKubeApi: di.inject(maybeKubeApiInjectable),
|
||||
}, {
|
||||
checkPreferredVersion: true,
|
||||
allowedUsableVersions: {
|
||||
policy: [
|
||||
"v1",
|
||||
"v1beta1",
|
||||
],
|
||||
},
|
||||
});
|
||||
},
|
||||
|
||||
|
||||
@@ -7,20 +7,45 @@ import type { LabelSelector, NamespaceScopedMetadata } from "../kube-object";
|
||||
import { KubeObject } from "../kube-object";
|
||||
import type { DerivedKubeApiOptions, KubeApiDependencies } from "../kube-api";
|
||||
import { KubeApi } from "../kube-api";
|
||||
import type { Condition } from "./types/condition";
|
||||
|
||||
export interface PodDisruptionBudgetSpec {
|
||||
export interface V1Beta1PodDisruptionBudgetSpec {
|
||||
minAvailable: string;
|
||||
maxUnavailable: string;
|
||||
selector: LabelSelector;
|
||||
}
|
||||
|
||||
export interface PodDisruptionBudgetStatus {
|
||||
export interface V1PodDisruptionBudgetSpec {
|
||||
maxUnavailable?: string | number;
|
||||
minAvailable?: string | number;
|
||||
selector?: LabelSelector;
|
||||
}
|
||||
|
||||
export type PodDisruptionBudgetSpec =
|
||||
| V1Beta1PodDisruptionBudgetSpec
|
||||
| V1PodDisruptionBudgetSpec;
|
||||
|
||||
export interface V1Beta1PodDisruptionBudgetStatus {
|
||||
currentHealthy: number;
|
||||
desiredHealthy: number;
|
||||
disruptionsAllowed: number;
|
||||
expectedPods: number;
|
||||
}
|
||||
|
||||
export interface V1PodDisruptionBudgetStatus {
|
||||
conditions?: Condition[];
|
||||
currentHealthy: number;
|
||||
desiredHealthy: number;
|
||||
disruptedPods?: Partial<Record<string, string>>;
|
||||
disruptionsAllowed: number;
|
||||
expectedPods: number;
|
||||
observedGeneration?: number;
|
||||
}
|
||||
|
||||
export type PodDisruptionBudgetStatus =
|
||||
| V1Beta1PodDisruptionBudgetStatus
|
||||
| V1PodDisruptionBudgetStatus;
|
||||
|
||||
export class PodDisruptionBudget extends KubeObject<
|
||||
NamespaceScopedMetadata,
|
||||
PodDisruptionBudgetStatus,
|
||||
@@ -31,7 +56,7 @@ export class PodDisruptionBudget extends KubeObject<
|
||||
static readonly apiBase = "/apis/policy/v1beta1/poddisruptionbudgets";
|
||||
|
||||
getSelectors() {
|
||||
return KubeObject.stringifyLabels(this.spec.selector.matchLabels);
|
||||
return KubeObject.stringifyLabels(this.spec.selector?.matchLabels);
|
||||
}
|
||||
|
||||
getMinAvailable() {
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
export interface Condition {
|
||||
lastTransitionTime: string;
|
||||
message: string;
|
||||
observedGeneration?: number;
|
||||
reason: string;
|
||||
status: string;
|
||||
type: string;
|
||||
}
|
||||
@@ -8,7 +8,7 @@
|
||||
import { Agent as HttpAgent } from "http";
|
||||
import { Agent as HttpsAgent } from "https";
|
||||
import { merge } from "lodash";
|
||||
import type { Response, RequestInit } from "node-fetch";
|
||||
import type { Response, RequestInit } from "@k8slens/node-fetch";
|
||||
import { stringify } from "querystring";
|
||||
import type { Patch } from "rfc6902";
|
||||
import type { PartialDeep, ValueOf } from "type-fest";
|
||||
|
||||
@@ -15,7 +15,7 @@ import type { IKubeWatchEvent } from "./kube-watch-event";
|
||||
import type { KubeJsonApiData, KubeJsonApi } from "./kube-json-api";
|
||||
import type { Disposer } from "../utils";
|
||||
import { isDefined, noop, WrappedAbortController } from "../utils";
|
||||
import type { RequestInit, Response } from "node-fetch";
|
||||
import type { RequestInit, Response } from "@k8slens/node-fetch";
|
||||
import type { Patch } from "rfc6902";
|
||||
import assert from "assert";
|
||||
import type { PartialDeep } from "type-fest";
|
||||
@@ -58,14 +58,32 @@ export interface DerivedKubeApiOptions {
|
||||
/**
|
||||
* If the API uses a different API endpoint (e.g. apiBase) depending on the cluster version,
|
||||
* fallback API bases can be listed individually.
|
||||
*
|
||||
* The first (existing) API base is used in the requests, if apiBase is not found.
|
||||
* This option only has effect if checkPreferredVersion is true.
|
||||
*
|
||||
* This option only has effect if {@link DerivedKubeApiOptions.checkPreferredVersion} is `true`.
|
||||
*/
|
||||
fallbackApiBases?: string[];
|
||||
|
||||
/**
|
||||
* This option is useful for protecting against newer versions on the same apiBase from being
|
||||
* used. So that if a certain type only supports `v1`, or `v2` of some kind and then the `v3`
|
||||
* version becomes the `preferredVersion` on the server but still has `v2` then the `v2` version
|
||||
* will be used instead.
|
||||
*
|
||||
* This can help to prevent crashes in the future if the shape of a kind sufficently changes.
|
||||
*
|
||||
* The order is important. It should be sorted and the first entry should be the most preferable.
|
||||
*
|
||||
* This option only has effect if {@link DerivedKubeApiOptions.checkPreferredVersion} is `true`
|
||||
*/
|
||||
allowedUsableVersions?: Partial<Record<string, [string, ...string[]]>>;
|
||||
|
||||
/**
|
||||
* If `true` then will check all declared apiBases against the kube api server
|
||||
* for the first accepted one.
|
||||
*
|
||||
* @default false
|
||||
*/
|
||||
checkPreferredVersion?: boolean;
|
||||
|
||||
@@ -133,10 +151,10 @@ export interface KubeApiResourceVersionList {
|
||||
|
||||
const not = <T>(fn: (val: T) => boolean) => (val: T) => !(fn(val));
|
||||
|
||||
const getOrderedVersions = (list: KubeApiResourceVersionList): KubeApiResourceVersion[] => [
|
||||
const getOrderedVersions = (list: KubeApiResourceVersionList, allowedUsableVersions: string[] | undefined): KubeApiResourceVersion[] => [
|
||||
list.preferredVersion,
|
||||
...list.versions.filter(not(matches(list.preferredVersion))),
|
||||
];
|
||||
].filter(({ version }) => !allowedUsableVersions || allowedUsableVersions.includes(version));
|
||||
|
||||
export type PropagationPolicy = undefined | "Orphan" | "Foreground" | "Background";
|
||||
|
||||
@@ -233,6 +251,7 @@ export class KubeApi<
|
||||
protected readonly doCheckPreferredVersion: boolean;
|
||||
protected readonly fullApiPathname: string;
|
||||
protected readonly fallbackApiBases: string[] | undefined;
|
||||
protected readonly allowedUsableVersions: Partial<Record<string, string[]>> | undefined;
|
||||
|
||||
constructor(protected readonly dependencies: KubeApiDependencies, opts: KubeApiOptions<Object, Data>) {
|
||||
const {
|
||||
@@ -243,6 +262,7 @@ export class KubeApi<
|
||||
apiBase: fullApiPathname = objectConstructor.apiBase,
|
||||
checkPreferredVersion: doCheckPreferredVersion = false,
|
||||
fallbackApiBases,
|
||||
allowedUsableVersions,
|
||||
} = opts;
|
||||
|
||||
assert(fullApiPathname, "apiBase MUST be provied either via KubeApiOptions.apiBase or KubeApiOptions.objectConstructor.apiBase");
|
||||
@@ -255,6 +275,7 @@ export class KubeApi<
|
||||
|
||||
this.doCheckPreferredVersion = doCheckPreferredVersion;
|
||||
this.fallbackApiBases = fallbackApiBases;
|
||||
this.allowedUsableVersions = allowedUsableVersions;
|
||||
this.fullApiPathname = fullApiPathname;
|
||||
this.kind = kind;
|
||||
this.isNamespaced = isNamespaced ?? objectConstructor.namespaced ?? false;
|
||||
@@ -291,7 +312,7 @@ export class KubeApi<
|
||||
try {
|
||||
const { apiPrefix, apiGroup, resource } = parseKubeApi(apiUrl);
|
||||
const list = await this.request.get(`${apiPrefix}/${apiGroup}`) as KubeApiResourceVersionList;
|
||||
const resourceVersions = getOrderedVersions(list);
|
||||
const resourceVersions = getOrderedVersions(list, this.allowedUsableVersions?.[apiGroup]);
|
||||
|
||||
for (const resourceVersion of resourceVersions) {
|
||||
const { resources } = await this.request.get(`${apiPrefix}/${resourceVersion.groupVersion}`) as KubeApiResourceList;
|
||||
@@ -313,8 +334,8 @@ export class KubeApi<
|
||||
}
|
||||
|
||||
protected async checkPreferredVersion() {
|
||||
if (this.fallbackApiBases && !this.doCheckPreferredVersion) {
|
||||
throw new Error("checkPreferredVersion must be enabled if fallbackApiBases is set in KubeApi");
|
||||
if (!this.doCheckPreferredVersion && (this.fallbackApiBases || this.allowedUsableVersions)) {
|
||||
throw new Error("checkPreferredVersion must be enabled if either fallbackApiBases or allowedUsableVersions are set in KubeApi");
|
||||
}
|
||||
|
||||
if (this.doCheckPreferredVersion && this.apiVersionPreferred === undefined) {
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
import type { JsonApiData, JsonApiError } from "./json-api";
|
||||
import { JsonApi } from "./json-api";
|
||||
import type { Response } from "node-fetch";
|
||||
import type { Response } from "@k8slens/node-fetch";
|
||||
import type { KubeJsonApiObjectMetadata } from "./kube-object";
|
||||
|
||||
export interface KubeJsonApiListMetadata {
|
||||
|
||||
@@ -12,7 +12,7 @@ import type { IKubeWatchEvent } from "./kube-watch-event";
|
||||
import { ItemStore } from "../item.store";
|
||||
import type { KubeApiQueryParams, KubeApi, KubeApiWatchCallback } from "./kube-api";
|
||||
import { parseKubeApi } from "./kube-api-parse";
|
||||
import type { RequestInit } from "node-fetch";
|
||||
import type { RequestInit } from "@k8slens/node-fetch";
|
||||
import type { Patch } from "rfc6902";
|
||||
import type { Logger } from "../logger";
|
||||
import assert from "assert";
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import type { AsyncResult } from "./async-result";
|
||||
import { delay } from "./delay";
|
||||
import { noop } from "./noop";
|
||||
|
||||
/**
|
||||
* @param error The error that resulted in the failure
|
||||
* @param attempt The 1-index attempt count
|
||||
*/
|
||||
export type OnIntermediateError<E> = (error: E, attempt: number) => void;
|
||||
|
||||
export interface BackoffCallerOptions<E> {
|
||||
/**
|
||||
* Called when an attempt fails
|
||||
*/
|
||||
onIntermediateError?: OnIntermediateError<E>;
|
||||
|
||||
/**
|
||||
* @default 5
|
||||
*/
|
||||
maxAttempts?: number;
|
||||
|
||||
/**
|
||||
* In miliseconds
|
||||
* @default 1000
|
||||
*/
|
||||
initialTimeout?: number;
|
||||
|
||||
/**
|
||||
* @default 2
|
||||
*/
|
||||
scaleFactor?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calls `fn` once and then again (with exponential delay between each attempt) up to `options.maxAttempts` times.
|
||||
* @param fn The function to repeatedly attempt
|
||||
* @returns The first success or the last failure
|
||||
*/
|
||||
export const backoffCaller = async <T, E, R extends AsyncResult<T, E>>(fn: () => Promise<R>, options?: BackoffCallerOptions<E>): Promise<R> => {
|
||||
const {
|
||||
initialTimeout = 1000,
|
||||
maxAttempts = 5,
|
||||
onIntermediateError = noop as OnIntermediateError<E>,
|
||||
scaleFactor = 2,
|
||||
} = options ?? {};
|
||||
|
||||
let timeout = initialTimeout;
|
||||
let attempt = 0;
|
||||
let result: R;
|
||||
|
||||
do {
|
||||
result = await fn();
|
||||
|
||||
if (result.callWasSuccessful) {
|
||||
return result;
|
||||
}
|
||||
|
||||
onIntermediateError(result.error, attempt + 1);
|
||||
|
||||
await delay(timeout);
|
||||
timeout *= scaleFactor;
|
||||
} while (attempt += 1, attempt < maxAttempts);
|
||||
|
||||
return result;
|
||||
};
|
||||
@@ -11,26 +11,17 @@ import isWindowsInjectable from "../../common/vars/is-windows.injectable";
|
||||
import { asLegacyGlobalFunctionForExtensionApi } from "../as-legacy-globals-for-extension-api/as-legacy-global-function-for-extension-api";
|
||||
import { getLegacyGlobalDiForExtensionApi } from "../as-legacy-globals-for-extension-api/legacy-global-di-for-extension-api";
|
||||
import getEnabledExtensionsInjectable from "./get-enabled-extensions/get-enabled-extensions.injectable";
|
||||
import type { UserPreferenceExtensionItems } from "./user-preferences";
|
||||
import { Preferences } from "./user-preferences";
|
||||
import { slackUrl, issuesTrackerUrl } from "../../common/vars";
|
||||
import { buildVersionInjectionToken } from "../../common/vars/build-semantic-version.injectable";
|
||||
import { asLegacyGlobalForExtensionApi } from "../as-legacy-globals-for-extension-api/as-legacy-global-object-for-extension-api";
|
||||
import userStoreInjectable from "../../common/user-store/user-store.injectable";
|
||||
|
||||
export interface AppExtensionItems {
|
||||
readonly Preferences: UserPreferenceExtensionItems;
|
||||
readonly version: string;
|
||||
readonly appName: string;
|
||||
readonly slackUrl: string;
|
||||
readonly issuesTrackerUrl: string;
|
||||
readonly isSnap: boolean;
|
||||
readonly isWindows: boolean;
|
||||
readonly isMac: boolean;
|
||||
readonly isLinux: boolean;
|
||||
getEnabledExtensions: () => string[];
|
||||
}
|
||||
const userStore = asLegacyGlobalForExtensionApi(userStoreInjectable);
|
||||
|
||||
export const App: AppExtensionItems = {
|
||||
Preferences,
|
||||
export const App = {
|
||||
Preferences: {
|
||||
getKubectlPath: () => userStore.kubectlBinariesPath,
|
||||
},
|
||||
getEnabledExtensions: asLegacyGlobalFunctionForExtensionApi(getEnabledExtensionsInjectable),
|
||||
get version() {
|
||||
const di = getLegacyGlobalDiForExtensionApi();
|
||||
@@ -64,4 +55,4 @@ export const App: AppExtensionItems = {
|
||||
},
|
||||
slackUrl,
|
||||
issuesTrackerUrl,
|
||||
};
|
||||
} as const;
|
||||
@@ -3,6 +3,7 @@
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import type { KubernetesClusterCategory } from "../../common/catalog-entities/kubernetes-cluster";
|
||||
import kubernetesClusterCategoryInjectable from "../../common/catalog/categories/kubernetes-cluster.injectable";
|
||||
import { asLegacyGlobalForExtensionApi } from "../as-legacy-globals-for-extension-api/as-legacy-global-object-for-extension-api";
|
||||
|
||||
@@ -12,6 +13,10 @@ export {
|
||||
WebLink,
|
||||
} from "../../common/catalog-entities";
|
||||
|
||||
export type {
|
||||
KubernetesClusterCategory,
|
||||
};
|
||||
|
||||
export const kubernetesClusterCategory = asLegacyGlobalForExtensionApi(kubernetesClusterCategoryInjectable);
|
||||
|
||||
export type {
|
||||
@@ -23,6 +28,7 @@ export type {
|
||||
WebLinkStatusPhase,
|
||||
KubernetesClusterStatusPhase,
|
||||
KubernetesClusterStatus,
|
||||
GeneralEntitySpec,
|
||||
} from "../../common/catalog-entities";
|
||||
|
||||
export * from "../../common/catalog/catalog-entity";
|
||||
@@ -5,7 +5,14 @@
|
||||
|
||||
import appEventBusInjectable from "../../common/app-event-bus/app-event-bus.injectable";
|
||||
import { asLegacyGlobalForExtensionApi } from "../as-legacy-globals-for-extension-api/as-legacy-global-object-for-extension-api";
|
||||
import type { AppEvent } from "../../common/app-event-bus/event-bus";
|
||||
import type { EventEmitter, EventEmitterCallback, EventEmitterOptions } from "../../common/event-emitter";
|
||||
|
||||
export type { AppEvent } from "../../common/app-event-bus/event-bus";
|
||||
export type {
|
||||
AppEvent,
|
||||
EventEmitter,
|
||||
EventEmitterCallback,
|
||||
EventEmitterOptions,
|
||||
};
|
||||
|
||||
export const appEventBus = asLegacyGlobalForExtensionApi(appEventBusInjectable);
|
||||
@@ -13,6 +13,8 @@ import * as Types from "./types";
|
||||
import * as Proxy from "./proxy";
|
||||
import loggerInjectable from "../../common/logger.injectable";
|
||||
import { asLegacyGlobalForExtensionApi } from "../as-legacy-globals-for-extension-api/as-legacy-global-object-for-extension-api";
|
||||
import type { Logger } from "../../common/logger";
|
||||
import type { LensExtension, LensExtensionManifest } from "../lens-extension";
|
||||
|
||||
const logger = asLegacyGlobalForExtensionApi(loggerInjectable);
|
||||
|
||||
@@ -25,4 +27,7 @@ export {
|
||||
Util,
|
||||
logger,
|
||||
Proxy,
|
||||
Logger,
|
||||
LensExtension,
|
||||
LensExtensionManifest,
|
||||
};
|
||||
@@ -30,7 +30,7 @@ import { storesAndApisCanBeCreatedInjectionToken } from "../../common/k8s-api/st
|
||||
import type { JsonApiConfig } from "../../common/k8s-api/json-api";
|
||||
import type { KubeJsonApi as InternalKubeJsonApi } from "../../common/k8s-api/kube-json-api";
|
||||
import createKubeJsonApiInjectable from "../../common/k8s-api/create-kube-json-api.injectable";
|
||||
import type { RequestInit } from "node-fetch";
|
||||
import type { RequestInit } from "@k8slens/node-fetch";
|
||||
import createKubeJsonApiForClusterInjectable from "../../common/k8s-api/create-kube-json-api-for-cluster.injectable";
|
||||
|
||||
export const apiManager = asLegacyGlobalForExtensionApi(apiManagerInjectable);
|
||||
|
||||
@@ -3,4 +3,10 @@
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
export { ExtensionStore } from "../extension-store";
|
||||
import type { BaseStoreParams } from "../../common/base-store/base-store";
|
||||
import { ExtensionStore } from "../extension-store";
|
||||
|
||||
export {
|
||||
BaseStoreParams,
|
||||
ExtensionStore,
|
||||
};
|
||||
@@ -1,19 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
|
||||
import userStoreInjectable from "../../common/user-store/user-store.injectable";
|
||||
import { asLegacyGlobalForExtensionApi } from "../as-legacy-globals-for-extension-api/as-legacy-global-object-for-extension-api";
|
||||
export interface UserPreferenceExtensionItems {
|
||||
/**
|
||||
* Get the configured kubectl binaries path.
|
||||
*/
|
||||
getKubectlPath: () => string | undefined;
|
||||
}
|
||||
|
||||
const userStore = asLegacyGlobalForExtensionApi(userStoreInjectable);
|
||||
|
||||
export const Preferences: UserPreferenceExtensionItems = {
|
||||
getKubectlPath: () => userStore.kubectlBinariesPath,
|
||||
};
|
||||
@@ -9,20 +9,9 @@ import { asLegacyGlobalFunctionForExtensionApi } from "../as-legacy-globals-for-
|
||||
import { getLegacyGlobalDiForExtensionApi } from "../as-legacy-globals-for-extension-api/legacy-global-di-for-extension-api";
|
||||
import { Singleton } from "../../common/utils";
|
||||
import { prevDefault, stopPropagation } from "../../renderer/utils/prevDefault";
|
||||
import type { IClassName } from "../../renderer/utils/cssNames";
|
||||
import { cssNames } from "../../renderer/utils/cssNames";
|
||||
|
||||
export interface UtilsExtensionItems {
|
||||
Singleton: typeof Singleton;
|
||||
prevDefault: <E extends React.SyntheticEvent | Event, R>(callback: (evt: E) => R) => (evt: E) => R;
|
||||
stopPropagation: (evt: Event | React.SyntheticEvent) => void;
|
||||
cssNames: (...classNames: IClassName[]) => string;
|
||||
openExternal: (url: string) => Promise<void>;
|
||||
openBrowser: (url: string) => Promise<void>;
|
||||
getAppVersion: () => string;
|
||||
}
|
||||
|
||||
export const Util: UtilsExtensionItems = {
|
||||
export const Util = {
|
||||
Singleton,
|
||||
prevDefault,
|
||||
stopPropagation,
|
||||
@@ -34,4 +23,4 @@ export const Util: UtilsExtensionItems = {
|
||||
|
||||
return di.inject(buildVersionInjectable).get();
|
||||
},
|
||||
};
|
||||
} as const;
|
||||
@@ -32,7 +32,12 @@ export interface LensExtensionManifest extends PackageJson {
|
||||
export const lensExtensionDependencies = Symbol("lens-extension-dependencies");
|
||||
export const Disposers = Symbol("disposers");
|
||||
|
||||
export class LensExtension<Dependencies extends LensExtensionDependencies = LensExtensionDependencies> {
|
||||
export class LensExtension<
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
Dependencies extends LensExtensionDependencies = LensExtensionDependencies,
|
||||
> {
|
||||
readonly id: LensExtensionId;
|
||||
readonly manifest: LensExtensionManifest;
|
||||
readonly manifestPath: string;
|
||||
@@ -50,6 +55,9 @@ export class LensExtension<Dependencies extends LensExtensionDependencies = Lens
|
||||
return this._isEnabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
[Disposers] = disposer();
|
||||
|
||||
constructor({ id, manifest, manifestPath, isBundled }: InstalledExtension) {
|
||||
@@ -72,6 +80,9 @@ export class LensExtension<Dependencies extends LensExtensionDependencies = Lens
|
||||
return this.manifest.description;
|
||||
}
|
||||
|
||||
/**
|
||||
* @ignore
|
||||
*/
|
||||
readonly [lensExtensionDependencies]!: Dependencies;
|
||||
|
||||
/**
|
||||
|
||||
@@ -200,34 +200,34 @@ describe("kube auth proxy tests", () => {
|
||||
await proxy.run();
|
||||
listeners.emit("error", { message: "foobarbat" });
|
||||
|
||||
expect(broadcastMessageMock).toBeCalledWith("cluster:foobar:connection-update", { message: "foobarbat", isError: true });
|
||||
expect(broadcastMessageMock).toBeCalledWith("cluster:foobar:connection-update", { message: "foobarbat", level: "error" });
|
||||
});
|
||||
|
||||
it("should call spawn and broadcast exit", async () => {
|
||||
await proxy.run();
|
||||
listeners.emit("exit", 0);
|
||||
|
||||
expect(broadcastMessageMock).toBeCalledWith("cluster:foobar:connection-update", { message: "proxy exited with code: 0", isError: false });
|
||||
expect(broadcastMessageMock).toBeCalledWith("cluster:foobar:connection-update", { message: "proxy exited with code: 0", level: "info" });
|
||||
});
|
||||
|
||||
it("should call spawn and broadcast errors from stderr", async () => {
|
||||
await proxy.run();
|
||||
listeners.emit("stderr/data", "an error");
|
||||
|
||||
expect(broadcastMessageMock).toBeCalledWith("cluster:foobar:connection-update", { message: "an error", isError: true });
|
||||
expect(broadcastMessageMock).toBeCalledWith("cluster:foobar:connection-update", { message: "an error", level: "error" });
|
||||
});
|
||||
|
||||
it("should call spawn and broadcast stdout serving info", async () => {
|
||||
await proxy.run();
|
||||
|
||||
expect(broadcastMessageMock).toBeCalledWith("cluster:foobar:connection-update", { message: "Authentication proxy started", isError: false });
|
||||
expect(broadcastMessageMock).toBeCalledWith("cluster:foobar:connection-update", { message: "Authentication proxy started", level: "info" });
|
||||
});
|
||||
|
||||
it("should call spawn and broadcast stdout other info", async () => {
|
||||
await proxy.run();
|
||||
listeners.emit("stdout/data", "some info");
|
||||
|
||||
expect(broadcastMessageMock).toBeCalledWith("cluster:foobar:connection-update", { message: "some info", isError: false });
|
||||
expect(broadcastMessageMock).toBeCalledWith("cluster:foobar:connection-update", { message: "some info", level: "info" });
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -10,8 +10,10 @@ import type { Cluster } from "../../common/cluster/cluster";
|
||||
import { requestApiVersionsInjectionToken } from "./request-api-versions";
|
||||
import { withConcurrencyLimit } from "../../common/utils/with-concurrency-limit";
|
||||
import requestKubeApiResourcesForInjectable from "./request-kube-api-resources-for.injectable";
|
||||
import type { AsyncResult } from "../../common/utils/async-result";
|
||||
import { backoffCaller } from "../../common/utils/backoff-caller";
|
||||
|
||||
export type RequestApiResources = (cluster: Cluster) => Promise<KubeApiResource[]>;
|
||||
export type RequestApiResources = (cluster: Cluster) => Promise<AsyncResult<KubeApiResource[], Error>>;
|
||||
|
||||
export interface KubeResourceListGroup {
|
||||
group: string;
|
||||
@@ -25,23 +27,46 @@ const requestApiResourcesInjectable = getInjectable({
|
||||
const apiVersionRequesters = di.injectMany(requestApiVersionsInjectionToken);
|
||||
const requestKubeApiResourcesFor = di.inject(requestKubeApiResourcesForInjectable);
|
||||
|
||||
return async (cluster) => {
|
||||
return async (...args) => {
|
||||
const [cluster] = args;
|
||||
const requestKubeApiResources = withConcurrencyLimit(5)(requestKubeApiResourcesFor(cluster));
|
||||
|
||||
try {
|
||||
const requests = await Promise.all(apiVersionRequesters.map(fn => fn(cluster)));
|
||||
const resources = await Promise.all((
|
||||
requests
|
||||
.flat()
|
||||
.map(requestKubeApiResources)
|
||||
));
|
||||
const groupLists: KubeResourceListGroup[] = [];
|
||||
|
||||
return resources.flat();
|
||||
} catch (error) {
|
||||
logger.error(`[LIST-API-RESOURCES]: failed to list api resources: ${error}`);
|
||||
for (const apiVersionRequester of apiVersionRequesters) {
|
||||
const result = await backoffCaller(() => apiVersionRequester(cluster), {
|
||||
onIntermediateError: (error, attempt) => {
|
||||
cluster.broadcastConnectUpdate(`Failed to list kube API resource kinds, attempt ${attempt}: ${error}`, "warning");
|
||||
logger.warn(`[LIST-API-RESOURCES]: failed to list kube api resources: ${error}`, { attempt, clusterId: cluster.id });
|
||||
},
|
||||
});
|
||||
|
||||
return [];
|
||||
if (!result.callWasSuccessful) {
|
||||
return result;
|
||||
}
|
||||
|
||||
groupLists.push(...result.response);
|
||||
}
|
||||
|
||||
const apiResourceRequests = groupLists.map(async listGroup => (
|
||||
Object.assign(await requestKubeApiResources(listGroup), { listGroup })
|
||||
));
|
||||
const results = await Promise.all(apiResourceRequests);
|
||||
const resources: KubeApiResource[] = [];
|
||||
|
||||
for (const result of results) {
|
||||
if (!result.callWasSuccessful) {
|
||||
cluster.broadcastConnectUpdate(`Kube APIs under "${result.listGroup.path}" may not be displayed`, "warning");
|
||||
continue;
|
||||
}
|
||||
|
||||
resources.push(...result.response);
|
||||
}
|
||||
|
||||
return {
|
||||
callWasSuccessful: true,
|
||||
response: resources,
|
||||
};
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
@@ -5,13 +5,14 @@
|
||||
|
||||
import { getInjectionToken } from "@ogre-tools/injectable";
|
||||
import type { Cluster } from "../../common/cluster/cluster";
|
||||
import type { AsyncResult } from "../../common/utils/async-result";
|
||||
|
||||
export interface KubeResourceListGroup {
|
||||
group: string;
|
||||
path: string;
|
||||
}
|
||||
|
||||
export type RequestApiVersions = (cluster: Cluster) => Promise<KubeResourceListGroup[]>;
|
||||
export type RequestApiVersions = (cluster: Cluster) => Promise<AsyncResult<KubeResourceListGroup[], Error>>;
|
||||
|
||||
export const requestApiVersionsInjectionToken = getInjectionToken<RequestApiVersions>({
|
||||
id: "request-api-versions-token",
|
||||
|
||||
@@ -13,12 +13,22 @@ const requestCoreApiVersionsInjectable = getInjectable({
|
||||
const k8sRequest = di.inject(k8sRequestInjectable);
|
||||
|
||||
return async (cluster) => {
|
||||
const { versions } = await k8sRequest(cluster, "/api") as V1APIVersions;
|
||||
try {
|
||||
const { versions } = await k8sRequest(cluster, "/api") as V1APIVersions;
|
||||
|
||||
return versions.map(version => ({
|
||||
group: "",
|
||||
path: `/api/${version}`,
|
||||
}));
|
||||
return {
|
||||
callWasSuccessful: true,
|
||||
response: versions.map(version => ({
|
||||
group: "",
|
||||
path: `/api/${version}`,
|
||||
})),
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
callWasSuccessful: false,
|
||||
error: error as Error,
|
||||
};
|
||||
}
|
||||
};
|
||||
},
|
||||
injectionToken: requestApiVersionsInjectionToken,
|
||||
|
||||
@@ -6,10 +6,11 @@ import type { V1APIResourceList } from "@kubernetes/client-node";
|
||||
import { getInjectable } from "@ogre-tools/injectable";
|
||||
import type { Cluster } from "../../common/cluster/cluster";
|
||||
import type { KubeApiResource } from "../../common/rbac";
|
||||
import type { AsyncResult } from "../../common/utils/async-result";
|
||||
import k8sRequestInjectable from "../k8s-request.injectable";
|
||||
import type { KubeResourceListGroup } from "./request-api-versions";
|
||||
|
||||
export type RequestKubeApiResources = (grouping: KubeResourceListGroup) => Promise<KubeApiResource[]>;
|
||||
export type RequestKubeApiResources = (grouping: KubeResourceListGroup) => Promise<AsyncResult<KubeApiResource[], Error>>;
|
||||
|
||||
export type RequestKubeApiResourcesFor = (cluster: Cluster) => RequestKubeApiResources;
|
||||
|
||||
@@ -19,14 +20,24 @@ const requestKubeApiResourcesForInjectable = getInjectable({
|
||||
const k8sRequest = di.inject(k8sRequestInjectable);
|
||||
|
||||
return (cluster) => async ({ group, path }) => {
|
||||
const { resources } = await k8sRequest(cluster, path) as V1APIResourceList;
|
||||
try {
|
||||
const { resources } = await k8sRequest(cluster, path) as V1APIResourceList;
|
||||
|
||||
return resources.map(resource => ({
|
||||
apiName: resource.name,
|
||||
kind: resource.kind,
|
||||
group,
|
||||
namespaced: resource.namespaced,
|
||||
}));
|
||||
return {
|
||||
callWasSuccessful: true,
|
||||
response: resources.map(resource => ({
|
||||
apiName: resource.name,
|
||||
kind: resource.kind,
|
||||
group,
|
||||
namespaced: resource.namespaced,
|
||||
})),
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
callWasSuccessful: false,
|
||||
error: error as Error,
|
||||
};
|
||||
}
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
@@ -14,14 +14,24 @@ const requestNonCoreApiVersionsInjectable = getInjectable({
|
||||
const k8sRequest = di.inject(k8sRequestInjectable);
|
||||
|
||||
return async (cluster) => {
|
||||
const { groups } = await k8sRequest(cluster, "/apis") as V1APIGroupList;
|
||||
try {
|
||||
const { groups } = await k8sRequest(cluster, "/apis") as V1APIGroupList;
|
||||
|
||||
return chain(groups.values())
|
||||
.filterMap(group => group.preferredVersion?.groupVersion && ({
|
||||
group: group.name,
|
||||
path: `/apis/${group.preferredVersion.groupVersion}`,
|
||||
}))
|
||||
.collect(v => [...v]);
|
||||
return {
|
||||
callWasSuccessful: true,
|
||||
response: chain(groups.values())
|
||||
.filterMap(group => group.preferredVersion?.groupVersion && ({
|
||||
group: group.name,
|
||||
path: `/apis/${group.preferredVersion.groupVersion}`,
|
||||
}))
|
||||
.collect(v => [...v]),
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
callWasSuccessful: false,
|
||||
error: error as Error,
|
||||
};
|
||||
}
|
||||
};
|
||||
},
|
||||
injectionToken: requestApiVersionsInjectionToken,
|
||||
|
||||
@@ -19,6 +19,10 @@ const LensExtensions = {
|
||||
Main: LensExtensionsMainApi,
|
||||
};
|
||||
|
||||
export type {
|
||||
LensExtensionsMainApi,
|
||||
};
|
||||
|
||||
const Pty = {
|
||||
spawn,
|
||||
};
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
*/
|
||||
import { getInjectable } from "@ogre-tools/injectable";
|
||||
import type { Cluster } from "../common/cluster/cluster";
|
||||
import nodeFetchModuleInjectable from "../common/fetch/fetch-module.injectable";
|
||||
import { FormData } from "@k8slens/node-fetch";
|
||||
import type { RequestMetricsParams } from "../common/k8s-api/endpoints/metrics.api/request-metrics.injectable";
|
||||
import { object } from "../common/utils";
|
||||
import k8sRequestInjectable from "./k8s-request.injectable";
|
||||
@@ -16,7 +16,6 @@ const getMetricsInjectable = getInjectable({
|
||||
|
||||
instantiate: (di): GetMetrics => {
|
||||
const k8sRequest = di.inject(k8sRequestInjectable);
|
||||
const { FormData } = di.inject(nodeFetchModuleInjectable);
|
||||
|
||||
return async (
|
||||
cluster,
|
||||
|
||||
@@ -71,17 +71,17 @@ export class KubeAuthProxy {
|
||||
},
|
||||
});
|
||||
this.proxyProcess.on("error", (error) => {
|
||||
this.cluster.broadcastConnectUpdate(error.message, true);
|
||||
this.cluster.broadcastConnectUpdate(error.message, "error");
|
||||
this.exit();
|
||||
});
|
||||
|
||||
this.proxyProcess.on("exit", (code) => {
|
||||
this.cluster.broadcastConnectUpdate(`proxy exited with code: ${code}`, code ? code > 0: false);
|
||||
this.cluster.broadcastConnectUpdate(`proxy exited with code: ${code}`, code ? "error" : "info");
|
||||
this.exit();
|
||||
});
|
||||
|
||||
this.proxyProcess.on("disconnect", () => {
|
||||
this.cluster.broadcastConnectUpdate("Proxy disconnected communications", true );
|
||||
this.cluster.broadcastConnectUpdate("Proxy disconnected communications", "error");
|
||||
this.exit();
|
||||
});
|
||||
|
||||
@@ -93,7 +93,7 @@ export class KubeAuthProxy {
|
||||
return;
|
||||
}
|
||||
|
||||
this.cluster.broadcastConnectUpdate(data.toString(), true);
|
||||
this.cluster.broadcastConnectUpdate(data.toString(), "error");
|
||||
});
|
||||
|
||||
this.proxyProcess.stdout.on("data", (data: Buffer) => {
|
||||
@@ -114,7 +114,7 @@ export class KubeAuthProxy {
|
||||
this.ready = true;
|
||||
} catch (error) {
|
||||
this.dependencies.logger.warn("[KUBE-AUTH-PROXY]: waitUntilUsed failed", error);
|
||||
this.cluster.broadcastConnectUpdate("Proxy port failed to be used within timelimit, restarting...", true);
|
||||
this.cluster.broadcastConnectUpdate("Proxy port failed to be used within timelimit, restarting...", "error");
|
||||
this.exit();
|
||||
|
||||
return this.run();
|
||||
|
||||
@@ -11,7 +11,7 @@ import * as extensionApi from "./extension-api";
|
||||
import { createApp } from "./create-app";
|
||||
|
||||
// @experimental
|
||||
export {
|
||||
export {
|
||||
createApp,
|
||||
extensionApi,
|
||||
afterApplicationIsLoadedInjectionToken,
|
||||
|
||||
+326
@@ -0,0 +1,326 @@
|
||||
// Jest Snapshot v1, https://goo.gl/fbAQLP
|
||||
|
||||
exports[`<HpaDetails/> renders 1`] = `
|
||||
<body>
|
||||
<div>
|
||||
<div
|
||||
class="HpaDetails"
|
||||
>
|
||||
<div
|
||||
class="DrawerItem"
|
||||
>
|
||||
<span
|
||||
class="name"
|
||||
>
|
||||
Reference
|
||||
</span>
|
||||
<span
|
||||
class="value"
|
||||
>
|
||||
Deployment
|
||||
/
|
||||
hpav2deployment
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
class="DrawerItem"
|
||||
>
|
||||
<span
|
||||
class="name"
|
||||
>
|
||||
Min Pods
|
||||
</span>
|
||||
<span
|
||||
class="value"
|
||||
>
|
||||
0
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
class="DrawerItem"
|
||||
>
|
||||
<span
|
||||
class="name"
|
||||
>
|
||||
Max Pods
|
||||
</span>
|
||||
<span
|
||||
class="value"
|
||||
>
|
||||
10
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
class="DrawerItem"
|
||||
>
|
||||
<span
|
||||
class="name"
|
||||
>
|
||||
Replicas
|
||||
</span>
|
||||
<span
|
||||
class="value"
|
||||
>
|
||||
0
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
class="DrawerItem status labelsOnly"
|
||||
>
|
||||
<span
|
||||
class="name"
|
||||
>
|
||||
Status
|
||||
</span>
|
||||
<span
|
||||
class="value"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
`;
|
||||
|
||||
exports[`<HpaDetails/> shows unknown metrics with lack of metric type 1`] = `
|
||||
<body>
|
||||
<div>
|
||||
<div
|
||||
class="HpaDetails"
|
||||
>
|
||||
<div
|
||||
class="DrawerItem"
|
||||
>
|
||||
<span
|
||||
class="name"
|
||||
>
|
||||
Reference
|
||||
</span>
|
||||
<span
|
||||
class="value"
|
||||
>
|
||||
Deployment
|
||||
/
|
||||
hpav2deployment
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
class="DrawerItem"
|
||||
>
|
||||
<span
|
||||
class="name"
|
||||
>
|
||||
Min Pods
|
||||
</span>
|
||||
<span
|
||||
class="value"
|
||||
>
|
||||
0
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
class="DrawerItem"
|
||||
>
|
||||
<span
|
||||
class="name"
|
||||
>
|
||||
Max Pods
|
||||
</span>
|
||||
<span
|
||||
class="value"
|
||||
>
|
||||
10
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
class="DrawerItem"
|
||||
>
|
||||
<span
|
||||
class="name"
|
||||
>
|
||||
Replicas
|
||||
</span>
|
||||
<span
|
||||
class="value"
|
||||
>
|
||||
0
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
class="DrawerItem status labelsOnly"
|
||||
>
|
||||
<span
|
||||
class="name"
|
||||
>
|
||||
Status
|
||||
</span>
|
||||
<span
|
||||
class="value"
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
class="DrawerTitle title"
|
||||
>
|
||||
Metrics
|
||||
</div>
|
||||
<div
|
||||
class="metrics"
|
||||
>
|
||||
<div
|
||||
class="Table flex column scrollable autoSize"
|
||||
>
|
||||
<div
|
||||
class="TableHead sticky flat"
|
||||
>
|
||||
<div
|
||||
class="TableCell name"
|
||||
>
|
||||
Name
|
||||
</div>
|
||||
<div
|
||||
class="TableCell metrics"
|
||||
>
|
||||
Current / Target
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
class="TableRow"
|
||||
>
|
||||
<div
|
||||
class="TableCell name"
|
||||
>
|
||||
unknown
|
||||
</div>
|
||||
<div
|
||||
class="TableCell metrics"
|
||||
>
|
||||
unknown / unknown
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
`;
|
||||
|
||||
exports[`<HpaDetails/> shows unknown metrics with with unusual type 1`] = `
|
||||
<body>
|
||||
<div>
|
||||
<div
|
||||
class="HpaDetails"
|
||||
>
|
||||
<div
|
||||
class="DrawerItem"
|
||||
>
|
||||
<span
|
||||
class="name"
|
||||
>
|
||||
Reference
|
||||
</span>
|
||||
<span
|
||||
class="value"
|
||||
>
|
||||
Deployment
|
||||
/
|
||||
hpav2deployment
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
class="DrawerItem"
|
||||
>
|
||||
<span
|
||||
class="name"
|
||||
>
|
||||
Min Pods
|
||||
</span>
|
||||
<span
|
||||
class="value"
|
||||
>
|
||||
0
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
class="DrawerItem"
|
||||
>
|
||||
<span
|
||||
class="name"
|
||||
>
|
||||
Max Pods
|
||||
</span>
|
||||
<span
|
||||
class="value"
|
||||
>
|
||||
10
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
class="DrawerItem"
|
||||
>
|
||||
<span
|
||||
class="name"
|
||||
>
|
||||
Replicas
|
||||
</span>
|
||||
<span
|
||||
class="value"
|
||||
>
|
||||
0
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
class="DrawerItem status labelsOnly"
|
||||
>
|
||||
<span
|
||||
class="name"
|
||||
>
|
||||
Status
|
||||
</span>
|
||||
<span
|
||||
class="value"
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
class="DrawerTitle title"
|
||||
>
|
||||
Metrics
|
||||
</div>
|
||||
<div
|
||||
class="metrics"
|
||||
>
|
||||
<div
|
||||
class="Table flex column scrollable autoSize"
|
||||
>
|
||||
<div
|
||||
class="TableHead sticky flat"
|
||||
>
|
||||
<div
|
||||
class="TableCell name"
|
||||
>
|
||||
Name
|
||||
</div>
|
||||
<div
|
||||
class="TableCell metrics"
|
||||
>
|
||||
Current / Target
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
class="TableRow"
|
||||
>
|
||||
<div
|
||||
class="TableCell name"
|
||||
>
|
||||
unknown
|
||||
</div>
|
||||
<div
|
||||
class="TableCell metrics"
|
||||
>
|
||||
unknown / unknown
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
`;
|
||||
@@ -19,8 +19,8 @@ interface Metric extends MetricNames {
|
||||
type: HpaMetricType;
|
||||
}
|
||||
|
||||
export function getMetricName(metric: Metric): string | undefined {
|
||||
switch (metric.type) {
|
||||
export function getMetricName(metric: Metric | undefined): string | undefined {
|
||||
switch (metric?.type) {
|
||||
case HpaMetricType.Resource:
|
||||
return metric.resource?.name;
|
||||
case HpaMetricType.Pods:
|
||||
|
||||
@@ -0,0 +1,392 @@
|
||||
/**
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
import type { RenderResult } from "@testing-library/react";
|
||||
import React from "react";
|
||||
import { HorizontalPodAutoscaler, HpaMetricType } from "../../../common/k8s-api/endpoints";
|
||||
import { getDiForUnitTesting } from "../../getDiForUnitTesting";
|
||||
import type { DiRender } from "../test-utils/renderFor";
|
||||
import { renderFor } from "../test-utils/renderFor";
|
||||
import { HpaDetails } from "./hpa-details";
|
||||
|
||||
jest.mock("react-router-dom", () => ({
|
||||
Link: ({ children }: { children: React.ReactNode }) => children,
|
||||
}));
|
||||
|
||||
const hpaV2 = {
|
||||
apiVersion: "autoscaling/v2",
|
||||
kind: "HorizontalPodAutoscaler",
|
||||
metadata: {
|
||||
name: "hpav2",
|
||||
resourceVersion: "1",
|
||||
uid: "hpav2",
|
||||
namespace: "default",
|
||||
selfLink: "/apis/autoscaling/v2/namespaces/default/horizontalpodautoscalers/hpav2",
|
||||
},
|
||||
spec: {
|
||||
maxReplicas: 10,
|
||||
scaleTargetRef: {
|
||||
kind: "Deployment",
|
||||
name: "hpav2deployment",
|
||||
apiVersion: "apps/v1",
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
describe("<HpaDetails/>", () => {
|
||||
let result: RenderResult;
|
||||
let render: DiRender;
|
||||
|
||||
beforeEach(() => {
|
||||
const di = getDiForUnitTesting({ doGeneralOverrides: true });
|
||||
|
||||
render = renderFor(di);
|
||||
});
|
||||
|
||||
it("renders", () => {
|
||||
const hpa = new HorizontalPodAutoscaler(hpaV2);
|
||||
|
||||
result = render(
|
||||
<HpaDetails object={hpa} />,
|
||||
);
|
||||
|
||||
expect(result.baseElement).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it("does not show metrics table if no metrics found", () => {
|
||||
const hpa = new HorizontalPodAutoscaler(hpaV2);
|
||||
|
||||
result = render(
|
||||
<HpaDetails object={hpa} />,
|
||||
);
|
||||
|
||||
expect(result.queryByTestId("hpa-metrics")).toBeNull();
|
||||
});
|
||||
|
||||
it("shows proper metric name for autoscaling/v1", () => {
|
||||
const hpa = new HorizontalPodAutoscaler({
|
||||
apiVersion: "autoscaling/v1",
|
||||
kind: "HorizontalPodAutoscaler",
|
||||
metadata: {
|
||||
name: "hpav1",
|
||||
resourceVersion: "1",
|
||||
uid: "hpav1",
|
||||
namespace: "default",
|
||||
selfLink: "/apis/autoscaling/v1/namespaces/default/horizontalpodautoscalers/hpav1",
|
||||
},
|
||||
spec: {
|
||||
maxReplicas: 10,
|
||||
scaleTargetRef: {
|
||||
kind: "Deployment",
|
||||
name: "hpav1deployment",
|
||||
apiVersion: "apps/v1",
|
||||
},
|
||||
targetCPUUtilizationPercentage: 80,
|
||||
},
|
||||
});
|
||||
|
||||
result = render(
|
||||
<HpaDetails object={hpa} />,
|
||||
);
|
||||
|
||||
expect(result.getByText("CPU Utilization percentage")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows proper metric name for container resource metrics", () => {
|
||||
const hpa = new HorizontalPodAutoscaler(
|
||||
{
|
||||
...hpaV2,
|
||||
spec: {
|
||||
...hpaV2.spec,
|
||||
metrics: [
|
||||
{
|
||||
type: HpaMetricType.ContainerResource,
|
||||
containerResource: {
|
||||
name: "cpu",
|
||||
container: "nginx",
|
||||
target: {
|
||||
type: "Utilization",
|
||||
averageUtilization: 60,
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
result = render(
|
||||
<HpaDetails object={hpa} />,
|
||||
);
|
||||
|
||||
expect(result.getByText("Resource cpu on Pods")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows proper metric name for resource metrics", () => {
|
||||
const hpa = new HorizontalPodAutoscaler(
|
||||
{
|
||||
...hpaV2,
|
||||
spec: {
|
||||
...hpaV2.spec,
|
||||
metrics: [
|
||||
{
|
||||
type: HpaMetricType.Resource,
|
||||
resource: {
|
||||
name: "cpu",
|
||||
target: {
|
||||
type: "Utilization",
|
||||
averageUtilization: 50,
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
result = render(
|
||||
<HpaDetails object={hpa} />,
|
||||
);
|
||||
|
||||
expect(result.getByText("Resource cpu on Pods")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows proper metric name for pod metrics for hpa v2", () => {
|
||||
const hpa = new HorizontalPodAutoscaler(
|
||||
{
|
||||
...hpaV2,
|
||||
spec: {
|
||||
...hpaV2.spec,
|
||||
metrics: [
|
||||
{
|
||||
type: HpaMetricType.Pods,
|
||||
pods: {
|
||||
metric: {
|
||||
name: "packets-per-second",
|
||||
},
|
||||
target: {
|
||||
type: "AverageValue",
|
||||
averageValue: "1k",
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
result = render(
|
||||
<HpaDetails object={hpa} />,
|
||||
);
|
||||
|
||||
expect(result.getByText("packets-per-second on Pods")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows proper metric name for pod metrics for hpa v2beta1", () => {
|
||||
const hpa = new HorizontalPodAutoscaler(
|
||||
{
|
||||
...hpaV2,
|
||||
spec: {
|
||||
...hpaV2.spec,
|
||||
metrics: [
|
||||
{
|
||||
type: HpaMetricType.Pods,
|
||||
pods: {
|
||||
metricName: "packets-per-second",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
result = render(
|
||||
<HpaDetails object={hpa} />,
|
||||
);
|
||||
|
||||
expect(result.getByText("packets-per-second on Pods")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows proper metric name for object metrics for hpa v2", () => {
|
||||
const hpa = new HorizontalPodAutoscaler(
|
||||
{
|
||||
...hpaV2,
|
||||
spec: {
|
||||
...hpaV2.spec,
|
||||
metrics: [
|
||||
{
|
||||
type: HpaMetricType.Object,
|
||||
object: {
|
||||
metric: {
|
||||
name: "requests-per-second",
|
||||
},
|
||||
target: {
|
||||
type: "Value",
|
||||
value: "10k",
|
||||
},
|
||||
describedObject: {
|
||||
kind: "Service",
|
||||
name: "nginx",
|
||||
apiVersion: "v1",
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
result = render(
|
||||
<HpaDetails object={hpa} />,
|
||||
);
|
||||
|
||||
expect(result.getByText(/requests-per-second/)).toHaveTextContent("requests-per-second onService/nginx");
|
||||
});
|
||||
|
||||
it("shows proper metric name for object metrics for hpa v2beta1", () => {
|
||||
const hpa = new HorizontalPodAutoscaler(
|
||||
{
|
||||
...hpaV2,
|
||||
spec: {
|
||||
...hpaV2.spec,
|
||||
metrics: [
|
||||
{
|
||||
type: HpaMetricType.Object,
|
||||
object: {
|
||||
metricName: "requests-per-second",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
result = render(
|
||||
<HpaDetails object={hpa} />,
|
||||
);
|
||||
|
||||
expect(result.getByText("requests-per-second")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows proper metric name for external metrics for hpa v2", () => {
|
||||
const hpa = new HorizontalPodAutoscaler(
|
||||
{
|
||||
...hpaV2,
|
||||
spec: {
|
||||
...hpaV2.spec,
|
||||
metrics: [
|
||||
{
|
||||
type: HpaMetricType.External,
|
||||
external: {
|
||||
metric: {
|
||||
name: "queue_messages_ready",
|
||||
selector: {
|
||||
matchLabels: { queue: "worker_tasks" },
|
||||
},
|
||||
},
|
||||
target: {
|
||||
type: "AverageValue",
|
||||
averageValue: "30",
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
result = render(
|
||||
<HpaDetails object={hpa} />,
|
||||
);
|
||||
|
||||
expect(result.getByText("queue_messages_ready on {\"matchLabels\":{\"queue\":\"worker_tasks\"}}")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows proper metric name for external metrics for hpa v2beta1", () => {
|
||||
const hpa = new HorizontalPodAutoscaler(
|
||||
{
|
||||
...hpaV2,
|
||||
spec: {
|
||||
...hpaV2.spec,
|
||||
metrics: [
|
||||
{
|
||||
type: HpaMetricType.External,
|
||||
external: {
|
||||
metricName: "queue_messages_ready",
|
||||
metricSelector: {
|
||||
matchLabels: { queue: "worker_tasks" },
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
result = render(
|
||||
<HpaDetails object={hpa} />,
|
||||
);
|
||||
|
||||
expect(result.getByText("queue_messages_ready on {\"matchLabels\":{\"queue\":\"worker_tasks\"}}")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("shows unknown metrics with lack of metric type", () => {
|
||||
const hpa = new HorizontalPodAutoscaler(
|
||||
{
|
||||
...hpaV2,
|
||||
spec: {
|
||||
...hpaV2.spec,
|
||||
metrics: [
|
||||
// @ts-ignore
|
||||
{
|
||||
resource: {
|
||||
name: "cpu",
|
||||
target: {
|
||||
type: "Utilization",
|
||||
averageUtilization: 50,
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
result = render(
|
||||
<HpaDetails object={hpa} />,
|
||||
);
|
||||
|
||||
expect(result.baseElement).toMatchSnapshot();
|
||||
});
|
||||
|
||||
it("shows unknown metrics with with unusual type", () => {
|
||||
const hpa = new HorizontalPodAutoscaler(
|
||||
{
|
||||
...hpaV2,
|
||||
spec: {
|
||||
...hpaV2.spec,
|
||||
metrics: [
|
||||
{
|
||||
// @ts-ignore
|
||||
type: "Unusual",
|
||||
resource: {
|
||||
name: "cpu",
|
||||
target: {
|
||||
type: "Utilization",
|
||||
averageUtilization: 50,
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
result = render(
|
||||
<HpaDetails object={hpa} />,
|
||||
);
|
||||
|
||||
expect(result.baseElement).toMatchSnapshot();
|
||||
});
|
||||
});
|
||||
@@ -62,7 +62,7 @@ class NonInjectedHpaDetails extends React.Component<HpaDetailsProps & Dependenci
|
||||
const renderName = (metric: HorizontalPodAutoscalerMetricSpec) => {
|
||||
const metricName = getMetricName(metric);
|
||||
|
||||
switch (metric.type) {
|
||||
switch (metric?.type) {
|
||||
case HpaMetricType.ContainerResource:
|
||||
|
||||
// fallthrough
|
||||
@@ -85,11 +85,13 @@ class NonInjectedHpaDetails extends React.Component<HpaDetailsProps & Dependenci
|
||||
}
|
||||
case HpaMetricType.External:
|
||||
return `${metricName} on ${JSON.stringify(metric.external.metricSelector ?? metric.external.metric?.selector)}`;
|
||||
default:
|
||||
return hpa.spec?.targetCPUUtilizationPercentage ? "CPU Utilization percentage" : "unknown";
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Table>
|
||||
<Table data-testid="hpa-metrics">
|
||||
<TableHead flat>
|
||||
<TableCell className="name">Name</TableCell>
|
||||
<TableCell className="metrics">Current / Target</TableCell>
|
||||
@@ -162,10 +164,14 @@ class NonInjectedHpaDetails extends React.Component<HpaDetailsProps & Dependenci
|
||||
))}
|
||||
</DrawerItem>
|
||||
|
||||
<DrawerTitle>Metrics</DrawerTitle>
|
||||
<div className="metrics">
|
||||
{this.renderMetrics()}
|
||||
</div>
|
||||
{(hpa.getMetrics().length !== 0 || hpa.spec?.targetCPUUtilizationPercentage) && (
|
||||
<>
|
||||
<DrawerTitle>Metrics</DrawerTitle>
|
||||
<div className="metrics">
|
||||
{this.renderMetrics()}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -113,6 +113,11 @@ class NonInjectedConfigMapDetails extends React.Component<ConfigMapDetailsProps
|
||||
value={value}
|
||||
onChange={v => this.data.set(name, v)}
|
||||
setInitialHeight
|
||||
options={{
|
||||
scrollbar: {
|
||||
alwaysConsumeMouseWheel: false,
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
))
|
||||
|
||||
+33
-59
@@ -10,70 +10,44 @@ import { observer } from "mobx-react";
|
||||
import { DrawerItem } from "../drawer";
|
||||
import { Badge } from "../badge";
|
||||
import type { KubeObjectDetailsProps } from "../kube-object-details";
|
||||
import { PodDisruptionBudget } from "../../../common/k8s-api/endpoints";
|
||||
import type { Logger } from "../../../common/logger";
|
||||
import { withInjectables } from "@ogre-tools/injectable-react";
|
||||
import loggerInjectable from "../../../common/logger.injectable";
|
||||
import type { PodDisruptionBudget } from "../../../common/k8s-api/endpoints";
|
||||
|
||||
export interface PodDisruptionBudgetDetailsProps extends KubeObjectDetailsProps<PodDisruptionBudget> {
|
||||
}
|
||||
|
||||
interface Dependencies {
|
||||
logger: Logger;
|
||||
}
|
||||
export const PodDisruptionBudgetDetails = observer((props: PodDisruptionBudgetDetailsProps) => {
|
||||
const { object: pdb } = props;
|
||||
|
||||
@observer
|
||||
class NonInjectedPodDisruptionBudgetDetails extends React.Component<PodDisruptionBudgetDetailsProps & Dependencies> {
|
||||
|
||||
render() {
|
||||
const { object: pdb } = this.props;
|
||||
|
||||
if (!pdb) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!(pdb instanceof PodDisruptionBudget)) {
|
||||
this.props.logger.error("[PodDisruptionBudgetDetails]: passed object that is not an instanceof PodDisruptionBudget", pdb);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
const selectors = pdb.getSelectors();
|
||||
|
||||
return (
|
||||
<div className="PdbDetails">
|
||||
{selectors.length > 0 && (
|
||||
<DrawerItem name="Selector" labelsOnly>
|
||||
{
|
||||
selectors.map(label => <Badge key={label} label={label}/>)
|
||||
}
|
||||
</DrawerItem>
|
||||
)}
|
||||
|
||||
<DrawerItem name="Min Available">
|
||||
{pdb.getMinAvailable()}
|
||||
</DrawerItem>
|
||||
|
||||
<DrawerItem name="Max Unavailable">
|
||||
{pdb.getMaxUnavailable()}
|
||||
</DrawerItem>
|
||||
|
||||
<DrawerItem name="Current Healthy">
|
||||
{pdb.getCurrentHealthy()}
|
||||
</DrawerItem>
|
||||
|
||||
<DrawerItem name="Desired Healthy">
|
||||
{pdb.getDesiredHealthy()}
|
||||
</DrawerItem>
|
||||
|
||||
</div>
|
||||
);
|
||||
if (!pdb) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export const PodDisruptionBudgetDetails = withInjectables<Dependencies, PodDisruptionBudgetDetailsProps>(NonInjectedPodDisruptionBudgetDetails, {
|
||||
getProps: (di, props) => ({
|
||||
...props,
|
||||
logger: di.inject(loggerInjectable),
|
||||
}),
|
||||
const selectors = pdb.getSelectors();
|
||||
|
||||
return (
|
||||
<div className="PdbDetails">
|
||||
{selectors.length > 0 && (
|
||||
<DrawerItem name="Selector" labelsOnly>
|
||||
{selectors.map(label => <Badge key={label} label={label}/>)}
|
||||
</DrawerItem>
|
||||
)}
|
||||
|
||||
<DrawerItem name="Min Available">
|
||||
{pdb.getMinAvailable()}
|
||||
</DrawerItem>
|
||||
|
||||
<DrawerItem name="Max Unavailable">
|
||||
{pdb.getMaxUnavailable()}
|
||||
</DrawerItem>
|
||||
|
||||
<DrawerItem name="Current Healthy">
|
||||
{pdb.getCurrentHealthy()}
|
||||
</DrawerItem>
|
||||
|
||||
<DrawerItem name="Desired Healthy">
|
||||
{pdb.getDesiredHealthy()}
|
||||
</DrawerItem>
|
||||
|
||||
</div>
|
||||
);
|
||||
});
|
||||
@@ -11,7 +11,7 @@ import React from "react";
|
||||
import { ipcRendererOn } from "../../../common/ipc";
|
||||
import type { Cluster } from "../../../common/cluster/cluster";
|
||||
import type { IClassName } from "../../utils";
|
||||
import { isBoolean, hasTypedProperty, isObject, isString, cssNames } from "../../utils";
|
||||
import { hasTypedProperty, isObject, isString, cssNames } from "../../utils";
|
||||
import { Button } from "../button";
|
||||
import { Icon } from "../icon";
|
||||
import { Spinner } from "../spinner";
|
||||
@@ -51,8 +51,8 @@ class NonInjectedClusterStatus extends React.Component<ClusterStatusProps & Depe
|
||||
return this.props.entityRegistry.getById(this.cluster.id);
|
||||
}
|
||||
|
||||
@computed get hasErrors(): boolean {
|
||||
return this.authOutput.some(({ isError }) => isError);
|
||||
@computed get hasErrorsOrWarnings(): boolean {
|
||||
return this.authOutput.some(({ level }) => level !== "info");
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
@@ -61,7 +61,7 @@ class NonInjectedClusterStatus extends React.Component<ClusterStatusProps & Depe
|
||||
if (
|
||||
isObject(res)
|
||||
&& hasTypedProperty(res, "message", isString)
|
||||
&& hasTypedProperty(res, "isError", isBoolean)
|
||||
&& hasTypedProperty(res, "level", function (val): val is KubeAuthUpdate["level"] { return ["info", "warning", "error"].includes(val as string); })
|
||||
) {
|
||||
this.authOutput.push(res);
|
||||
} else {
|
||||
@@ -87,7 +87,7 @@ class NonInjectedClusterStatus extends React.Component<ClusterStatusProps & Depe
|
||||
} catch (error) {
|
||||
this.authOutput.push({
|
||||
message: String(error),
|
||||
isError: true,
|
||||
level: "error",
|
||||
});
|
||||
} finally {
|
||||
this.isReconnecting = false;
|
||||
@@ -102,8 +102,8 @@ class NonInjectedClusterStatus extends React.Component<ClusterStatusProps & Depe
|
||||
return (
|
||||
<pre>
|
||||
{
|
||||
this.authOutput.map(({ message, isError }, index) => (
|
||||
<p key={index} className={cssNames({ error: isError })}>
|
||||
this.authOutput.map(({ message, level }, index) => (
|
||||
<p key={index} className={cssNames({ error: level === "error", warning: level === "warning" })}>
|
||||
{message.trim()}
|
||||
</p>
|
||||
))
|
||||
@@ -113,7 +113,7 @@ class NonInjectedClusterStatus extends React.Component<ClusterStatusProps & Depe
|
||||
}
|
||||
|
||||
renderStatusIcon() {
|
||||
if (this.hasErrors) {
|
||||
if (this.hasErrorsOrWarnings) {
|
||||
return <Icon material="cloud_off" className={styles.icon} />;
|
||||
}
|
||||
|
||||
@@ -131,7 +131,7 @@ class NonInjectedClusterStatus extends React.Component<ClusterStatusProps & Depe
|
||||
}
|
||||
|
||||
renderReconnectionHelp() {
|
||||
if (this.hasErrors && !this.isReconnecting) {
|
||||
if (this.hasErrorsOrWarnings && !this.isReconnecting) {
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
|
||||
+2
-7
@@ -6,8 +6,8 @@ import { getInjectable } from "@ogre-tools/injectable";
|
||||
import { kubeObjectDetailItemInjectionToken } from "../kube-object-detail-item-injection-token";
|
||||
import { computed } from "mobx";
|
||||
import { PodDisruptionBudgetDetails } from "../../../+config-pod-disruption-budgets";
|
||||
import { kubeObjectMatchesToKindAndApiVersion } from "../kube-object-matches-to-kind-and-api-version";
|
||||
import currentKubeObjectInDetailsInjectable from "../../current-kube-object-in-details.injectable";
|
||||
import { PodDisruptionBudget } from "../../../../../common/k8s-api/endpoints";
|
||||
|
||||
const podDisruptionBudgetDetailItemInjectable = getInjectable({
|
||||
id: "pod-disruption-budget-detail-item",
|
||||
@@ -17,7 +17,7 @@ const podDisruptionBudgetDetailItemInjectable = getInjectable({
|
||||
|
||||
return {
|
||||
Component: PodDisruptionBudgetDetails,
|
||||
enabled: computed(() => isPodDisruptionBudget(kubeObject.value.get()?.object)),
|
||||
enabled: computed(() => kubeObject.value.get()?.object instanceof PodDisruptionBudget),
|
||||
orderNumber: 10,
|
||||
};
|
||||
},
|
||||
@@ -25,9 +25,4 @@ const podDisruptionBudgetDetailItemInjectable = getInjectable({
|
||||
injectionToken: kubeObjectDetailItemInjectionToken,
|
||||
});
|
||||
|
||||
const isPodDisruptionBudget = kubeObjectMatchesToKindAndApiVersion(
|
||||
"PodDisruptionBudget",
|
||||
["policy/v1beta1"],
|
||||
);
|
||||
|
||||
export default podDisruptionBudgetDetailItemInjectable;
|
||||
@@ -22,6 +22,10 @@ const LensExtensions = {
|
||||
Renderer: LensExtensionsRendererApi,
|
||||
};
|
||||
|
||||
export type {
|
||||
LensExtensionsRendererApi,
|
||||
};
|
||||
|
||||
export {
|
||||
React,
|
||||
ReactDOM,
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* Copyright (c) OpenLens Authors. All rights reserved.
|
||||
* Licensed under MIT License. See LICENSE in root directory for more information.
|
||||
*/
|
||||
import type { Response, Headers as NodeFetchHeaders } from "node-fetch";
|
||||
import type { Response, Headers as NodeFetchHeaders } from "@k8slens/node-fetch";
|
||||
import { PassThrough } from "stream";
|
||||
|
||||
export const createMockResponseFromString = (url: string, data: string, statusCode = 200) => {
|
||||
|
||||
Reference in new issue
Block a user