Merge branch 'master' into fix/ignore-clusters-with-corrupted-kubeconfig

This commit is contained in:
Lauri Nevala committed 2021-02-25 13:31:13 +02:00
commit 607ebb599b
383 files changed
+15646 -3180

No files matched your search

@@ -0,0 +1,40 @@
import { ingressStore } from "../../components/+network-ingresses/ingress.store";
import { apiManager } from "../api-manager";
import { KubeApi } from "../kube-api";
class TestApi extends KubeApi {
protected async checkPreferredVersion() {
return;
}
}
describe("ApiManager", () => {
describe("registerApi", () => {
it("re-register store if apiBase changed", async () => {
const apiBase = "apis/v1/foo";
const fallbackApiBase = "/apis/extensions/v1beta1/foo";
const kubeApi = new TestApi({
apiBase,
fallbackApiBases: [fallbackApiBase],
checkPreferredVersion: true,
});
apiManager.registerApi(apiBase, kubeApi);
// Define to use test api for ingress store
Object.defineProperty(ingressStore, "api", { value: kubeApi });
apiManager.registerStore(ingressStore, [kubeApi]);
// Test that store is returned with original apiBase
expect(apiManager.getStore(kubeApi)).toBe(ingressStore);
// Change apiBase similar as checkPreferredVersion does
Object.defineProperty(kubeApi, "apiBase", { value: fallbackApiBase });
apiManager.registerApi(fallbackApiBase, kubeApi);
// Test that store is returned with new apiBase
expect(apiManager.getStore(kubeApi)).toBe(ingressStore);
});
});
});
+1 -1
View File
@@ -79,4 +79,4 @@ describe("KubeApi", () => {
expect(kubeApi.apiPrefix).toEqual("/apis");
expect(kubeApi.apiGroup).toEqual("extensions");
});
});
});
+11 -5
View File
@@ -2,16 +2,16 @@ import type { KubeObjectStore } from "../kube-object.store";
import { action, observable } from "mobx";
import { autobind } from "../utils";
import { KubeApi } from "./kube-api";
import { KubeApi, parseKubeApi } from "./kube-api";
@autobind()
export class ApiManager {
private apis = observable.map<string, KubeApi>();
private stores = observable.map<KubeApi, KubeObjectStore>();
private stores = observable.map<string, KubeObjectStore>();
getApi(pathOrCallback: string | ((api: KubeApi) => boolean)) {
if (typeof pathOrCallback === "string") {
return this.apis.get(pathOrCallback) || this.apis.get(KubeApi.parseApi(pathOrCallback).apiBase);
return this.apis.get(pathOrCallback) || this.apis.get(parseKubeApi(pathOrCallback).apiBase);
}
return Array.from(this.apis.values()).find(pathOrCallback ?? (() => true));
@@ -23,6 +23,12 @@ export class ApiManager {
registerApi(apiBase: string, api: KubeApi) {
if (!this.apis.has(apiBase)) {
this.stores.forEach((store) => {
if(store.api === api) {
this.stores.set(apiBase, store);
}
});
this.apis.set(apiBase, api);
}
}
@@ -46,12 +52,12 @@ export class ApiManager {
@action
registerStore(store: KubeObjectStore, apis: KubeApi[] = [store.api]) {
apis.forEach(api => {
this.stores.set(api, store);
this.stores.set(api.apiBase, store);
});
}
getStore<S extends KubeObjectStore>(api: string | KubeApi): S {
return this.stores.get(this.resolveApi(api)) as S;
return this.stores.get(this.resolveApi(api)?.apiBase) as S;
}
}
+1 -1
View File
@@ -28,7 +28,7 @@ export class KubeEvent extends KubeObject {
firstTimestamp: string;
lastTimestamp: string;
count: number;
type: string;
type: "Normal" | "Warning" | string;
eventTime: null;
reportingComponent: string;
reportingInstance: string;
@@ -3,11 +3,8 @@ import { apiBase } from "../index";
import { stringify } from "querystring";
import { autobind } from "../../utils";
interface IHelmChartList {
[repo: string]: {
[name: string]: HelmChart;
};
}
export type RepoHelmChartList = Record<string, HelmChart[]>;
export type HelmChartList = Record<string, RepoHelmChartList>;
export interface IHelmChartDetails {
readme: string;
@@ -22,12 +19,12 @@ const endpoint = compile(`/v2/charts/:repo?/:name?`) as (params?: {
export const helmChartsApi = {
list() {
return apiBase
.get<IHelmChartList>(endpoint())
.get<HelmChartList>(endpoint())
.then(data => {
return Object
.values(data)
.reduce((allCharts, repoCharts) => allCharts.concat(Object.values(repoCharts)), [])
.map(HelmChart.create);
.map(([chart]) => HelmChart.create(chart));
});
},
@@ -86,7 +83,7 @@ export class HelmChart {
tillerVersion?: string;
getId() {
return this.digest;
return `${this.apiVersion}/${this.name}@${this.getAppVersion()}`;
}
getName() {
@@ -57,6 +57,7 @@ export interface IReleaseRevision {
updated: string;
status: string;
chart: string;
app_version: string;
description: string;
}
@@ -197,10 +198,9 @@ export class HelmRelease implements ItemObject {
}
getUpdated(humanize = true, compact = true) {
const now = new Date().getTime();
const updated = this.updated.replace(/\s\w*$/, ""); // 2019-11-26 10:58:09 +0300 MSK -> 2019-11-26 10:58:09 +0300 to pass into Date()
const updatedDate = new Date(updated).getTime();
const diff = now - updatedDate;
const diff = Date.now() - updatedDate;
if (humanize) {
return formatDuration(diff, compact);
+1
View File
@@ -14,6 +14,7 @@ export * from "./events.api";
export * from "./hpa.api";
export * from "./ingress.api";
export * from "./job.api";
export * from "./limit-range.api";
export * from "./namespaces.api";
export * from "./network-policy.api";
export * from "./nodes.api";
@@ -0,0 +1,57 @@
import { KubeObject } from "../kube-object";
import { KubeApi } from "../kube-api";
import { autobind } from "../../utils";
export enum LimitType {
CONTAINER = "Container",
POD = "Pod",
PVC = "PersistentVolumeClaim",
}
export enum Resource {
MEMORY = "memory",
CPU = "cpu",
STORAGE = "storage",
EPHEMERAL_STORAGE = "ephemeral-storage",
}
export enum LimitPart {
MAX = "max",
MIN = "min",
DEFAULT = "default",
DEFAULT_REQUEST = "defaultRequest",
MAX_LIMIT_REQUEST_RATIO = "maxLimitRequestRatio",
}
type LimitRangeParts = Partial<Record<LimitPart, Record<string, string>>>;
export interface LimitRangeItem extends LimitRangeParts {
type: string
}
@autobind()
export class LimitRange extends KubeObject {
static kind = "LimitRange";
static namespaced = true;
static apiBase = "/api/v1/limitranges";
spec: {
limits: LimitRangeItem[];
};
getContainerLimits() {
return this.spec.limits.filter(limit => limit.type === LimitType.CONTAINER);
}
getPodLimits() {
return this.spec.limits.filter(limit => limit.type === LimitType.POD);
}
getPVCLimits() {
return this.spec.limits.filter(limit => limit.type === LimitType.PVC);
}
}
export const limitRangeApi = new KubeApi({
objectConstructor: LimitRange,
});
@@ -63,10 +63,16 @@ export class PersistentVolume extends KubeObject {
return this.status.phase || "-";
}
getClaimRefName() {
const { claimRef } = this.spec;
getStorageClass(): string {
return this.spec.storageClassName;
}
return claimRef ? claimRef.name : "";
getClaimRefName(): string {
return this.spec.claimRef?.name ?? "";
}
getStorageClassName() {
return this.spec.storageClassName || "";
}
}
+3
View File
@@ -104,6 +104,9 @@ export interface IPodContainer {
configMapRef?: {
name: string;
};
secretRef?: {
name: string;
}
}[];
volumeMounts?: {
name: string;
+29 -1
View File
@@ -3,7 +3,7 @@
import { stringify } from "querystring";
import { EventEmitter } from "../../common/event-emitter";
import { cancelableFetch } from "../utils/cancelableFetch";
import { randomBytes } from "crypto";
export interface JsonApiData {
}
@@ -55,6 +55,34 @@ export class JsonApi<D = JsonApiData, P extends JsonApiParams = JsonApiParams> {
return this.request<T>(path, params, { ...reqInit, method: "get" });
}
getResponse(path: string, params?: P, init: RequestInit = {}): Promise<Response> {
const reqPath = `${this.config.apiBase}${path}`;
const subdomain = randomBytes(2).toString("hex");
let reqUrl = `http://${subdomain}.${window.location.host}${reqPath}`; // hack around browser connection limits (chromium allows 6 per domain)
const reqInit: RequestInit = { ...init };
const { query } = params || {} as P;
if (!reqInit.method) {
reqInit.method = "get";
}
if (query) {
const queryString = stringify(query);
reqUrl += (reqUrl.includes("?") ? "&" : "?") + queryString;
}
const infoLog: JsonApiLog = {
method: reqInit.method.toUpperCase(),
reqUrl: reqPath,
reqInit,
};
this.writeLog({ ...infoLog });
return fetch(reqUrl, reqInit);
}
post<T = D>(path: string, params?: P, reqInit: RequestInit = {}) {
return this.request<T>(path, params, { ...reqInit, method: "post" });
}
+108 -14
View File
@@ -8,8 +8,10 @@ import { apiManager } from "./api-manager";
import { apiKube } from "./index";
import { createKubeApiURL, parseKubeApi } from "./kube-api-parse";
import { KubeJsonApi, KubeJsonApiData, KubeJsonApiDataList } from "./kube-json-api";
import { IKubeObjectConstructor, KubeObject } from "./kube-object";
import { kubeWatchApi } from "./kube-watch-api";
import { IKubeObjectConstructor, KubeObject, KubeStatus } from "./kube-object";
import byline from "byline";
import { IKubeWatchEvent } from "./kube-watch-api";
import { ReadableWebToNodeStream } from "../utils/readableStream";
export interface IKubeApiOptions<T extends KubeObject> {
/**
@@ -91,15 +93,15 @@ export function ensureObjectSelfLink(api: KubeApi, object: KubeJsonApiData) {
}
}
export type KubeApiWatchCallback = (data: IKubeWatchEvent, error: any) => void;
export type KubeApiWatchOptions = {
namespace: string;
callback?: KubeApiWatchCallback;
abortController?: AbortController
};
export class KubeApi<T extends KubeObject = any> {
static parseApi = parseKubeApi;
static watchAll(...apis: KubeApi[]) {
const disposers = apis.map(api => api.watch());
return () => disposers.forEach(unwatch => unwatch());
}
readonly kind: string;
readonly apiBase: string;
readonly apiPrefix: string;
@@ -112,6 +114,7 @@ export class KubeApi<T extends KubeObject = any> {
public objectConstructor: IKubeObjectConstructor<T>;
protected request: KubeJsonApi;
protected resourceVersions = new Map<string, string>();
protected watchDisposer: () => void;
constructor(protected options: IKubeApiOptions<T>) {
const {
@@ -124,7 +127,7 @@ export class KubeApi<T extends KubeObject = any> {
if (!options.apiBase) {
options.apiBase = objectConstructor.apiBase;
}
const { apiBase, apiPrefix, apiGroup, apiVersion, resource } = KubeApi.parseApi(options.apiBase);
const { apiBase, apiPrefix, apiGroup, apiVersion, resource } = parseKubeApi(options.apiBase);
this.kind = kind;
this.isNamespaced = isNamespaced;
@@ -157,7 +160,7 @@ export class KubeApi<T extends KubeObject = any> {
for (const apiUrl of apiBases) {
// Split e.g. "/apis/extensions/v1beta1/ingresses" to parts
const { apiPrefix, apiGroup, apiVersionWithGroup, resource } = KubeApi.parseApi(apiUrl);
const { apiPrefix, apiGroup, apiVersionWithGroup, resource } = parseKubeApi(apiUrl);
// Request available resources
try {
@@ -269,6 +272,7 @@ export class KubeApi<T extends KubeObject = any> {
}
protected parseResponse(data: KubeJsonApiData | KubeJsonApiData[] | KubeJsonApiDataList, namespace?: string): any {
if (!data) return;
const KubeObjectConstructor = this.objectConstructor;
if (KubeObject.isJsonApiData(data)) {
@@ -365,8 +369,98 @@ export class KubeApi<T extends KubeObject = any> {
});
}
watch(): () => void {
return kubeWatchApi.subscribe(this);
watch(opts: KubeApiWatchOptions = { namespace: "" }): () => void {
if (!opts.abortController) {
opts.abortController = new AbortController();
}
let errorReceived = false;
let timedRetry: NodeJS.Timeout;
const { abortController, namespace, callback } = opts;
abortController.signal.addEventListener("abort", () => {
clearTimeout(timedRetry);
});
const watchUrl = this.getWatchUrl(namespace);
const responsePromise = this.request.getResponse(watchUrl, null, {
signal: abortController.signal
});
responsePromise.then((response) => {
if (!response.ok && !abortController.signal.aborted) {
callback?.(null, response);
return;
}
const nodeStream = new ReadableWebToNodeStream(response.body);
["end", "close", "error"].forEach((eventName) => {
nodeStream.on(eventName, () => {
if (errorReceived) return; // kubernetes errors should be handled in a callback
clearTimeout(timedRetry);
timedRetry = setTimeout(() => { // we did not get any kubernetes errors so let's retry
if (abortController.signal.aborted) return;
this.watch({...opts, namespace, callback});
}, 1000);
});
});
const stream = byline(nodeStream);
stream.on("data", (line) => {
try {
const event: IKubeWatchEvent = JSON.parse(line);
if (event.type === "ERROR" && event.object.kind === "Status") {
errorReceived = true;
callback(null, new KubeStatus(event.object as any));
return;
}
this.modifyWatchEvent(event);
if (callback) {
callback(event, null);
}
} catch (ignore) {
// ignore parse errors
}
});
}, (error) => {
if (error instanceof DOMException) return; // AbortController rejects, we can ignore it
callback?.(null, error);
}).catch((error) => {
callback?.(null, error);
});
const disposer = () => {
abortController.abort();
};
return disposer;
}
protected modifyWatchEvent(event: IKubeWatchEvent) {
switch (event.type) {
case "ADDED":
case "DELETED":
case "MODIFIED": {
ensureObjectSelfLink(this, event.object);
const { namespace, resourceVersion } = event.object.metadata;
this.setResourceVersion(namespace, resourceVersion);
this.setResourceVersion("", resourceVersion);
break;
}
}
}
}
+1 -1
View File
@@ -21,7 +21,7 @@ export interface KubeJsonApiData extends JsonApiData {
resourceVersion: string;
continue?: string;
finalizers?: string[];
selfLink: string;
selfLink?: string;
labels?: {
[label: string]: string;
};
+30 -4
View File
@@ -40,6 +40,29 @@ export interface IKubeObjectMetadata {
}[];
}
export interface IKubeStatus {
kind: string;
apiVersion: string;
code: number;
message?: string;
reason?: string;
}
export class KubeStatus {
public readonly kind = "Status";
public readonly apiVersion: string;
public readonly code: number;
public readonly message: string;
public readonly reason: string;
constructor(data: IKubeStatus) {
this.apiVersion = data.apiVersion;
this.code = data.code;
this.message = data.message || "";
this.reason = data.reason || "";
}
}
export type IKubeMetaField = keyof IKubeObjectMetadata;
@autobind()
@@ -99,12 +122,15 @@ export class KubeObject implements ItemObject {
return this.metadata.namespace || undefined;
}
// todo: refactor with named arguments
getAge(humanize = true, compact = true, fromNow = false) {
getTimeDiffFromNow(): number {
return Date.now() - new Date(this.metadata.creationTimestamp).getTime();
}
getAge(humanize = true, compact = true, fromNow = false): string | number {
if (fromNow) {
return moment(this.metadata.creationTimestamp).fromNow();
return moment(this.metadata.creationTimestamp).fromNow(); // "string", getTimeDiffFromNow() cannot be used
}
const diff = new Date().getTime() - new Date(this.metadata.creationTimestamp).getTime();
const diff = this.getTimeDiffFromNow();
if (humanize) {
return formatDuration(diff, compact);
+100 -152
View File
@@ -1,183 +1,131 @@
// Kubernetes watch-api consumer
// Kubernetes watch-api client
// API: https://developer.mozilla.org/en-US/docs/Web/API/Streams_API/Using_readable_streams
import { computed, observable, reaction } from "mobx";
import { stringify } from "querystring";
import { autobind, EventEmitter } from "../utils";
import { KubeJsonApiData } from "./kube-json-api";
import type { KubeObjectStore } from "../kube-object.store";
import { ensureObjectSelfLink, KubeApi } from "./kube-api";
import { apiManager } from "./api-manager";
import { apiPrefix, isDevelopment } from "../../common/vars";
import { getHostedCluster } from "../../common/cluster-store";
import type { ClusterContext } from "../components/context";
export interface IKubeWatchEvent<T = any> {
type: "ADDED" | "MODIFIED" | "DELETED";
import plimit from "p-limit";
import { comparer, IReactionDisposer, observable, reaction, when } from "mobx";
import { autobind, noop } from "../utils";
import { KubeApi } from "./kube-api";
import { KubeJsonApiData } from "./kube-json-api";
import { isDebugging, isProduction } from "../../common/vars";
export interface IKubeWatchEvent<T = KubeJsonApiData> {
type: "ADDED" | "MODIFIED" | "DELETED" | "ERROR";
object?: T;
}
export interface IKubeWatchRouteEvent {
type: "STREAM_END";
url: string;
status: number;
export interface IKubeWatchSubscribeStoreOptions {
namespaces?: string[]; // default: all accessible namespaces
preload?: boolean; // preload store items, default: true
waitUntilLoaded?: boolean; // subscribe only after loading all stores, default: true
loadOnce?: boolean; // check store.isLoaded to skip loading if done already, default: false
}
export interface IKubeWatchRouteQuery {
api: string | string[];
export interface IKubeWatchLog {
message: string | string[] | Error;
meta?: object;
cssStyle?: string;
}
@autobind()
export class KubeWatchApi {
protected evtSource: EventSource;
protected onData = new EventEmitter<[IKubeWatchEvent]>();
protected subscribers = observable.map<KubeApi, number>();
protected reconnectTimeoutMs = 5000;
protected maxReconnectsOnError = 10;
protected reconnectAttempts = this.maxReconnectsOnError;
@observable context: ClusterContext = null;
constructor() {
reaction(() => this.activeApis, () => this.connect(), {
fireImmediately: true,
delay: 500,
});
contextReady = when(() => Boolean(this.context));
isAllowedApi(api: KubeApi): boolean {
return Boolean(this.context?.cluster.isAllowedResource(api.kind));
}
@computed get activeApis() {
return Array.from(this.subscribers.keys());
}
preloadStores(stores: KubeObjectStore[], opts: { namespaces?: string[], loadOnce?: boolean } = {}) {
const limitRequests = plimit(1); // load stores one by one to allow quick skipping when fast clicking btw pages
const preloading: Promise<any>[] = [];
getSubscribersCount(api: KubeApi) {
return this.subscribers.get(api) || 0;
}
for (const store of stores) {
preloading.push(limitRequests(async () => {
if (store.isLoaded && opts.loadOnce) return; // skip
subscribe(...apis: KubeApi[]) {
apis.forEach(api => {
this.subscribers.set(api, this.getSubscribersCount(api) + 1);
});
return () => apis.forEach(api => {
const count = this.getSubscribersCount(api) - 1;
if (count <= 0) this.subscribers.delete(api);
else this.subscribers.set(api, count);
});
}
protected getQuery(): Partial<IKubeWatchRouteQuery> {
const { isAdmin, allowedNamespaces } = getHostedCluster();
return store.loadAll({ namespaces: opts.namespaces });
}));
}
return {
api: this.activeApis.map(api => {
if (isAdmin) return api.getWatchUrl();
return allowedNamespaces.map(namespace => api.getWatchUrl(namespace));
}).flat()
loading: Promise.allSettled(preloading),
cancelLoading: () => limitRequests.clearQueue(),
};
}
// todo: maybe switch to websocket to avoid often reconnects
@autobind()
protected connect() {
if (this.evtSource) this.disconnect(); // close previous connection
subscribeStores(stores: KubeObjectStore[], opts: IKubeWatchSubscribeStoreOptions = {}): () => void {
const { preload = true, waitUntilLoaded = true, loadOnce = false, } = opts;
const subscribingNamespaces = opts.namespaces ?? this.context?.allNamespaces ?? [];
const unsubscribeList: Function[] = [];
let isUnsubscribed = false;
if (!this.activeApis.length) {
const load = (namespaces = subscribingNamespaces) => this.preloadStores(stores, { namespaces, loadOnce });
let preloading = preload && load();
let cancelReloading: IReactionDisposer = noop;
const subscribe = () => {
if (isUnsubscribed) return;
stores.forEach((store) => {
unsubscribeList.push(store.subscribe());
});
};
if (preloading) {
if (waitUntilLoaded) {
preloading.loading.then(subscribe, error => {
this.log({
message: new Error("Loading stores has failed"),
meta: { stores, error, options: opts },
});
});
} else {
subscribe();
}
// reload stores only for context namespaces change
cancelReloading = reaction(() => this.context?.contextNamespaces, namespaces => {
preloading?.cancelLoading();
unsubscribeList.forEach(unsubscribe => unsubscribe());
unsubscribeList.length = 0;
preloading = load(namespaces);
preloading.loading.then(subscribe);
}, {
equals: comparer.shallow,
});
}
// unsubscribe
return () => {
if (isUnsubscribed) return;
isUnsubscribed = true;
cancelReloading();
preloading?.cancelLoading();
unsubscribeList.forEach(unsubscribe => unsubscribe());
unsubscribeList.length = 0;
};
}
protected log({ message, cssStyle = "", meta = {} }: IKubeWatchLog) {
if (isProduction && !isDebugging) {
return;
}
const query = this.getQuery();
const apiUrl = `${apiPrefix}/watch?${stringify(query)}`;
this.evtSource = new EventSource(apiUrl);
this.evtSource.onmessage = this.onMessage;
this.evtSource.onerror = this.onError;
this.writeLog("CONNECTING", query.api);
}
reconnect() {
if (!this.evtSource || this.evtSource.readyState !== EventSource.OPEN) {
this.reconnectAttempts = this.maxReconnectsOnError;
this.connect();
}
}
protected disconnect() {
if (!this.evtSource) return;
this.evtSource.close();
this.evtSource.onmessage = null;
this.evtSource = null;
}
protected onMessage(evt: MessageEvent) {
if (!evt.data) return;
const data = JSON.parse(evt.data);
if ((data as IKubeWatchEvent).object) {
this.onData.emit(data);
} else {
this.onRouteEvent(data);
}
}
protected async onRouteEvent(event: IKubeWatchRouteEvent) {
if (event.type === "STREAM_END") {
this.disconnect();
const { apiBase, namespace } = KubeApi.parseApi(event.url);
const api = apiManager.getApi(apiBase);
if (api) {
try {
await api.refreshResourceVersion({ namespace });
this.reconnect();
} catch (error) {
console.error("failed to refresh resource version", error);
if (this.subscribers.size > 0) {
setTimeout(() => {
this.onRouteEvent(event);
}, 1000);
}
}
}
}
}
protected onError(evt: MessageEvent) {
const { reconnectAttempts: attemptsRemain, reconnectTimeoutMs } = this;
if (evt.eventPhase === EventSource.CLOSED) {
if (attemptsRemain > 0) {
this.reconnectAttempts--;
setTimeout(() => this.connect(), reconnectTimeoutMs);
}
}
}
protected writeLog(...data: any[]) {
if (isDevelopment) {
console.log("%cKUBE-WATCH-API:", `font-weight: bold`, ...data);
}
}
addListener(store: KubeObjectStore, callback: (evt: IKubeWatchEvent) => void) {
const listener = (evt: IKubeWatchEvent<KubeJsonApiData>) => {
const { namespace, resourceVersion } = evt.object.metadata;
const api = apiManager.getApiByKind(evt.object.kind, evt.object.apiVersion);
api.setResourceVersion(namespace, resourceVersion);
api.setResourceVersion("", resourceVersion);
ensureObjectSelfLink(api, evt.object);
if (store == apiManager.getStore(api)) {
callback(evt);
}
const logInfo = [`%c[KUBE-WATCH-API]:`, `font-weight: bold; ${cssStyle}`, message].flat().map(String);
const logMeta = {
time: new Date().toLocaleString(),
...meta,
};
this.onData.addListener(listener);
return () => this.onData.removeListener(listener);
}
reset() {
this.subscribers.clear();
if (message instanceof Error) {
console.error(...logInfo, logMeta);
} else {
console.info(...logInfo, logMeta);
}
}
}
+2 -2
View File
@@ -1,7 +1,7 @@
import get from "lodash/get";
import { KubeObject } from "./kube-object";
interface IToleration {
export interface IToleration {
key?: string;
operator?: string;
effect?: string;
@@ -82,4 +82,4 @@ export class WorkloadKubeObject extends KubeObject {
return Object.keys(affinity).length;
}
}
}
@@ -82,9 +82,9 @@ export class HelmChartDetails extends Component<Props> {
<div className="intro-contents box grow">
<div className="description flex align-center justify-space-between">
{selectedChart.getDescription()}
<Button primary label={`Install`} onClick={this.install} />
<Button primary label="Install" onClick={this.install} />
</div>
<DrawerItem name={`Version`} className="version" onClick={stopPropagation}>
<DrawerItem name="Version" className="version" onClick={stopPropagation}>
<Select
themeName="outlined"
menuPortalTarget={null}
@@ -93,16 +93,16 @@ export class HelmChartDetails extends Component<Props> {
onChange={onVersionChange}
/>
</DrawerItem>
<DrawerItem name={`Home`}>
<DrawerItem name="Home">
<a href={selectedChart.getHome()} target="_blank" rel="noreferrer">{selectedChart.getHome()}</a>
</DrawerItem>
<DrawerItem name={`Maintainers`} className="maintainers">
<DrawerItem name="Maintainers" className="maintainers">
{selectedChart.getMaintainers().map(({ name, email, url }) =>
<a key={name} href={url || `mailto:${email}`} target="_blank" rel="noreferrer">{name}</a>
)}
</DrawerItem>
{selectedChart.getKeywords().length > 0 && (
<DrawerItem name={`Keywords`} labelsOnly>
<DrawerItem name="Keywords" labelsOnly>
{selectedChart.getKeywords().map(key => <Badge key={key} label={key} />)}
</DrawerItem>
)}
@@ -11,4 +11,4 @@ export interface IHelmChartsRouteParams {
repo?: string;
}
export const helmChartsURL = buildURL<IHelmChartsRouteParams>(helmChartsRoute.path);
export const helmChartsURL = buildURL<IHelmChartsRouteParams>(helmChartsRoute.path);
@@ -11,8 +11,11 @@ import { navigation } from "../../navigation";
import { ItemListLayout } from "../item-object-list/item-list-layout";
import { SearchInputUrl } from "../input";
enum sortBy {
enum columnId {
name = "name",
description = "description",
version = "version",
appVersion = "app-version",
repo = "repo",
}
@@ -53,13 +56,15 @@ export class HelmCharts extends Component<Props> {
return (
<>
<ItemListLayout
isConfigurable
tableId="helm_charts"
className="HelmCharts"
store={helmChartStore}
isClusterScoped={true}
isSelectable={false}
sortingCallbacks={{
[sortBy.name]: (chart: HelmChart) => chart.getName(),
[sortBy.repo]: (chart: HelmChart) => chart.getRepository(),
[columnId.name]: (chart: HelmChart) => chart.getName(),
[columnId.repo]: (chart: HelmChart) => chart.getRepository(),
}}
searchFilters={[
(chart: HelmChart) => chart.getName(),
@@ -67,20 +72,16 @@ export class HelmCharts extends Component<Props> {
(chart: HelmChart) => chart.getAppVersion(),
(chart: HelmChart) => chart.getKeywords(),
]}
filterItems={[
(items: HelmChart[]) => items.filter(item => !item.deprecated)
]}
customizeHeader={() => (
<SearchInputUrl placeholder={`Search Helm Charts`} />
<SearchInputUrl placeholder="Search Helm Charts" />
)}
renderTableHeader={[
{ className: "icon" },
{ title: "Name", className: "name", sortBy: sortBy.name },
{ title: "Description", className: "description" },
{ title: "Version", className: "version" },
{ title: "App Version", className: "app-version" },
{ title: "Repository", className: "repository", sortBy: sortBy.repo },
{ className: "icon", showWithColumn: columnId.name },
{ title: "Name", className: "name", sortBy: columnId.name, id: columnId.name },
{ title: "Description", className: "description", id: columnId.description },
{ title: "Version", className: "version", id: columnId.version },
{ title: "App Version", className: "app-version", id: columnId.appVersion },
{ title: "Repository", className: "repository", sortBy: columnId.repo, id: columnId.repo },
]}
renderTableContents={(chart: HelmChart) => [
<figure key="image">
@@ -93,7 +94,8 @@ export class HelmCharts extends Component<Props> {
chart.getDescription(),
chart.getVersion(),
chart.getAppVersion(),
{ title: chart.getRepository(), className: chart.getRepository().toLowerCase() }
{ title: chart.getRepository(), className: chart.getRepository().toLowerCase() },
{ className: "menu" }
]}
detailsItem={this.selectedChart}
onDetails={this.showDetails}
@@ -1,2 +1,2 @@
export * from "./helm-charts";
export * from "./helm-charts.route";
export * from "./helm-charts.route";
@@ -1,2 +1,2 @@
export * from "./releases";
export * from "./release.route";
export * from "./release.route";
@@ -111,7 +111,7 @@ export class ReleaseDetails extends Component<Props> {
return (
<div className="values">
<DrawerTitle title={`Values`}/>
<DrawerTitle title="Values"/>
<div className="flex column gaps">
<AceEditor
mode="yaml"
@@ -120,7 +120,7 @@ export class ReleaseDetails extends Component<Props> {
/>
<Button
primary
label={`Save`}
label="Save"
waiting={saving}
onClick={this.updateValues}
/>
@@ -200,7 +200,7 @@ export class ReleaseDetails extends Component<Props> {
<span>{release.getChart()}</span>
<Button
primary
label={`Upgrade`}
label="Upgrade"
className="box right upgrade"
onClick={this.upgradeVersion}
/>
@@ -226,9 +226,9 @@ export class ReleaseDetails extends Component<Props> {
/>
</DrawerItem>
{this.renderValues()}
<DrawerTitle title={`Notes`}/>
<DrawerTitle title="Notes"/>
{this.renderNotes()}
<DrawerTitle title={`Resources`}/>
<DrawerTitle title="Resources"/>
{this.renderResources()}
</div>
);
@@ -42,7 +42,7 @@ export class HelmReleaseMenu extends React.Component<Props> {
<>
{hasRollback && (
<MenuItem onClick={this.rollback}>
<Icon material="history" interactive={toolbar} title={`Rollback`}/>
<Icon material="history" interactive={toolbar} title="Rollback"/>
<span className="title">Rollback</span>
</MenuItem>
)}
@@ -77,7 +77,8 @@ export class ReleaseRollbackDialog extends React.Component<Props> {
themeName="light"
value={revision}
options={revisions}
formatOptionLabel={({ value }: SelectOption<IReleaseRevision>) => `${value.revision} - ${value.chart}`}
formatOptionLabel={({ value }: SelectOption<IReleaseRevision>) => `${value.revision} - ${value.chart}
- ${value.app_version}, updated: ${new Date(value.updated).toLocaleString()}`}
onChange={({ value }: SelectOption<IReleaseRevision>) => this.revision = value}
/>
</div>
@@ -5,7 +5,7 @@ import { HelmRelease, helmReleasesApi, IReleaseCreatePayload, IReleaseUpdatePayl
import { ItemStore } from "../../item.store";
import { Secret } from "../../api/endpoints";
import { secretsStore } from "../+config-secrets/secrets.store";
import { getHostedCluster } from "../../../common/cluster-store";
import { namespaceStore } from "../+namespaces/namespace.store";
@autobind()
export class ReleaseStore extends ItemStore<HelmRelease> {
@@ -33,7 +33,7 @@ export class ReleaseStore extends ItemStore<HelmRelease> {
});
if (amountChanged || labelsChanged) {
this.loadAll();
this.loadFromContextNamespaces();
}
this.releaseSecrets = [...secrets];
});
@@ -58,26 +58,30 @@ export class ReleaseStore extends ItemStore<HelmRelease> {
}
@action
async loadAll() {
async loadAll(namespaces: string[]) {
this.isLoading = true;
let items;
try {
const { isAdmin, allowedNamespaces } = getHostedCluster();
const items = await this.loadItems(namespaces);
items = await this.loadItems(!isAdmin ? allowedNamespaces : null);
} finally {
if (items) {
items = this.sortItems(items);
this.items.replace(items);
}
this.items.replace(this.sortItems(items));
this.isLoaded = true;
} catch (error) {
console.error(`Loading Helm Chart releases has failed: ${error}`);
} finally {
this.isLoading = false;
}
}
async loadItems(namespaces?: string[]) {
if (!namespaces) {
async loadFromContextNamespaces(): Promise<void> {
return this.loadAll(namespaceStore.contextNamespaces);
}
async loadItems(namespaces: string[]) {
const isLoadingAll = namespaceStore.allowedNamespaces.every(ns => namespaces.includes(ns));
const noAccessibleNamespaces = namespaceStore.context.cluster.accessibleNamespaces.length === 0;
if (isLoadingAll && noAccessibleNamespaces) {
return helmReleasesApi.list();
} else {
return Promise
@@ -89,7 +93,7 @@ export class ReleaseStore extends ItemStore<HelmRelease> {
async create(payload: IReleaseCreatePayload) {
const response = await helmReleasesApi.create(payload);
if (this.isLoaded) this.loadAll();
if (this.isLoaded) this.loadFromContextNamespaces();
return response;
}
@@ -97,7 +101,7 @@ export class ReleaseStore extends ItemStore<HelmRelease> {
async update(name: string, namespace: string, payload: IReleaseUpdatePayload) {
const response = await helmReleasesApi.update(name, namespace, payload);
if (this.isLoaded) this.loadAll();
if (this.isLoaded) this.loadFromContextNamespaces();
return response;
}
@@ -105,7 +109,7 @@ export class ReleaseStore extends ItemStore<HelmRelease> {
async rollback(name: string, namespace: string, revision: number) {
const response = await helmReleasesApi.rollback(name, namespace, revision);
if (this.isLoaded) this.loadAll();
if (this.isLoaded) this.loadFromContextNamespaces();
return response;
}
@@ -14,11 +14,13 @@ import { ItemListLayout } from "../item-object-list/item-list-layout";
import { HelmReleaseMenu } from "./release-menu";
import { secretsStore } from "../+config-secrets/secrets.store";
enum sortBy {
enum columnId {
name = "name",
namespace = "namespace",
revision = "revision",
chart = "chart",
version = "version",
appVersion = "app-version",
status = "status",
updated = "update"
}
@@ -81,16 +83,18 @@ export class HelmReleases extends Component<Props> {
return (
<>
<ItemListLayout
isConfigurable
tableId="helm_releases"
className="HelmReleases"
store={releaseStore}
dependentStores={[secretsStore]}
sortingCallbacks={{
[sortBy.name]: (release: HelmRelease) => release.getName(),
[sortBy.namespace]: (release: HelmRelease) => release.getNs(),
[sortBy.revision]: (release: HelmRelease) => release.getRevision(),
[sortBy.chart]: (release: HelmRelease) => release.getChart(),
[sortBy.status]: (release: HelmRelease) => release.getStatus(),
[sortBy.updated]: (release: HelmRelease) => release.getUpdated(false, false),
[columnId.name]: (release: HelmRelease) => release.getName(),
[columnId.namespace]: (release: HelmRelease) => release.getNs(),
[columnId.revision]: (release: HelmRelease) => release.getRevision(),
[columnId.chart]: (release: HelmRelease) => release.getChart(),
[columnId.status]: (release: HelmRelease) => release.getStatus(),
[columnId.updated]: (release: HelmRelease) => release.getUpdated(false, false),
}}
searchFilters={[
(release: HelmRelease) => release.getName(),
@@ -101,14 +105,14 @@ export class HelmReleases extends Component<Props> {
]}
renderHeaderTitle="Releases"
renderTableHeader={[
{ title: "Name", className: "name", sortBy: sortBy.name },
{ title: "Namespace", className: "namespace", sortBy: sortBy.namespace },
{ title: "Chart", className: "chart", sortBy: sortBy.chart },
{ title: "Revision", className: "revision", sortBy: sortBy.revision },
{ title: "Version", className: "version" },
{ title: "App Version", className: "app-version" },
{ title: "Status", className: "status", sortBy: sortBy.status },
{ title: "Updated", className: "updated", sortBy: sortBy.updated },
{ title: "Name", className: "name", sortBy: columnId.name, id: columnId.name },
{ title: "Namespace", className: "namespace", sortBy: columnId.namespace, id: columnId.namespace },
{ title: "Chart", className: "chart", sortBy: columnId.chart, id: columnId.chart },
{ title: "Revision", className: "revision", sortBy: columnId.revision, id: columnId.revision },
{ title: "Version", className: "version", id: columnId.version },
{ title: "App Version", className: "app-version", id: columnId.appVersion },
{ title: "Status", className: "status", sortBy: columnId.status, id: columnId.status },
{ title: "Updated", className: "updated", sortBy: columnId.updated, id: columnId.updated },
]}
renderTableContents={(release: HelmRelease) => {
const version = release.getVersion();
@@ -0,0 +1,18 @@
import { navigate } from "../../navigation";
import { commandRegistry } from "../../../extensions/registries/command-registry";
import { helmChartsURL } from "../+apps-helm-charts";
import { releaseURL } from "../+apps-releases";
commandRegistry.add({
id: "cluster.viewHelmCharts",
title: "Cluster: View Helm Charts",
scope: "cluster",
action: () => navigate(helmChartsURL())
});
commandRegistry.add({
id: "cluster.viewHelmReleases",
title: "Cluster: View Helm Releases",
scope: "cluster",
action: () => navigate(releaseURL())
});
+2 -1
View File
@@ -1,2 +1,3 @@
export * from "./apps";
export * from "./apps.route";
export * from "./apps.route";
export * from "./apps.command";
@@ -0,0 +1,16 @@
import { navigate } from "../../navigation";
import { commandRegistry } from "../../../extensions/registries/command-registry";
import { clusterSettingsURL } from "./cluster-settings.route";
import { clusterStore } from "../../../common/cluster-store";
commandRegistry.add({
id: "cluster.viewCurrentClusterSettings",
title: "Cluster: View Settings",
scope: "global",
action: () => navigate(clusterSettingsURL({
params: {
clusterId: clusterStore.active.id
}
})),
isActive: (context) => !!context.cluster
});
@@ -48,4 +48,4 @@ export class ClusterHomeDirSetting extends React.Component<Props> {
</>
);
}
}
}
@@ -45,4 +45,4 @@ export class ClusterNameSetting extends React.Component<Props> {
</>
);
}
}
}
@@ -45,4 +45,4 @@ export class ClusterProxySetting extends React.Component<Props> {
</>
);
}
}
}
@@ -1,7 +1,5 @@
import React from "react";
import { observer } from "mobx-react";
import { Link } from "react-router-dom";
import { workspacesURL } from "../../+workspaces";
import { workspaceStore } from "../../../../common/workspace-store";
import { Cluster } from "../../../../main/cluster";
import { Select } from "../../../components/select";
@@ -18,10 +16,7 @@ export class ClusterWorkspaceSetting extends React.Component<Props> {
<>
<SubTitle title="Cluster Workspace"/>
<p>
Define cluster{" "}
<Link to={workspacesURL()}>
workspace
</Link>.
Define cluster workspace.
</p>
<Select
value={this.props.cluster.workspace}
@@ -25,4 +25,4 @@ export class General extends React.Component<Props> {
<ClusterAccessibleNamespaces cluster={this.props.cluster} />
</div>;
}
}
}
@@ -1,2 +1,3 @@
export * from "./cluster-settings.route";
export * from "./cluster-settings";
export * from "./cluster-settings.command";
@@ -17,4 +17,4 @@ export class Removal extends React.Component<Props> {
</div>
);
}
}
}
@@ -58,4 +58,4 @@ export class Status extends React.Component<Props> {
</div>
</div>;
}
}
}
@@ -23,11 +23,13 @@ interface IWarning extends ItemObject {
kind: string;
message: string;
selfLink: string;
age: string | number;
}
enum sortBy {
type = "type",
object = "object"
object = "object",
age = "age",
}
@observer
@@ -35,6 +37,7 @@ export class ClusterIssues extends React.Component<Props> {
private sortCallbacks = {
[sortBy.type]: (warning: IWarning) => warning.kind,
[sortBy.object]: (warning: IWarning) => warning.getName(),
[sortBy.age]: (warning: IWarning) => warning.age || "",
};
@computed get warnings() {
@@ -42,15 +45,16 @@ export class ClusterIssues extends React.Component<Props> {
// Node bad conditions
nodesStore.items.forEach(node => {
const { kind, selfLink, getId, getName } = node;
const { kind, selfLink, getId, getName, getAge } = node;
node.getWarningConditions().forEach(({ message }) => {
warnings.push({
kind,
age: getAge(),
getId,
getName,
selfLink,
kind,
message,
selfLink,
});
});
});
@@ -59,12 +63,13 @@ export class ClusterIssues extends React.Component<Props> {
const events = eventStore.getWarnings();
events.forEach(error => {
const { message, involvedObject } = error;
const { message, involvedObject, getAge } = error;
const { uid, name, kind } = involvedObject;
warnings.push({
getId: () => uid,
getName: () => name,
age: getAge(),
message,
kind,
selfLink: lookupApiLink(involvedObject, error),
@@ -78,7 +83,7 @@ export class ClusterIssues extends React.Component<Props> {
getTableRow(uid: string) {
const { warnings } = this;
const warning = warnings.find(warn => warn.getId() == uid);
const { getId, getName, message, kind, selfLink } = warning;
const { getId, getName, message, kind, selfLink, age } = warning;
return (
<TableRow
@@ -96,6 +101,9 @@ export class ClusterIssues extends React.Component<Props> {
<TableCell className="kind">
{kind}
</TableCell>
<TableCell className="age">
{age}
</TableCell>
</TableRow>
);
}
@@ -139,6 +147,7 @@ export class ClusterIssues extends React.Component<Props> {
<TableCell className="message">Message</TableCell>
<TableCell className="object" sortBy={sortBy.object}>Object</TableCell>
<TableCell className="kind" sortBy={sortBy.type}>Type</TableCell>
<TableCell className="timestamp" sortBy={sortBy.age}>Age</TableCell>
</TableHead>
</Table>
</>
@@ -95,4 +95,4 @@ export const ClusterMetrics = observer(() => {
{renderMetrics()}
</div>
);
});
});
@@ -3,13 +3,9 @@ import "./cluster-overview.scss";
import React from "react";
import { reaction } from "mobx";
import { disposeOnUnmount, observer } from "mobx-react";
import { eventStore } from "../+events/event.store";
import { nodesStore } from "../+nodes/nodes.store";
import { podsStore } from "../+workloads-pods/pods.store";
import { getHostedCluster } from "../../../common/cluster-store";
import { isAllowedResource } from "../../../common/rbac";
import { KubeObjectStore } from "../../kube-object.store";
import { interval } from "../../utils";
import { TabLayout } from "../layout/tab-layout";
import { Spinner } from "../spinner";
@@ -20,42 +16,24 @@ import { ClusterPieCharts } from "./cluster-pie-charts";
@observer
export class ClusterOverview extends React.Component {
private stores: KubeObjectStore<any>[] = [];
private subscribers: Array<() => void> = [];
private metricPoller = interval(60, this.loadMetrics);
@disposeOnUnmount
fetchMetrics = reaction(
() => clusterOverviewStore.metricNodeRole, // Toggle Master/Worker node switcher
() => this.metricPoller.restart(true)
);
private metricPoller = interval(60, () => this.loadMetrics());
loadMetrics() {
getHostedCluster().available && clusterOverviewStore.loadMetrics();
}
async componentDidMount() {
if (isAllowedResource("nodes")) {
this.stores.push(nodesStore);
}
componentDidMount() {
this.metricPoller.start(true);
if (isAllowedResource("pods")) {
this.stores.push(podsStore);
}
if (isAllowedResource("events")) {
this.stores.push(eventStore);
}
await Promise.all(this.stores.map(store => store.loadAll()));
this.loadMetrics();
this.subscribers = this.stores.map(store => store.subscribe());
this.metricPoller.start();
disposeOnUnmount(this, [
reaction(
() => clusterOverviewStore.metricNodeRole, // Toggle Master/Worker node switcher
() => this.metricPoller.restart(true)
),
]);
}
componentWillUnmount() {
this.subscribers.forEach(dispose => dispose()); // unsubscribe all
this.metricPoller.stop();
}
@@ -143,7 +143,7 @@ export const ClusterPieCharts = observer(() => {
<div className="chart flex column align-center box grow">
<PieChart
data={cpuData}
title={`CPU`}
title="CPU"
legendColors={["#c93dce", "#4caf50", "#3d90ce", defaultColor]}
/>
{cpuLimitsOverload && renderLimitWarning()}
@@ -151,7 +151,7 @@ export const ClusterPieCharts = observer(() => {
<div className="chart flex column align-center box grow">
<PieChart
data={memoryData}
title={`Memory`}
title="Memory"
legendColors={["#c93dce", "#4caf50", "#3d90ce", defaultColor]}
/>
{memoryLimitsOverload && renderLimitWarning()}
@@ -159,7 +159,7 @@ export const ClusterPieCharts = observer(() => {
<div className="chart flex column align-center box grow">
<PieChart
data={podsData}
title={`Pods`}
title="Pods"
legendColors={["#4caf50", defaultColor]}
/>
</div>
@@ -11,13 +11,15 @@ import { Badge } from "../badge";
import { cssNames } from "../../utils";
import { KubeObjectStatusIcon } from "../kube-object-status-icon";
enum sortBy {
enum columnId {
name = "name",
namespace = "namespace",
metrics = "metrics",
minPods = "min-pods",
maxPods = "max-pods",
replicas = "replicas",
age = "age",
status = "status"
}
interface Props extends RouteComponentProps<IHpaRouteParams> {
@@ -37,28 +39,30 @@ export class HorizontalPodAutoscalers extends React.Component<Props> {
render() {
return (
<KubeObjectListLayout
isConfigurable
tableId="configuration_hpa"
className="HorizontalPodAutoscalers" store={hpaStore}
sortingCallbacks={{
[sortBy.name]: (item: HorizontalPodAutoscaler) => item.getName(),
[sortBy.namespace]: (item: HorizontalPodAutoscaler) => item.getNs(),
[sortBy.minPods]: (item: HorizontalPodAutoscaler) => item.getMinPods(),
[sortBy.maxPods]: (item: HorizontalPodAutoscaler) => item.getMaxPods(),
[sortBy.replicas]: (item: HorizontalPodAutoscaler) => item.getReplicas()
[columnId.name]: (item: HorizontalPodAutoscaler) => item.getName(),
[columnId.namespace]: (item: HorizontalPodAutoscaler) => item.getNs(),
[columnId.minPods]: (item: HorizontalPodAutoscaler) => item.getMinPods(),
[columnId.maxPods]: (item: HorizontalPodAutoscaler) => item.getMaxPods(),
[columnId.replicas]: (item: HorizontalPodAutoscaler) => item.getReplicas()
}}
searchFilters={[
(item: HorizontalPodAutoscaler) => item.getSearchFields()
]}
renderHeaderTitle="Horizontal Pod Autoscalers"
renderTableHeader={[
{ title: "Name", className: "name", sortBy: sortBy.name },
{ className: "warning" },
{ title: "Namespace", className: "namespace", sortBy: sortBy.namespace },
{ title: "Metrics", className: "metrics" },
{ title: "Min Pods", className: "min-pods", sortBy: sortBy.minPods },
{ title: "Max Pods", className: "max-pods", sortBy: sortBy.maxPods },
{ title: "Replicas", className: "replicas", sortBy: sortBy.replicas },
{ title: "Age", className: "age", sortBy: sortBy.age },
{ title: "Status", className: "status" },
{ title: "Name", className: "name", sortBy: columnId.name },
{ className: "warning", showWithColumn: columnId.name },
{ title: "Namespace", className: "namespace", sortBy: columnId.namespace, id: columnId.namespace },
{ title: "Metrics", className: "metrics", id: columnId.metrics },
{ title: "Min Pods", className: "min-pods", sortBy: columnId.minPods, id: columnId.minPods },
{ title: "Max Pods", className: "max-pods", sortBy: columnId.maxPods, id: columnId.maxPods },
{ title: "Replicas", className: "replicas", sortBy: columnId.replicas, id: columnId.replicas },
{ title: "Age", className: "age", sortBy: columnId.age, id: columnId.age },
{ title: "Status", className: "status", id: columnId.status },
]}
renderTableContents={(hpa: HorizontalPodAutoscaler) => [
hpa.getName(),
@@ -0,0 +1,3 @@
export * from "./limit-ranges";
export * from "./limit-ranges.route";
export * from "./limit-range-details";
@@ -0,0 +1,12 @@
.LimitRangeDetails {
.DrawerItem {
> .name {
font-weight: $font-weight-normal;
padding-left: 4px;
}
.DrawerItem {
padding-top: 4px;
}
}
}
@@ -0,0 +1,97 @@
import "./limit-range-details.scss";
import React from "react";
import { observer } from "mobx-react";
import { KubeObjectDetailsProps } from "../kube-object";
import { LimitPart, LimitRange, LimitRangeItem, Resource } from "../../api/endpoints/limit-range.api";
import { kubeObjectDetailRegistry } from "../../api/kube-object-detail-registry";
import { KubeObjectMeta } from "../kube-object/kube-object-meta";
import { DrawerItem } from "../drawer/drawer-item";
import { Badge } from "../badge";
interface Props extends KubeObjectDetailsProps<LimitRange> {
}
function renderLimit(limit: LimitRangeItem, part: LimitPart, resource: Resource) {
const resourceLimit = limit[part]?.[resource];
if (!resourceLimit) {
return null;
}
return <Badge label={`${part}:${resourceLimit}`}/>;
}
function renderResourceLimits(limit: LimitRangeItem, resource: Resource) {
return (
<React.Fragment key={limit.type + resource}>
{renderLimit(limit, LimitPart.MIN, resource)}
{renderLimit(limit, LimitPart.MAX, resource)}
{renderLimit(limit, LimitPart.DEFAULT, resource)}
{renderLimit(limit, LimitPart.DEFAULT_REQUEST, resource)}
{renderLimit(limit, LimitPart.MAX_LIMIT_REQUEST_RATIO, resource)}
</React.Fragment>
);
}
function renderLimitDetails(limits: LimitRangeItem[], resources: Resource[]) {
return resources.map(resource =>
<DrawerItem key={resource} name={resource}>
{
limits.map(limit =>
renderResourceLimits(limit, resource)
)
}
</DrawerItem>
);
}
@observer
export class LimitRangeDetails extends React.Component<Props> {
render() {
const { object: limitRange } = this.props;
if (!limitRange) return null;
const containerLimits = limitRange.getContainerLimits();
const podLimits = limitRange.getPodLimits();
const pvcLimits = limitRange.getPVCLimits();
return (
<div className="LimitRangeDetails">
<KubeObjectMeta object={limitRange}/>
{containerLimits.length > 0 &&
<DrawerItem name="Container Limits" labelsOnly>
{
renderLimitDetails(containerLimits, [Resource.CPU, Resource.MEMORY, Resource.EPHEMERAL_STORAGE])
}
</DrawerItem>
}
{podLimits.length > 0 &&
<DrawerItem name="Pod Limits" labelsOnly>
{
renderLimitDetails(podLimits, [Resource.CPU, Resource.MEMORY, Resource.EPHEMERAL_STORAGE])
}
</DrawerItem>
}
{pvcLimits.length > 0 &&
<DrawerItem name="Persistent Volume Claim Limits" labelsOnly>
{
renderLimitDetails(pvcLimits, [Resource.STORAGE])
}
</DrawerItem>
}
</div>
);
}
}
kubeObjectDetailRegistry.add({
kind: "LimitRange",
apiVersions: ["v1"],
components: {
Details: (props) => <LimitRangeDetails {...props} />
}
});
@@ -0,0 +1,11 @@
import type { RouteProps } from "react-router";
import { buildURL } from "../../../common/utils/buildUrl";
export const limitRangesRoute: RouteProps = {
path: "/limitranges"
};
export interface LimitRangeRouteParams {
}
export const limitRangeURL = buildURL<LimitRangeRouteParams>(limitRangesRoute.path);
@@ -0,0 +1,7 @@
.LimitRanges {
.TableCell {
&.warning {
@include table-cell-warning;
}
}
}
@@ -0,0 +1,12 @@
import { autobind } from "../../../common/utils/autobind";
import { KubeObjectStore } from "../../kube-object.store";
import { apiManager } from "../../api/api-manager";
import { LimitRange, limitRangeApi } from "../../api/endpoints/limit-range.api";
@autobind()
export class LimitRangesStore extends KubeObjectStore<LimitRange> {
api = limitRangeApi;
}
export const limitRangeStore = new LimitRangesStore();
apiManager.registerStore(limitRangeStore);
@@ -0,0 +1,55 @@
import "./limit-ranges.scss";
import { RouteComponentProps } from "react-router";
import { observer } from "mobx-react";
import { KubeObjectListLayout } from "../kube-object/kube-object-list-layout";
import { limitRangeStore } from "./limit-ranges.store";
import { LimitRangeRouteParams } from "./limit-ranges.route";
import React from "react";
import { KubeObjectStatusIcon } from "../kube-object-status-icon";
import { LimitRange } from "../../api/endpoints/limit-range.api";
enum columnId {
name = "name",
namespace = "namespace",
age = "age",
}
interface Props extends RouteComponentProps<LimitRangeRouteParams> {
}
@observer
export class LimitRanges extends React.Component<Props> {
render() {
return (
<KubeObjectListLayout
isConfigurable
tableId="configuration_limitranges"
className="LimitRanges"
store={limitRangeStore}
sortingCallbacks={{
[columnId.name]: (item: LimitRange) => item.getName(),
[columnId.namespace]: (item: LimitRange) => item.getNs(),
[columnId.age]: (item: LimitRange) => item.getTimeDiffFromNow(),
}}
searchFilters={[
(item: LimitRange) => item.getName(),
(item: LimitRange) => item.getNs(),
]}
renderHeaderTitle={"Limit Ranges"}
renderTableHeader={[
{ title: "Name", className: "name", sortBy: columnId.name, id: columnId.name },
{ className: "warning", showWithColumn: columnId.name },
{ title: "Namespace", className: "namespace", sortBy: columnId.namespace, id: columnId.namespace },
{ title: "Age", className: "age", sortBy: columnId.age, id: columnId.age },
]}
renderTableContents={(limitRange: LimitRange) => [
limitRange.getName(),
<KubeObjectStatusIcon key="icon" object={limitRange}/>,
limitRange.getNs(),
limitRange.getAge(),
]}
/>
);
}
}
@@ -9,7 +9,7 @@ import { KubeObjectListLayout } from "../kube-object";
import { IConfigMapsRouteParams } from "./config-maps.route";
import { KubeObjectStatusIcon } from "../kube-object-status-icon";
enum sortBy {
enum columnId {
name = "name",
namespace = "namespace",
keys = "keys",
@@ -24,12 +24,14 @@ export class ConfigMaps extends React.Component<Props> {
render() {
return (
<KubeObjectListLayout
isConfigurable
tableId="configuration_configmaps"
className="ConfigMaps" store={configMapsStore}
sortingCallbacks={{
[sortBy.name]: (item: ConfigMap) => item.getName(),
[sortBy.namespace]: (item: ConfigMap) => item.getNs(),
[sortBy.keys]: (item: ConfigMap) => item.getKeys(),
[sortBy.age]: (item: ConfigMap) => item.metadata.creationTimestamp,
[columnId.name]: (item: ConfigMap) => item.getName(),
[columnId.namespace]: (item: ConfigMap) => item.getNs(),
[columnId.keys]: (item: ConfigMap) => item.getKeys(),
[columnId.age]: (item: ConfigMap) => item.getTimeDiffFromNow(),
}}
searchFilters={[
(item: ConfigMap) => item.getSearchFields(),
@@ -37,11 +39,11 @@ export class ConfigMaps extends React.Component<Props> {
]}
renderHeaderTitle="Config Maps"
renderTableHeader={[
{ title: "Name", className: "name", sortBy: sortBy.name },
{ className: "warning" },
{ title: "Namespace", className: "namespace", sortBy: sortBy.namespace },
{ title: "Keys", className: "keys", sortBy: sortBy.keys },
{ title: "Age", className: "age", sortBy: sortBy.age },
{ title: "Name", className: "name", sortBy: columnId.name, id: columnId.name },
{ className: "warning", showWithColumn: columnId.name },
{ title: "Namespace", className: "namespace", sortBy: columnId.namespace, id: columnId.namespace },
{ title: "Keys", className: "keys", sortBy: columnId.keys, id: columnId.keys },
{ title: "Age", className: "age", sortBy: columnId.age, id: columnId.age },
]}
renderTableContents={(configMap: ConfigMap) => [
configMap.getName(),
@@ -7,7 +7,7 @@ import { PodDisruptionBudget } from "../../api/endpoints/poddisruptionbudget.api
import { KubeObjectDetailsProps, KubeObjectListLayout } from "../kube-object";
import { KubeObjectStatusIcon } from "../kube-object-status-icon";
enum sortBy {
enum columnId {
name = "name",
namespace = "namespace",
minAvailable = "min-available",
@@ -25,30 +25,32 @@ export class PodDisruptionBudgets extends React.Component<Props> {
render() {
return (
<KubeObjectListLayout
isConfigurable
tableId="configuration_distribution_budgets"
className="PodDisruptionBudgets"
store={podDisruptionBudgetsStore}
sortingCallbacks={{
[sortBy.name]: (pdb: PodDisruptionBudget) => pdb.getName(),
[sortBy.namespace]: (pdb: PodDisruptionBudget) => pdb.getNs(),
[sortBy.minAvailable]: (pdb: PodDisruptionBudget) => pdb.getMinAvailable(),
[sortBy.maxUnavailable]: (pdb: PodDisruptionBudget) => pdb.getMaxUnavailable(),
[sortBy.currentHealthy]: (pdb: PodDisruptionBudget) => pdb.getCurrentHealthy(),
[sortBy.desiredHealthy]: (pdb: PodDisruptionBudget) => pdb.getDesiredHealthy(),
[sortBy.age]: (pdb: PodDisruptionBudget) => pdb.getAge(),
[columnId.name]: (pdb: PodDisruptionBudget) => pdb.getName(),
[columnId.namespace]: (pdb: PodDisruptionBudget) => pdb.getNs(),
[columnId.minAvailable]: (pdb: PodDisruptionBudget) => pdb.getMinAvailable(),
[columnId.maxUnavailable]: (pdb: PodDisruptionBudget) => pdb.getMaxUnavailable(),
[columnId.currentHealthy]: (pdb: PodDisruptionBudget) => pdb.getCurrentHealthy(),
[columnId.desiredHealthy]: (pdb: PodDisruptionBudget) => pdb.getDesiredHealthy(),
[columnId.age]: (pdb: PodDisruptionBudget) => pdb.getAge(),
}}
searchFilters={[
(pdb: PodDisruptionBudget) => pdb.getSearchFields(),
]}
renderHeaderTitle="Pod Disruption Budgets"
renderTableHeader={[
{ title: "Name", className: "name", sortBy: sortBy.name },
{ className: "warning" },
{ title: "Namespace", className: "namespace", sortBy: sortBy.namespace },
{ title: "Min Available", className: "min-available", sortBy: sortBy.minAvailable },
{ title: "Max Unavailable", className: "max-unavailable", sortBy: sortBy.maxUnavailable },
{ title: "Current Healthy", className: "current-healthy", sortBy: sortBy.currentHealthy },
{ title: "Desired Healthy", className: "desired-healthy", sortBy: sortBy.desiredHealthy },
{ title: "Age", className: "age", sortBy: sortBy.age },
{ title: "Name", className: "name", sortBy: columnId.name, id: columnId.name },
{ className: "warning", showWithColumn: columnId.name },
{ title: "Namespace", className: "namespace", sortBy: columnId.namespace, id: columnId.namespace },
{ title: "Min Available", className: "min-available", sortBy: columnId.minAvailable, id: columnId.minAvailable },
{ title: "Max Unavailable", className: "max-unavailable", sortBy: columnId.maxUnavailable, id: columnId.maxUnavailable },
{ title: "Current Healthy", className: "current-healthy", sortBy: columnId.currentHealthy, id: columnId.currentHealthy },
{ title: "Desired Healthy", className: "desired-healthy", sortBy: columnId.desiredHealthy, id: columnId.desiredHealthy },
{ title: "Age", className: "age", sortBy: columnId.age, id: columnId.age },
]}
renderTableContents={(pdb: PodDisruptionBudget) => {
return [
@@ -146,7 +146,7 @@ export class AddQuotaDialog extends React.Component<Props> {
<div className="flex gaps">
<Input
required autoFocus
placeholder={`ResourceQuota name`}
placeholder="ResourceQuota name"
validators={systemName}
value={this.quotaName} onChange={v => this.quotaName = v.toLowerCase()}
className="box grow"
@@ -156,7 +156,7 @@ export class AddQuotaDialog extends React.Component<Props> {
<SubTitle title="Namespace" />
<NamespaceSelect
value={this.namespace}
placeholder={`Namespace`}
placeholder="Namespace"
themeName="light"
className="box grow"
onChange={({ value }) => this.namespace = value}
@@ -167,14 +167,14 @@ export class AddQuotaDialog extends React.Component<Props> {
<Select
className="quota-select"
themeName="light"
placeholder={`Select a quota..`}
placeholder="Select a quota.."
options={this.quotaOptions}
value={this.quotaSelectValue}
onChange={({ value }) => this.quotaSelectValue = value}
/>
<Input
maxLength={10}
placeholder={`Value`}
placeholder="Value"
value={this.quotaInputValue}
onChange={v => this.quotaInputValue = v}
onKeyDown={this.onInputQuota}
@@ -183,7 +183,7 @@ export class AddQuotaDialog extends React.Component<Props> {
<Button round primary onClick={this.setQuota}>
<Icon
material={this.quotas[this.quotaSelectValue] ? "edit" : "add"}
tooltip={`Set quota`}
tooltip="Set quota"
/>
</Button>
</div>
@@ -10,7 +10,7 @@ import { resourceQuotaStore } from "./resource-quotas.store";
import { IResourceQuotaRouteParams } from "./resource-quotas.route";
import { KubeObjectStatusIcon } from "../kube-object-status-icon";
enum sortBy {
enum columnId {
name = "name",
namespace = "namespace",
age = "age"
@@ -25,11 +25,13 @@ export class ResourceQuotas extends React.Component<Props> {
return (
<>
<KubeObjectListLayout
isConfigurable
tableId="configuration_quotas"
className="ResourceQuotas" store={resourceQuotaStore}
sortingCallbacks={{
[sortBy.name]: (item: ResourceQuota) => item.getName(),
[sortBy.namespace]: (item: ResourceQuota) => item.getNs(),
[sortBy.age]: (item: ResourceQuota) => item.metadata.creationTimestamp,
[columnId.name]: (item: ResourceQuota) => item.getName(),
[columnId.namespace]: (item: ResourceQuota) => item.getNs(),
[columnId.age]: (item: ResourceQuota) => item.getTimeDiffFromNow(),
}}
searchFilters={[
(item: ResourceQuota) => item.getSearchFields(),
@@ -37,10 +39,10 @@ export class ResourceQuotas extends React.Component<Props> {
]}
renderHeaderTitle="Resource Quotas"
renderTableHeader={[
{ title: "Name", className: "name", sortBy: sortBy.name },
{ className: "warning" },
{ title: "Namespace", className: "namespace", sortBy: sortBy.namespace },
{ title: "Age", className: "age", sortBy: sortBy.age },
{ title: "Name", className: "name", sortBy: columnId.name, id: columnId.name },
{ className: "warning", showWithColumn: columnId.name },
{ title: "Namespace", className: "namespace", sortBy: columnId.namespace, id: columnId.namespace },
{ title: "Age", className: "age", sortBy: columnId.age, id: columnId.age },
]}
renderTableContents={(resourceQuota: ResourceQuota) => [
resourceQuota.getName(),
@@ -133,7 +133,7 @@ export class AddSecretDialog extends React.Component<Props> {
<SubTitle compact className="fields-title" title={upperFirst(field.toString())}>
<Icon
small
tooltip={`Add field`}
tooltip="Add field"
material="add_circle_outline"
onClick={() => this.addField(field)}
/>
@@ -146,7 +146,7 @@ export class AddSecretDialog extends React.Component<Props> {
<div key={index} className="secret-field flex gaps auto align-center">
<Input
className="key"
placeholder={`Name`}
placeholder="Name"
title={key}
tabIndex={required ? -1 : 0}
readOnly={required}
@@ -156,7 +156,7 @@ export class AddSecretDialog extends React.Component<Props> {
multiLine maxRows={5}
required={required}
className="value"
placeholder={`Value`}
placeholder="Value"
value={value} onChange={v => item.value = v}
/>
<Icon
@@ -194,7 +194,7 @@ export class AddSecretDialog extends React.Component<Props> {
<SubTitle title="Secret name" />
<Input
autoFocus required
placeholder={`Name`}
placeholder="Name"
validators={systemName}
value={name} onChange={v => this.name = v}
/>
@@ -69,7 +69,7 @@ export class SecretDetails extends React.Component<Props> {
</DrawerItem>
{!isEmpty(this.data) && (
<>
<DrawerTitle title={`Data`}/>
<DrawerTitle title="Data"/>
{
Object.entries(this.data).map(([name, value]) => {
const revealSecret = this.revealSecret[name];
@@ -107,7 +107,7 @@ export class SecretDetails extends React.Component<Props> {
}
<Button
primary
label={`Save`} waiting={this.isSaving}
label="Save" waiting={this.isSaving}
className="save-btn"
onClick={this.saveSecret}
/>
@@ -11,7 +11,7 @@ import { Badge } from "../badge";
import { secretsStore } from "./secrets.store";
import { KubeObjectStatusIcon } from "../kube-object-status-icon";
enum sortBy {
enum columnId {
name = "name",
namespace = "namespace",
labels = "labels",
@@ -29,14 +29,16 @@ export class Secrets extends React.Component<Props> {
return (
<>
<KubeObjectListLayout
isConfigurable
tableId="configuration_secrets"
className="Secrets" store={secretsStore}
sortingCallbacks={{
[sortBy.name]: (item: Secret) => item.getName(),
[sortBy.namespace]: (item: Secret) => item.getNs(),
[sortBy.labels]: (item: Secret) => item.getLabels(),
[sortBy.keys]: (item: Secret) => item.getKeys(),
[sortBy.type]: (item: Secret) => item.type,
[sortBy.age]: (item: Secret) => item.metadata.creationTimestamp,
[columnId.name]: (item: Secret) => item.getName(),
[columnId.namespace]: (item: Secret) => item.getNs(),
[columnId.labels]: (item: Secret) => item.getLabels(),
[columnId.keys]: (item: Secret) => item.getKeys(),
[columnId.type]: (item: Secret) => item.type,
[columnId.age]: (item: Secret) => item.getTimeDiffFromNow(),
}}
searchFilters={[
(item: Secret) => item.getSearchFields(),
@@ -44,13 +46,13 @@ export class Secrets extends React.Component<Props> {
]}
renderHeaderTitle="Secrets"
renderTableHeader={[
{ title: "Name", className: "name", sortBy: sortBy.name },
{ className: "warning" },
{ title: "Namespace", className: "namespace", sortBy: sortBy.namespace },
{ title: "Labels", className: "labels", sortBy: sortBy.labels },
{ title: "Keys", className: "keys", sortBy: sortBy.keys },
{ title: "Type", className: "type", sortBy: sortBy.type },
{ title: "Age", className: "age", sortBy: sortBy.age },
{ title: "Name", className: "name", sortBy: columnId.name, id: columnId.name },
{ className: "warning", showWithColumn: columnId.name },
{ title: "Namespace", className: "namespace", sortBy: columnId.namespace, id: columnId.namespace },
{ title: "Labels", className: "labels", sortBy: columnId.labels, id: columnId.labels },
{ title: "Keys", className: "keys", sortBy: columnId.keys, id: columnId.keys },
{ title: "Type", className: "type", sortBy: columnId.type, id: columnId.type },
{ title: "Age", className: "age", sortBy: columnId.age, id: columnId.age },
]}
renderTableContents={(secret: Secret) => [
secret.getName(),
@@ -0,0 +1,50 @@
import { navigate } from "../../navigation";
import { commandRegistry } from "../../../extensions/registries/command-registry";
import { configMapsURL } from "../+config-maps";
import { secretsURL } from "../+config-secrets";
import { resourceQuotaURL } from "../+config-resource-quotas";
import { limitRangeURL } from "../+config-limit-ranges";
import { hpaURL } from "../+config-autoscalers";
import { pdbURL } from "../+config-pod-disruption-budgets";
commandRegistry.add({
id: "cluster.viewConfigMaps",
title: "Cluster: View ConfigMaps",
scope: "cluster",
action: () => navigate(configMapsURL())
});
commandRegistry.add({
id: "cluster.viewSecrets",
title: "Cluster: View Secrets",
scope: "cluster",
action: () => navigate(secretsURL())
});
commandRegistry.add({
id: "cluster.viewResourceQuotas",
title: "Cluster: View ResourceQuotas",
scope: "cluster",
action: () => navigate(resourceQuotaURL())
});
commandRegistry.add({
id: "cluster.viewLimitRanges",
title: "Cluster: View LimitRanges",
scope: "cluster",
action: () => navigate(limitRangeURL())
});
commandRegistry.add({
id: "cluster.viewHorizontalPodAutoscalers",
title: "Cluster: View HorizontalPodAutoscalers (HPA)",
scope: "cluster",
action: () => navigate(hpaURL())
});
commandRegistry.add({
id: "cluster.viewPodDisruptionBudget",
title: "Cluster: View PodDisruptionBudgets",
scope: "cluster",
action: () => navigate(pdbURL())
});
@@ -8,6 +8,7 @@ import { resourceQuotaRoute, ResourceQuotas, resourceQuotaURL } from "../+config
import { pdbRoute, pdbURL, PodDisruptionBudgets } from "../+config-pod-disruption-budgets";
import { HorizontalPodAutoscalers, hpaRoute, hpaURL } from "../+config-autoscalers";
import { isAllowedResource } from "../../../common/rbac";
import { LimitRanges, limitRangesRoute, limitRangeURL } from "../+config-limit-ranges";
@observer
export class Config extends React.Component {
@@ -42,6 +43,15 @@ export class Config extends React.Component {
});
}
if (isAllowedResource("limitranges")) {
routes.push({
title: "Limit Ranges",
component: LimitRanges,
url: limitRangeURL({ query }),
routePath: limitRangesRoute.path.toString(),
});
}
if (isAllowedResource("horizontalpodautoscalers")) {
routes.push({
title: "HPA",
+1
View File
@@ -1,2 +1,3 @@
export * from "./config.route";
export * from "./config";
export * from "./config.command";
@@ -19,7 +19,7 @@ export const crdGroupsUrlParam = createPageParam<string[]>({
defaultValue: [],
});
enum sortBy {
enum columnId {
kind = "kind",
group = "group",
version = "version",
@@ -47,14 +47,16 @@ export class CrdList extends React.Component {
render() {
const selectedGroups = this.groups;
const sortingCallbacks = {
[sortBy.kind]: (crd: CustomResourceDefinition) => crd.getResourceKind(),
[sortBy.group]: (crd: CustomResourceDefinition) => crd.getGroup(),
[sortBy.version]: (crd: CustomResourceDefinition) => crd.getVersion(),
[sortBy.scope]: (crd: CustomResourceDefinition) => crd.getScope(),
[columnId.kind]: (crd: CustomResourceDefinition) => crd.getResourceKind(),
[columnId.group]: (crd: CustomResourceDefinition) => crd.getGroup(),
[columnId.version]: (crd: CustomResourceDefinition) => crd.getVersion(),
[columnId.scope]: (crd: CustomResourceDefinition) => crd.getScope(),
};
return (
<KubeObjectListLayout
isConfigurable
tableId="crd"
className="CrdList"
isClusterScoped={true}
store={crdStore}
@@ -97,11 +99,11 @@ export class CrdList extends React.Component {
};
}}
renderTableHeader={[
{ title: "Resource", className: "kind", sortBy: sortBy.kind },
{ title: "Group", className: "group", sortBy: sortBy.group },
{ title: "Version", className: "version", sortBy: sortBy.group },
{ title: "Scope", className: "scope", sortBy: sortBy.scope },
{ title: "Age", className: "age", sortBy: sortBy.age },
{ title: "Resource", className: "kind", sortBy: columnId.kind, id: columnId.kind },
{ title: "Group", className: "group", sortBy: columnId.group, id: columnId.group },
{ title: "Version", className: "version", sortBy: columnId.version, id: columnId.version },
{ title: "Scope", className: "scope", sortBy: columnId.scope, id: columnId.scope },
{ title: "Age", className: "age", sortBy: columnId.age, id: columnId.age },
]}
renderTableContents={(crd: CustomResourceDefinition) => [
<Link key="link" to={crd.getResourceUrl()} onClick={stopPropagation}>
@@ -16,7 +16,7 @@ import { parseJsonPath } from "../../utils/jsonPath";
interface Props extends RouteComponentProps<ICRDRouteParams> {
}
enum sortBy {
enum columnId {
name = "name",
namespace = "namespace",
age = "age",
@@ -30,7 +30,7 @@ export class CrdResources extends React.Component<Props> {
const { store } = this;
if (store && !store.isLoading && !store.isLoaded) {
store.loadAll();
store.reloadAll();
}
})
]);
@@ -55,9 +55,9 @@ export class CrdResources extends React.Component<Props> {
const isNamespaced = crd.isNamespaced();
const extraColumns = crd.getPrinterColumns(false); // Cols with priority bigger than 0 are shown in details
const sortingCallbacks: { [sortBy: string]: TableSortCallback } = {
[sortBy.name]: (item: KubeObject) => item.getName(),
[sortBy.namespace]: (item: KubeObject) => item.getNs(),
[sortBy.age]: (item: KubeObject) => item.metadata.creationTimestamp,
[columnId.name]: (item: KubeObject) => item.getName(),
[columnId.namespace]: (item: KubeObject) => item.getNs(),
[columnId.age]: (item: KubeObject) => item.getTimeDiffFromNow(),
};
extraColumns.forEach(column => {
@@ -66,6 +66,8 @@ export class CrdResources extends React.Component<Props> {
return (
<KubeObjectListLayout
isConfigurable
tableId="crd_resources"
className="CrdResources"
isClusterScoped={!isNamespaced}
store={store}
@@ -75,18 +77,19 @@ export class CrdResources extends React.Component<Props> {
]}
renderHeaderTitle={crd.getResourceTitle()}
renderTableHeader={[
{ title: "Name", className: "name", sortBy: sortBy.name },
isNamespaced && { title: "Namespace", className: "namespace", sortBy: sortBy.namespace },
{ title: "Name", className: "name", sortBy: columnId.name, id: columnId.name },
isNamespaced && { title: "Namespace", className: "namespace", sortBy: columnId.namespace, id: columnId.namespace },
...extraColumns.map(column => {
const { name } = column;
return {
title: name,
className: name.toLowerCase(),
sortBy: name
sortBy: name,
id: name
};
}),
{ title: "Age", className: "age", sortBy: sortBy.age },
{ title: "Age", className: "age", sortBy: columnId.age, id: columnId.age },
]}
renderTableContents={(crdInstance: KubeObject) => [
crdInstance.getName(),
@@ -94,7 +97,7 @@ export class CrdResources extends React.Component<Props> {
...extraColumns.map((column) => {
let value = jsonPath.value(crdInstance, parseJsonPath(column.jsonPath.slice(1)));
if (Array.isArray(value) || typeof value === "object") {
if (Array.isArray(value) || typeof value === "object") {
value = JSON.stringify(value);
}
@@ -20,8 +20,8 @@ export class EventStore extends KubeObjectStore<KubeEvent> {
protected sortItems(items: KubeEvent[]) {
return super.sortItems(items, [
event => event.metadata.creationTimestamp
], "desc");
event => event.getTimeDiffFromNow(), // keep events order as timeline ("fresh" on top)
], "asc");
}
getEventsByObject(obj: KubeObject): KubeEvent[] {
@@ -52,6 +52,10 @@ export class EventStore extends KubeObjectStore<KubeEvent> {
return compact(eventsWithError);
}
getWarningsCount() {
return this.getWarnings().length;
}
}
export const eventStore = new EventStore();
+102 -42
View File
@@ -1,22 +1,29 @@
import "./events.scss";
import React, { Fragment } from "react";
import { computed, observable } from "mobx";
import { observer } from "mobx-react";
import { orderBy } from "lodash";
import { TabLayout } from "../layout/tab-layout";
import { eventStore } from "./event.store";
import { EventStore, eventStore } from "./event.store";
import { getDetailsUrl, KubeObjectListLayout, KubeObjectListLayoutProps } from "../kube-object";
import { KubeEvent } from "../../api/endpoints/events.api";
import { TableSortCallbacks, TableSortParams, TableProps } from "../table";
import { IHeaderPlaceholders } from "../item-object-list";
import { Tooltip } from "../tooltip";
import { Link } from "react-router-dom";
import { cssNames, IClassName, stopPropagation } from "../../utils";
import { Icon } from "../icon";
import { lookupApiLink } from "../../api/kube-api";
import { eventsURL } from "./events.route";
enum sortBy {
enum columnId {
message = "message",
namespace = "namespace",
object = "object",
type = "type",
count = "count",
source = "source",
age = "age",
}
@@ -34,60 +41,116 @@ const defaultProps: Partial<Props> = {
export class Events extends React.Component<Props> {
static defaultProps = defaultProps as object;
@observable sorting: TableSortParams = {
sortBy: columnId.age,
orderBy: "asc",
};
private sortingCallbacks: TableSortCallbacks = {
[columnId.namespace]: (event: KubeEvent) => event.getNs(),
[columnId.type]: (event: KubeEvent) => event.type,
[columnId.object]: (event: KubeEvent) => event.involvedObject.name,
[columnId.count]: (event: KubeEvent) => event.count,
[columnId.age]: (event: KubeEvent) => event.getTimeDiffFromNow(),
};
private tableConfiguration: TableProps = {
sortSyncWithUrl: false,
sortByDefault: this.sorting,
onSort: params => this.sorting = params,
};
get store(): EventStore {
return eventStore;
}
@computed get items(): KubeEvent[] {
const items = this.store.contextItems;
const { sortBy, orderBy: order } = this.sorting;
// we must sort items before passing to "KubeObjectListLayout -> Table"
// to make it work with "compact=true" (proper table sorting actions + initial items)
return orderBy(items, this.sortingCallbacks[sortBy], order as any);
}
@computed get visibleItems(): KubeEvent[] {
const { compact, compactLimit } = this.props;
if (compact) {
return this.items.slice(0, compactLimit);
}
return this.items;
}
customizeHeader = ({ info, title }: IHeaderPlaceholders) => {
const { compact } = this.props;
const { store, items, visibleItems } = this;
const allEventsAreShown = visibleItems.length === items.length;
// handle "compact"-mode header
if (compact) {
if (allEventsAreShown) return title; // title == "Events"
return <>
{title}
<span> ({visibleItems.length} of <Link to={eventsURL()}>{items.length}</Link>)</span>
</>;
}
return {
info: <>
{info}
<Icon
small
material="help_outline"
className="help-icon"
tooltip={`Limited to ${store.limit}`}
/>
</>
};
};
render() {
const { store, visibleItems } = this;
const { compact, compactLimit, className, ...layoutProps } = this.props;
const events = (
<KubeObjectListLayout
{...layoutProps}
isConfigurable
tableId="events"
store={store}
className={cssNames("Events", className, { compact })}
store={eventStore}
renderHeaderTitle="Events"
customizeHeader={this.customizeHeader}
isSelectable={false}
sortingCallbacks={{
[sortBy.namespace]: (event: KubeEvent) => event.getNs(),
[sortBy.type]: (event: KubeEvent) => event.involvedObject.kind,
[sortBy.object]: (event: KubeEvent) => event.involvedObject.name,
[sortBy.count]: (event: KubeEvent) => event.count,
[sortBy.age]: (event: KubeEvent) => event.metadata.creationTimestamp,
}}
items={visibleItems}
virtual={!compact}
tableProps={this.tableConfiguration}
sortingCallbacks={this.sortingCallbacks}
searchFilters={[
(event: KubeEvent) => event.getSearchFields(),
(event: KubeEvent) => event.message,
(event: KubeEvent) => event.getSource(),
(event: KubeEvent) => event.involvedObject.name,
]}
renderHeaderTitle="Events"
customizeHeader={({ title, info }) => (
compact ? title : ({
info: (
<>
{info}
<Icon
small
material="help_outline"
className="help-icon"
tooltip={`Limited to ${eventStore.limit}`}
/>
</>
)
})
)}
renderTableHeader={[
{ title: "Message", className: "message" },
{ title: "Namespace", className: "namespace", sortBy: sortBy.namespace },
{ title: "Type", className: "type", sortBy: sortBy.type },
{ title: "Involved Object", className: "object", sortBy: sortBy.object },
{ title: "Source", className: "source" },
{ title: "Count", className: "count", sortBy: sortBy.count },
{ title: "Age", className: "age", sortBy: sortBy.age },
{ title: "Type", className: "type", sortBy: columnId.type, id: columnId.type },
{ title: "Message", className: "message", id: columnId.message },
{ title: "Namespace", className: "namespace", sortBy: columnId.namespace, id: columnId.namespace },
{ title: "Involved Object", className: "object", sortBy: columnId.object, id: columnId.object },
{ title: "Source", className: "source", id: columnId.source },
{ title: "Count", className: "count", sortBy: columnId.count, id: columnId.count },
{ title: "Last Seen", className: "age", sortBy: columnId.age, id: columnId.age },
]}
renderTableContents={(event: KubeEvent) => {
const { involvedObject, type, message } = event;
const { kind, name } = involvedObject;
const tooltipId = `message-${event.getId()}`;
const isWarning = type === "Warning";
const detailsUrl = getDetailsUrl(lookupApiLink(involvedObject, event));
const isWarning = event.isWarning();
return [
type, // type of event: "Normal" or "Warning"
{
className: { warning: isWarning },
title: (
@@ -100,17 +163,14 @@ export class Events extends React.Component<Props> {
)
},
event.getNs(),
kind,
<Link key="link" to={detailsUrl} title={name} onClick={stopPropagation}>{name}</Link>,
<Link key="link" to={getDetailsUrl(lookupApiLink(involvedObject, event))} onClick={stopPropagation}>
{involvedObject.kind}: {involvedObject.name}
</Link>,
event.getSource(),
event.count,
event.getAge(),
];
}}
virtual={!compact}
filterItems={[
items => compact ? items.slice(0, compactLimit) : items,
]}
/>
);
@@ -14,7 +14,7 @@ export interface KubeEventDetailsProps {
@observer
export class KubeEventDetails extends React.Component<KubeEventDetailsProps> {
async componentDidMount() {
eventStore.loadAll();
eventStore.reloadAll();
}
render() {
@@ -1,2 +1,2 @@
export * from "./landing-page.route";
export * from "./landing-page";
export * from "./landing-page";
@@ -72,7 +72,7 @@ export class AddNamespaceDialog extends React.Component<Props> {
<Input
required autoFocus
iconLeft="layers"
placeholder={`Namespace`}
placeholder="Namespace"
validators={systemName}
value={namespace} onChange={v => this.namespace = v.toLowerCase()}
/>
@@ -12,6 +12,7 @@ import { Spinner } from "../spinner";
import { resourceQuotaStore } from "../+config-resource-quotas/resource-quotas.store";
import { KubeObjectMeta } from "../kube-object/kube-object-meta";
import { kubeObjectDetailRegistry } from "../../api/kube-object-detail-registry";
import { limitRangeStore } from "../+config-limit-ranges/limit-ranges.store";
interface Props extends KubeObjectDetailsProps<Namespace> {
}
@@ -24,8 +25,15 @@ export class NamespaceDetails extends React.Component<Props> {
return resourceQuotaStore.getAllByNs(namespace);
}
@computed get limitranges() {
const namespace = this.props.object.getName();
return limitRangeStore.getAllByNs(namespace);
}
componentDidMount() {
resourceQuotaStore.loadAll();
resourceQuotaStore.reloadAll();
limitRangeStore.reloadAll();
}
render() {
@@ -52,6 +60,16 @@ export class NamespaceDetails extends React.Component<Props> {
);
})}
</DrawerItem>
<DrawerItem name="Limit Ranges">
{!this.limitranges && limitRangeStore.isLoading && <Spinner/>}
{this.limitranges.map(limitrange => {
return (
<Link key={limitrange.getId()} to={getDetailsUrl(limitrange.selfLink)}>
{limitrange.getName()}
</Link>
);
})}
</DrawerItem>
</div>
);
}
@@ -0,0 +1,77 @@
import "./namespace-select.scss";
import React from "react";
import { observer } from "mobx-react";
import { components, PlaceholderProps } from "react-select";
import { Icon } from "../icon";
import { FilterIcon } from "../item-object-list/filter-icon";
import { FilterType } from "../item-object-list/page-filters.store";
import { SelectOption } from "../select";
import { NamespaceSelect } from "./namespace-select";
import { namespaceStore } from "./namespace.store";
const Placeholder = observer((props: PlaceholderProps<any>) => {
const getPlaceholder = (): React.ReactNode => {
const namespaces = namespaceStore.contextNamespaces;
switch (namespaces.length) {
case 0:
case namespaceStore.allowedNamespaces.length:
return <>All namespaces</>;
case 1:
return <>Namespace: {namespaces[0]}</>;
default:
return <>Namespaces: {namespaces.join(", ")}</>;
}
};
return (
<components.Placeholder {...props}>
{getPlaceholder()}
</components.Placeholder>
);
});
@observer
export class NamespaceSelectFilter extends React.Component {
formatOptionLabel({ value: namespace, label }: SelectOption) {
if (namespace) {
const isSelected = namespaceStore.hasContext(namespace);
return (
<div className="flex gaps align-center">
<FilterIcon type={FilterType.NAMESPACE}/>
<span>{namespace}</span>
{isSelected && <Icon small material="check" className="box right"/>}
</div>
);
}
return label;
}
onChange([{ value: namespace }]: SelectOption[]) {
if (namespace) {
namespaceStore.toggleContext(namespace);
} else {
namespaceStore.toggleAll(false); // "All namespaces" clicked
}
}
render() {
return (
<NamespaceSelect
isMulti={true}
components={{ Placeholder }}
showAllNamespacesOption={true}
closeMenuOnSelect={false}
controlShouldRenderValue={false}
placeholder={""}
onChange={this.onChange}
formatOptionLabel={this.formatOptionLabel}
/>
);
}
}
@@ -2,53 +2,50 @@ import "./namespace-select.scss";
import React from "react";
import { computed } from "mobx";
import { observer } from "mobx-react";
import { disposeOnUnmount, observer } from "mobx-react";
import { Select, SelectOption, SelectProps } from "../select";
import { cssNames, noop } from "../../utils";
import { cssNames } from "../../utils";
import { Icon } from "../icon";
import { namespaceStore } from "./namespace.store";
import { FilterIcon } from "../item-object-list/filter-icon";
import { FilterType } from "../item-object-list/page-filters.store";
import { kubeWatchApi } from "../../api/kube-watch-api";
interface Props extends SelectProps {
showIcons?: boolean;
showClusterOption?: boolean; // show cluster option on the top (default: false)
clusterOptionLabel?: React.ReactNode; // label for cluster option (default: "Cluster")
customizeOptions?(nsOptions: SelectOption[]): SelectOption[];
showClusterOption?: boolean; // show "Cluster" option on the top (default: false)
showAllNamespacesOption?: boolean; // show "All namespaces" option on the top (default: false)
customizeOptions?(options: SelectOption[]): SelectOption[];
}
const defaultProps: Partial<Props> = {
showIcons: true,
showClusterOption: false,
get clusterOptionLabel() {
return `Cluster`;
},
};
@observer
export class NamespaceSelect extends React.Component<Props> {
static defaultProps = defaultProps as object;
private unsubscribe = noop;
async componentDidMount() {
if (!namespaceStore.isLoaded) {
await namespaceStore.loadAll();
}
this.unsubscribe = namespaceStore.subscribe();
componentDidMount() {
disposeOnUnmount(this, [
kubeWatchApi.subscribeStores([namespaceStore], {
preload: true,
loadOnce: true, // skip reloading namespaces on every render / page visit
})
]);
}
componentWillUnmount() {
this.unsubscribe();
}
@computed get options(): SelectOption[] {
const { customizeOptions, showClusterOption, clusterOptionLabel } = this.props;
@computed.struct get options(): SelectOption[] {
const { customizeOptions, showClusterOption, showAllNamespacesOption } = this.props;
let options: SelectOption[] = namespaceStore.items.map(ns => ({ value: ns.getName() }));
options = customizeOptions ? customizeOptions(options) : options;
if (showAllNamespacesOption) {
options.unshift({ label: "All Namespaces", value: "" });
} else if (showClusterOption) {
options.unshift({ label: "Cluster", value: "" });
}
if (showClusterOption) {
options.unshift({ value: null, label: clusterOptionLabel });
if (customizeOptions) {
options = customizeOptions(options);
}
return options;
@@ -60,14 +57,14 @@ export class NamespaceSelect extends React.Component<Props> {
return label || (
<>
{showIcons && <Icon small material="layers" />}
{showIcons && <Icon small material="layers"/>}
{value}
</>
);
};
render() {
const { className, showIcons, showClusterOption, clusterOptionLabel, customizeOptions, ...selectProps } = this.props;
const { className, showIcons, customizeOptions, ...selectProps } = this.props;
return (
<Select
@@ -80,36 +77,3 @@ export class NamespaceSelect extends React.Component<Props> {
);
}
}
@observer
export class NamespaceSelectFilter extends React.Component {
render() {
const { contextNs, hasContext, toggleContext } = namespaceStore;
let placeholder = <>All namespaces</>;
if (contextNs.length == 1) placeholder = <>Namespace: {contextNs[0]}</>;
if (contextNs.length >= 2) placeholder = <>Namespaces: {contextNs.join(", ")}</>;
return (
<NamespaceSelect
placeholder={placeholder}
closeMenuOnSelect={false}
isOptionSelected={() => false}
controlShouldRenderValue={false}
isMulti
onChange={([{ value }]: SelectOption[]) => toggleContext(value)}
formatOptionLabel={({ value: namespace }: SelectOption) => {
const isSelected = hasContext(namespace);
return (
<div className="flex gaps align-center">
<FilterIcon type={FilterType.NAMESPACE} />
<span>{namespace}</span>
{isSelected && <Icon small material="check" className="box right" />}
</div>
);
}}
/>
);
}
}
@@ -1,120 +1,182 @@
import { action, comparer, observable, reaction } from "mobx";
import { action, comparer, computed, IReactionDisposer, IReactionOptions, observable, reaction } from "mobx";
import { autobind, createStorage } from "../../utils";
import { KubeObjectStore } from "../../kube-object.store";
import { Namespace, namespacesApi } from "../../api/endpoints";
import { KubeObjectStore, KubeObjectStoreLoadingParams } from "../../kube-object.store";
import { Namespace, namespacesApi } from "../../api/endpoints/namespaces.api";
import { createPageParam } from "../../navigation";
import { apiManager } from "../../api/api-manager";
import { isAllowedResource } from "../../../common/rbac";
import { getHostedCluster } from "../../../common/cluster-store";
const storage = createStorage<string[]>("context_namespaces", []);
const storage = createStorage<string[]>("context_namespaces");
export const namespaceUrlParam = createPageParam<string[]>({
name: "namespaces",
isSystem: true,
multiValues: true,
get defaultValue() {
return storage.get(); // initial namespaces coming from URL or local-storage (default)
return storage.get() ?? []; // initial namespaces coming from URL or local-storage (default)
}
});
export function getDummyNamespace(name: string) {
return new Namespace({
kind: Namespace.kind,
apiVersion: "v1",
metadata: {
name,
uid: "",
resourceVersion: "",
selfLink: `/api/v1/namespaces/${name}`
}
});
}
@autobind()
export class NamespaceStore extends KubeObjectStore<Namespace> {
api = namespacesApi;
contextNs = observable.array<string>();
@observable private contextNs = observable.set<string>();
constructor() {
super();
this.init();
}
private init() {
this.setContext(this.initNamespaces);
private async init() {
await this.contextReady;
return reaction(() => this.contextNs.toJS(), namespaces => {
this.setContext(this.initialNamespaces);
this.autoLoadAllowedNamespaces();
this.autoUpdateUrlAndLocalStorage();
}
public onContextChange(callback: (contextNamespaces: string[]) => void, opts: IReactionOptions = {}): IReactionDisposer {
return reaction(() => Array.from(this.contextNs), callback, {
equals: comparer.shallow,
...opts,
});
}
private autoUpdateUrlAndLocalStorage(): IReactionDisposer {
return this.onContextChange(namespaces => {
storage.set(namespaces); // save to local-storage
namespaceUrlParam.set(namespaces, { replaceHistory: true }); // update url
}, {
fireImmediately: true,
equals: comparer.identity,
});
}
get initNamespaces() {
return namespaceUrlParam.get();
private autoLoadAllowedNamespaces(): IReactionDisposer {
return reaction(() => this.allowedNamespaces, namespaces => this.loadAll({ namespaces }), {
fireImmediately: true,
equals: comparer.shallow,
});
}
getContextParams() {
return {
namespaces: this.contextNs.toJS(),
};
}
@computed
private get initialNamespaces(): string[] {
const namespaces = new Set(this.allowedNamespaces);
const prevSelectedNamespaces = storage.get();
subscribe(apis = [this.api]) {
const { accessibleNamespaces } = getHostedCluster();
// if user has given static list of namespaces let's not start watches because watch adds stuff that's not wanted
if (accessibleNamespaces.length > 0) {
return Function; // no-op
// return previously saved namespaces from local-storage (if any)
if (prevSelectedNamespaces) {
return prevSelectedNamespaces.filter(namespace => namespaces.has(namespace));
}
return super.subscribe(apis);
// otherwise select "default" or first allowed namespace
if (namespaces.has("default")) {
return ["default"];
} else if (namespaces.size) {
return [Array.from(namespaces)[0]];
}
return [];
}
protected async loadItems(namespaces?: string[]) {
if (!isAllowedResource("namespaces")) {
if (namespaces) return namespaces.map(this.getDummyNamespace);
@computed get allowedNamespaces(): string[] {
return Array.from(new Set([
...(this.context?.allNamespaces ?? []), // allowed namespaces from cluster (main), updating every 30s
...this.items.map(item => item.getName()), // loaded namespaces from k8s api
].flat()));
}
@computed get contextNamespaces(): string[] {
const namespaces = Array.from(this.contextNs);
if (!namespaces.length) {
return this.allowedNamespaces; // show all namespaces when nothing selected
}
return namespaces;
}
getSubscribeApis() {
// if user has given static list of namespaces let's not start watches because watch adds stuff that's not wanted
if (this.context?.cluster.accessibleNamespaces.length > 0) {
return [];
}
if (namespaces) {
return Promise.all(namespaces.map(name => this.api.get({ name })));
} else {
return super.loadItems();
}
return super.getSubscribeApis();
}
protected getDummyNamespace(name: string) {
return new Namespace({
kind: "Namespace",
apiVersion: "v1",
metadata: {
name,
uid: "",
resourceVersion: "",
selfLink: `/api/v1/namespaces/${name}`
}
});
protected async loadItems(params: KubeObjectStoreLoadingParams) {
const { allowedNamespaces } = this;
let namespaces = (await super.loadItems(params)) || [];
namespaces = namespaces.filter(namespace => allowedNamespaces.includes(namespace.getName()));
if (!namespaces.length && allowedNamespaces.length > 0) {
return allowedNamespaces.map(getDummyNamespace);
}
return namespaces;
}
@action
setContext(namespaces: string[]) {
setContext(namespace: string | string[]) {
const namespaces = [namespace].flat();
this.contextNs.replace(namespaces);
}
hasContext(namespace: string | string[]) {
const context = Array.isArray(namespace) ? namespace : [namespace];
@action
resetContext() {
this.contextNs.clear();
}
return context.every(namespace => this.contextNs.includes(namespace));
hasContext(namespaces: string | string[]) {
return [namespaces].flat().every(namespace => this.contextNs.has(namespace));
}
@computed get hasAllContexts(): boolean {
return this.contextNs.size === this.allowedNamespaces.length;
}
@action
toggleContext(namespace: string) {
if (this.hasContext(namespace)) this.contextNs.remove(namespace);
else this.contextNs.push(namespace);
if (this.hasContext(namespace)) {
this.contextNs.delete(namespace);
} else {
this.contextNs.add(namespace);
}
}
@action
reset() {
super.reset();
this.contextNs.clear();
toggleAll(showAll?: boolean) {
if (typeof showAll === "boolean") {
if (showAll) {
this.setContext(this.allowedNamespaces);
} else {
this.resetContext(); // empty context considered as "All namespaces"
}
} else {
this.toggleAll(!this.hasAllContexts);
}
}
@action
async remove(item: Namespace) {
await super.remove(item);
this.contextNs.remove(item.getName());
this.contextNs.delete(item.getName());
}
}
@@ -11,7 +11,7 @@ import { INamespacesRouteParams } from "./namespaces.route";
import { namespaceStore } from "./namespace.store";
import { KubeObjectStatusIcon } from "../kube-object-status-icon";
enum sortBy {
enum columnId {
name = "name",
labels = "labels",
age = "age",
@@ -27,12 +27,14 @@ export class Namespaces extends React.Component<Props> {
<TabLayout>
<KubeObjectListLayout
isClusterScoped
isConfigurable
tableId="namespaces"
className="Namespaces" store={namespaceStore}
sortingCallbacks={{
[sortBy.name]: (ns: Namespace) => ns.getName(),
[sortBy.labels]: (ns: Namespace) => ns.getLabels(),
[sortBy.age]: (ns: Namespace) => ns.metadata.creationTimestamp,
[sortBy.status]: (ns: Namespace) => ns.getStatus(),
[columnId.name]: (ns: Namespace) => ns.getName(),
[columnId.labels]: (ns: Namespace) => ns.getLabels(),
[columnId.age]: (ns: Namespace) => ns.getTimeDiffFromNow(),
[columnId.status]: (ns: Namespace) => ns.getStatus(),
}}
searchFilters={[
(item: Namespace) => item.getSearchFields(),
@@ -40,11 +42,11 @@ export class Namespaces extends React.Component<Props> {
]}
renderHeaderTitle="Namespaces"
renderTableHeader={[
{ title: "Name", className: "name", sortBy: sortBy.name },
{ className: "warning" },
{ title: "Labels", className: "labels", sortBy: sortBy.labels },
{ title: "Age", className: "age", sortBy: sortBy.age },
{ title: "Status", className: "status", sortBy: sortBy.status },
{ title: "Name", className: "name", sortBy: columnId.name, id: columnId.name },
{ className: "warning", showWithColumn: columnId.name },
{ title: "Labels", className: "labels", sortBy: columnId.labels, id: columnId.labels },
{ title: "Age", className: "age", sortBy: columnId.age, id: columnId.age },
{ title: "Status", className: "status", sortBy: columnId.status, id: columnId.status },
]}
renderTableContents={(item: Namespace) => [
item.getName(),
@@ -9,9 +9,10 @@ import { endpointStore } from "./endpoints.store";
import { KubeObjectListLayout } from "../kube-object";
import { KubeObjectStatusIcon } from "../kube-object-status-icon";
enum sortBy {
enum columnId {
name = "name",
namespace = "namespace",
endpoints = "endpoints",
age = "age",
}
@@ -23,22 +24,24 @@ export class Endpoints extends React.Component<Props> {
render() {
return (
<KubeObjectListLayout
isConfigurable
tableId="network_endpoints"
className="Endpoints" store={endpointStore}
sortingCallbacks={{
[sortBy.name]: (endpoint: Endpoint) => endpoint.getName(),
[sortBy.namespace]: (endpoint: Endpoint) => endpoint.getNs(),
[sortBy.age]: (endpoint: Endpoint) => endpoint.metadata.creationTimestamp,
[columnId.name]: (endpoint: Endpoint) => endpoint.getName(),
[columnId.namespace]: (endpoint: Endpoint) => endpoint.getNs(),
[columnId.age]: (endpoint: Endpoint) => endpoint.getTimeDiffFromNow(),
}}
searchFilters={[
(endpoint: Endpoint) => endpoint.getSearchFields()
]}
renderHeaderTitle="Endpoints"
renderTableHeader={[
{ title: "Name", className: "name", sortBy: sortBy.name },
{ className: "warning" },
{ title: "Namespace", className: "namespace", sortBy: sortBy.namespace },
{ title: "Endpoints", className: "endpoints" },
{ title: "Age", className: "age", sortBy: sortBy.age },
{ title: "Name", className: "name", sortBy: columnId.name, id: columnId.name },
{ className: "warning", showWithColumn: columnId.name },
{ title: "Namespace", className: "namespace", sortBy: columnId.namespace, id: columnId.namespace },
{ title: "Endpoints", className: "endpoints", id: columnId.endpoints },
{ title: "Age", className: "age", sortBy: columnId.age, id: columnId.age },
]}
renderTableContents={(endpoint: Endpoint) => [
endpoint.getName(),
@@ -9,9 +9,11 @@ import { ingressStore } from "./ingress.store";
import { KubeObjectListLayout } from "../kube-object";
import { KubeObjectStatusIcon } from "../kube-object-status-icon";
enum sortBy {
enum columnId {
name = "name",
namespace = "namespace",
loadBalancers ="load-balancers",
rules = "rules",
age = "age",
}
@@ -23,11 +25,13 @@ export class Ingresses extends React.Component<Props> {
render() {
return (
<KubeObjectListLayout
isConfigurable
tableId="network_ingresses"
className="Ingresses" store={ingressStore}
sortingCallbacks={{
[sortBy.name]: (ingress: Ingress) => ingress.getName(),
[sortBy.namespace]: (ingress: Ingress) => ingress.getNs(),
[sortBy.age]: (ingress: Ingress) => ingress.metadata.creationTimestamp,
[columnId.name]: (ingress: Ingress) => ingress.getName(),
[columnId.namespace]: (ingress: Ingress) => ingress.getNs(),
[columnId.age]: (ingress: Ingress) => ingress.getTimeDiffFromNow(),
}}
searchFilters={[
(ingress: Ingress) => ingress.getSearchFields(),
@@ -35,12 +39,12 @@ export class Ingresses extends React.Component<Props> {
]}
renderHeaderTitle="Ingresses"
renderTableHeader={[
{ title: "Name", className: "name", sortBy: sortBy.name },
{ className: "warning" },
{ title: "Namespace", className: "namespace", sortBy: sortBy.namespace },
{ title: "LoadBalancers", className: "loadbalancers" },
{ title: "Rules", className: "rules" },
{ title: "Age", className: "age", sortBy: sortBy.age },
{ title: "Name", className: "name", sortBy: columnId.name, id: columnId.name },
{ className: "warning", showWithColumn: columnId.name },
{ title: "Namespace", className: "namespace", sortBy: columnId.namespace, id: columnId.namespace },
{ title: "LoadBalancers", className: "loadbalancers", id: columnId.loadBalancers },
{ title: "Rules", className: "rules", id: columnId.rules },
{ title: "Age", className: "age", sortBy: columnId.age, id: columnId.age },
]}
renderTableContents={(ingress: Ingress) => [
ingress.getName(),
@@ -9,9 +9,10 @@ import { INetworkPoliciesRouteParams } from "./network-policies.route";
import { networkPolicyStore } from "./network-policy.store";
import { KubeObjectStatusIcon } from "../kube-object-status-icon";
enum sortBy {
enum columnId {
name = "name",
namespace = "namespace",
types = "types",
age = "age",
}
@@ -23,22 +24,24 @@ export class NetworkPolicies extends React.Component<Props> {
render() {
return (
<KubeObjectListLayout
isConfigurable
tableId="network_policies"
className="NetworkPolicies" store={networkPolicyStore}
sortingCallbacks={{
[sortBy.name]: (item: NetworkPolicy) => item.getName(),
[sortBy.namespace]: (item: NetworkPolicy) => item.getNs(),
[sortBy.age]: (item: NetworkPolicy) => item.metadata.creationTimestamp,
[columnId.name]: (item: NetworkPolicy) => item.getName(),
[columnId.namespace]: (item: NetworkPolicy) => item.getNs(),
[columnId.age]: (item: NetworkPolicy) => item.getTimeDiffFromNow(),
}}
searchFilters={[
(item: NetworkPolicy) => item.getSearchFields(),
]}
renderHeaderTitle="Network Policies"
renderTableHeader={[
{ title: "Name", className: "name", sortBy: sortBy.name },
{ className: "warning" },
{ title: "Namespace", className: "namespace", sortBy: sortBy.namespace },
{ title: "Policy Types", className: "type" },
{ title: "Age", className: "age", sortBy: sortBy.age },
{ title: "Name", className: "name", sortBy: columnId.name, id: columnId.name },
{ className: "warning", showWithColumn: columnId.name },
{ title: "Namespace", className: "namespace", sortBy: columnId.namespace, id: columnId.namespace },
{ title: "Policy Types", className: "type", id: columnId.types },
{ title: "Age", className: "age", sortBy: columnId.age, id: columnId.age },
]}
renderTableContents={(item: NetworkPolicy) => [
item.getName(),
@@ -117,7 +117,7 @@ export class NetworkPolicyDetails extends React.Component<Props> {
{ingress && (
<>
<DrawerTitle title={`Ingress`}/>
<DrawerTitle title="Ingress"/>
{ingress.map((ingress, i) => {
const { ports } = ingress;
@@ -1,17 +1,18 @@
import "./service-details.scss";
import React from "react";
import { observer } from "mobx-react";
import { disposeOnUnmount, observer } from "mobx-react";
import { DrawerItem, DrawerTitle } from "../drawer";
import { Badge } from "../badge";
import { KubeEventDetails } from "../+events/kube-event-details";
import { KubeObjectDetailsProps } from "../kube-object";
import { Service, endpointApi } from "../../api/endpoints";
import { Service } from "../../api/endpoints";
import { KubeObjectMeta } from "../kube-object/kube-object-meta";
import { ServicePortComponent } from "./service-port-component";
import { endpointStore } from "../+network-endpoints/endpoints.store";
import { ServiceDetailsEndpoint } from "./service-details-endpoint";
import { kubeObjectDetailRegistry } from "../../api/kube-object-detail-registry";
import { kubeWatchApi } from "../../api/kube-watch-api";
interface Props extends KubeObjectDetailsProps<Service> {
}
@@ -19,10 +20,11 @@ interface Props extends KubeObjectDetailsProps<Service> {
@observer
export class ServiceDetails extends React.Component<Props> {
componentDidMount() {
if (!endpointStore.isLoaded) {
endpointStore.loadAll();
}
endpointApi.watch();
disposeOnUnmount(this, [
kubeWatchApi.subscribeStores([endpointStore], {
preload: true,
}),
]);
}
render() {
@@ -48,7 +50,7 @@ export class ServiceDetails extends React.Component<Props> {
{spec.sessionAffinity}
</DrawerItem>
<DrawerTitle title={`Connection`}/>
<DrawerTitle title="Connection"/>
<DrawerItem name="Cluster IP">
{spec.clusterIP}
@@ -75,9 +77,9 @@ export class ServiceDetails extends React.Component<Props> {
{spec.loadBalancerIP}
</DrawerItem>
)}
<DrawerTitle title={`Endpoint`}/>
<DrawerTitle title="Endpoint"/>
<ServiceDetailsEndpoint endpoint={endpoint} />
<ServiceDetailsEndpoint endpoint={endpoint}/>
</div>
);
}
@@ -37,7 +37,7 @@ export class ServicePortComponent extends React.Component<Props> {
return (
<div className={cssNames("ServicePortComponent", { waiting: this.waiting })}>
<span title={`Open in a browser`} onClick={() => this.portForward() }>
<span title="Open in a browser" onClick={() => this.portForward() }>
{port.toString()}
{this.waiting && (
<Spinner />
@@ -10,12 +10,13 @@ import { Badge } from "../badge";
import { serviceStore } from "./services.store";
import { KubeObjectStatusIcon } from "../kube-object-status-icon";
enum sortBy {
enum columnId {
name = "name",
namespace = "namespace",
selector = "selector",
ports = "port",
clusterIp = "cluster-ip",
externalIp = "external-ip",
age = "age",
type = "type",
status = "status",
@@ -29,16 +30,18 @@ export class Services extends React.Component<Props> {
render() {
return (
<KubeObjectListLayout
isConfigurable
tableId="network_services"
className="Services" store={serviceStore}
sortingCallbacks={{
[sortBy.name]: (service: Service) => service.getName(),
[sortBy.namespace]: (service: Service) => service.getNs(),
[sortBy.selector]: (service: Service) => service.getSelector(),
[sortBy.ports]: (service: Service) => (service.spec.ports || []).map(({ port }) => port)[0],
[sortBy.clusterIp]: (service: Service) => service.getClusterIp(),
[sortBy.type]: (service: Service) => service.getType(),
[sortBy.age]: (service: Service) => service.metadata.creationTimestamp,
[sortBy.status]: (service: Service) => service.getStatus(),
[columnId.name]: (service: Service) => service.getName(),
[columnId.namespace]: (service: Service) => service.getNs(),
[columnId.selector]: (service: Service) => service.getSelector(),
[columnId.ports]: (service: Service) => (service.spec.ports || []).map(({ port }) => port)[0],
[columnId.clusterIp]: (service: Service) => service.getClusterIp(),
[columnId.type]: (service: Service) => service.getType(),
[columnId.age]: (service: Service) => service.getTimeDiffFromNow(),
[columnId.status]: (service: Service) => service.getStatus(),
}}
searchFilters={[
(service: Service) => service.getSearchFields(),
@@ -47,16 +50,16 @@ export class Services extends React.Component<Props> {
]}
renderHeaderTitle="Services"
renderTableHeader={[
{ title: "Name", className: "name", sortBy: sortBy.name },
{ className: "warning" },
{ title: "Namespace", className: "namespace", sortBy: sortBy.namespace },
{ title: "Type", className: "type", sortBy: sortBy.type },
{ title: "Cluster IP", className: "clusterIp", sortBy: sortBy.clusterIp, },
{ title: "Ports", className: "ports", sortBy: sortBy.ports },
{ title: "External IP", className: "externalIp" },
{ title: "Selector", className: "selector", sortBy: sortBy.selector },
{ title: "Age", className: "age", sortBy: sortBy.age },
{ title: "Status", className: "status", sortBy: sortBy.status },
{ title: "Name", className: "name", sortBy: columnId.name, id: columnId.name },
{ className: "warning", showWithColumn: columnId.name },
{ title: "Namespace", className: "namespace", sortBy: columnId.namespace, id: columnId.namespace },
{ title: "Type", className: "type", sortBy: columnId.type, id: columnId.type },
{ title: "Cluster IP", className: "clusterIp", sortBy: columnId.clusterIp, id: columnId.clusterIp },
{ title: "Ports", className: "ports", sortBy: columnId.ports, id: columnId.ports },
{ title: "External IP", className: "externalIp", id: columnId.externalIp },
{ title: "Selector", className: "selector", sortBy: columnId.selector, id: columnId.selector },
{ title: "Age", className: "age", sortBy: columnId.age, id: columnId.age },
{ title: "Status", className: "status", sortBy: columnId.status, id: columnId.status },
]}
renderTableContents={(service: Service) => [
service.getName(),
@@ -1,2 +1,3 @@
export * from "./network.route";
export * from "./network";
export * from "./network.command";
@@ -0,0 +1,34 @@
import { navigate } from "../../navigation";
import { commandRegistry } from "../../../extensions/registries/command-registry";
import { servicesURL } from "../+network-services";
import { endpointURL } from "../+network-endpoints";
import { ingressURL } from "../+network-ingresses";
import { networkPoliciesURL } from "../+network-policies";
commandRegistry.add({
id: "cluster.viewServices",
title: "Cluster: View Services",
scope: "cluster",
action: () => navigate(servicesURL())
});
commandRegistry.add({
id: "cluster.viewEndpoints",
title: "Cluster: View Endpoints",
scope: "cluster",
action: () => navigate(endpointURL())
});
commandRegistry.add({
id: "cluster.viewIngresses",
title: "Cluster: View Ingresses",
scope: "cluster",
action: () => navigate(ingressURL())
});
commandRegistry.add({
id: "cluster.viewNetworkPolicies",
title: "Cluster: View NetworkPolicies",
scope: "cluster",
action: () => navigate(networkPoliciesURL())
});
+1
View File
@@ -1,3 +1,4 @@
export * from "./nodes";
export * from "./nodes.route";
export * from "./node-details";
export * from "./node.command";
@@ -29,9 +29,7 @@ export class NodeDetails extends React.Component<Props> {
});
async componentDidMount() {
if (!podsStore.isLoaded) {
podsStore.loadAll();
}
podsStore.reloadAll();
}
componentWillUnmount() {
@@ -0,0 +1,10 @@
import { navigate } from "../../navigation";
import { commandRegistry } from "../../../extensions/registries/command-registry";
import { nodesURL } from "./nodes.route";
commandRegistry.add({
id: "cluster.viewNodes",
title: "Cluster: View Nodes",
scope: "cluster",
action: () => navigate(nodesURL())
});
@@ -1,3 +1,4 @@
import { sum } from "lodash";
import { action, computed, observable } from "mobx";
import { clusterApi, IClusterMetrics, INodeMetrics, Node, nodesApi } from "../../api/endpoints";
import { autobind } from "../../utils";
@@ -62,6 +63,10 @@ export class NodesStore extends KubeObjectStore<Node> {
});
}
getWarningsCount(): number {
return sum(this.items.map((node: Node) => node.getWarningConditions().length));
}
reset() {
super.reset();
this.metrics = {};
+27 -21
View File
@@ -17,7 +17,7 @@ import upperFirst from "lodash/upperFirst";
import { KubeObjectStatusIcon } from "../kube-object-status-icon";
import { Badge } from "../badge/badge";
enum sortBy {
enum columnId {
name = "name",
cpu = "cpu",
memory = "memory",
@@ -51,6 +51,10 @@ export class Nodes extends React.Component<Props> {
if (!metrics || !metrics[1]) return <LineProgress value={0}/>;
const usage = metrics[0];
const cores = metrics[1];
const cpuUsagePercent = Math.ceil(usage * 100) / cores;
const cpuUsagePercentLabel: String = cpuUsagePercent % 1 === 0
? cpuUsagePercent.toString()
: cpuUsagePercent.toFixed(2);
return (
<LineProgress
@@ -58,7 +62,7 @@ export class Nodes extends React.Component<Props> {
value={usage}
tooltip={{
preferredPositions: TooltipPosition.BOTTOM,
children: `CPU: ${Math.ceil(usage * 100) / cores}\%, cores: ${cores}`
children: `CPU: ${cpuUsagePercentLabel}\%, cores: ${cores}`
}}
/>
);
@@ -131,21 +135,23 @@ export class Nodes extends React.Component<Props> {
return (
<TabLayout>
<KubeObjectListLayout
isConfigurable
tableId="nodes"
className="Nodes"
store={nodesStore} isClusterScoped
isReady={nodesStore.isLoaded}
dependentStores={[podsStore]}
isSelectable={false}
sortingCallbacks={{
[sortBy.name]: (node: Node) => node.getName(),
[sortBy.cpu]: (node: Node) => nodesStore.getLastMetricValues(node, ["cpuUsage"]),
[sortBy.memory]: (node: Node) => nodesStore.getLastMetricValues(node, ["memoryUsage"]),
[sortBy.disk]: (node: Node) => nodesStore.getLastMetricValues(node, ["fsUsage"]),
[sortBy.conditions]: (node: Node) => node.getNodeConditionText(),
[sortBy.taints]: (node: Node) => node.getTaints().length,
[sortBy.roles]: (node: Node) => node.getRoleLabels(),
[sortBy.age]: (node: Node) => node.metadata.creationTimestamp,
[sortBy.version]: (node: Node) => node.getKubeletVersion(),
[columnId.name]: (node: Node) => node.getName(),
[columnId.cpu]: (node: Node) => nodesStore.getLastMetricValues(node, ["cpuUsage"]),
[columnId.memory]: (node: Node) => nodesStore.getLastMetricValues(node, ["memoryUsage"]),
[columnId.disk]: (node: Node) => nodesStore.getLastMetricValues(node, ["fsUsage"]),
[columnId.conditions]: (node: Node) => node.getNodeConditionText(),
[columnId.taints]: (node: Node) => node.getTaints().length,
[columnId.roles]: (node: Node) => node.getRoleLabels(),
[columnId.age]: (node: Node) => node.getTimeDiffFromNow(),
[columnId.version]: (node: Node) => node.getKubeletVersion(),
}}
searchFilters={[
(node: Node) => node.getSearchFields(),
@@ -155,16 +161,16 @@ export class Nodes extends React.Component<Props> {
]}
renderHeaderTitle="Nodes"
renderTableHeader={[
{ title: "Name", className: "name", sortBy: sortBy.name },
{ className: "warning" },
{ title: "CPU", className: "cpu", sortBy: sortBy.cpu },
{ title: "Memory", className: "memory", sortBy: sortBy.memory },
{ title: "Disk", className: "disk", sortBy: sortBy.disk },
{ title: "Taints", className: "taints", sortBy: sortBy.taints },
{ title: "Roles", className: "roles", sortBy: sortBy.roles },
{ title: "Version", className: "version", sortBy: sortBy.version },
{ title: "Age", className: "age", sortBy: sortBy.age },
{ title: "Conditions", className: "conditions", sortBy: sortBy.conditions },
{ title: "Name", className: "name", sortBy: columnId.name, id: columnId.name },
{ className: "warning", showWithColumn: columnId.name },
{ title: "CPU", className: "cpu", sortBy: columnId.cpu, id: columnId.cpu },
{ title: "Memory", className: "memory", sortBy: columnId.memory, id: columnId.memory },
{ title: "Disk", className: "disk", sortBy: columnId.disk, id: columnId.disk },
{ title: "Taints", className: "taints", sortBy: columnId.taints, id: columnId.taints },
{ title: "Roles", className: "roles", sortBy: columnId.roles, id: columnId.roles },
{ title: "Version", className: "version", sortBy: columnId.version, id: columnId.version },
{ title: "Age", className: "age", sortBy: columnId.age, id: columnId.age },
{ title: "Conditions", className: "conditions", sortBy: columnId.conditions, id: columnId.conditions },
]}
renderTableContents={(node: Node) => {
const tooltipId = `node-taints-${node.getId()}`;
@@ -1,3 +1,3 @@
export * from "./pod-security-policies.route";
export * from "./pod-security-policies";
export * from "./pod-security-policy-details";
export * from "./pod-security-policy-details";
@@ -7,7 +7,7 @@ import { podSecurityPoliciesStore } from "./pod-security-policies.store";
import { PodSecurityPolicy } from "../../api/endpoints";
import { KubeObjectStatusIcon } from "../kube-object-status-icon";
enum sortBy {
enum columnId {
name = "name",
volumes = "volumes",
privileged = "privileged",
@@ -19,14 +19,16 @@ export class PodSecurityPolicies extends React.Component {
render() {
return (
<KubeObjectListLayout
isConfigurable
tableId="access_roles"
className="PodSecurityPolicies"
isClusterScoped={true}
store={podSecurityPoliciesStore}
sortingCallbacks={{
[sortBy.name]: (item: PodSecurityPolicy) => item.getName(),
[sortBy.volumes]: (item: PodSecurityPolicy) => item.getVolumes(),
[sortBy.privileged]: (item: PodSecurityPolicy) => +item.isPrivileged(),
[sortBy.age]: (item: PodSecurityPolicy) => item.metadata.creationTimestamp,
[columnId.name]: (item: PodSecurityPolicy) => item.getName(),
[columnId.volumes]: (item: PodSecurityPolicy) => item.getVolumes(),
[columnId.privileged]: (item: PodSecurityPolicy) => +item.isPrivileged(),
[columnId.age]: (item: PodSecurityPolicy) => item.getTimeDiffFromNow(),
}}
searchFilters={[
(item: PodSecurityPolicy) => item.getSearchFields(),
@@ -35,11 +37,11 @@ export class PodSecurityPolicies extends React.Component {
]}
renderHeaderTitle="Pod Security Policies"
renderTableHeader={[
{ title: "Name", className: "name", sortBy: sortBy.name },
{ className: "warning" },
{ title: "Privileged", className: "privileged", sortBy: sortBy.privileged },
{ title: "Volumes", className: "volumes", sortBy: sortBy.volumes },
{ title: "Age", className: "age", sortBy: sortBy.age },
{ title: "Name", className: "name", sortBy: columnId.name, id: columnId.name },
{ className: "warning", showWithColumn: columnId.name },
{ title: "Privileged", className: "privileged", sortBy: columnId.privileged, id: columnId.privileged },
{ title: "Volumes", className: "volumes", sortBy: columnId.volumes, id: columnId.volumes },
{ title: "Age", className: "age", sortBy: columnId.age, id: columnId.age },
]}
renderTableContents={(item: PodSecurityPolicy) => {
return [
@@ -111,7 +111,7 @@ export class AddHelmRepoDialog extends React.Component<Props> {
<>
<SubTitle title="Security settings" />
<Checkbox
label={`Skip TLS certificate checks for the repository`}
label="Skip TLS certificate checks for the repository"
value={this.helmRepo.insecureSkipTlsVerify}
onChange={v => this.helmRepo.insecureSkipTlsVerify = v}
/>
@@ -120,12 +120,12 @@ export class AddHelmRepoDialog extends React.Component<Props> {
{this.renderFileInput(`Cerificate file`, FileType.CertFile, AddHelmRepoDialog.certExtensions)}
<SubTitle title="Chart Repository Credentials" />
<Input
placeholder={`Username`}
placeholder="Username"
value={this.helmRepo.username} onChange= {v => this.helmRepo.username = v}
/>
<Input
type="password"
placeholder={`Password`}
placeholder="Password"
value={this.helmRepo.password} onChange={v => this.helmRepo.password = v}
/>
</>);
@@ -148,13 +148,13 @@ export class AddHelmRepoDialog extends React.Component<Props> {
<div className="flex column gaps">
<Input
autoFocus required
placeholder={`Helm repo name`}
placeholder="Helm repo name"
validators={systemName}
value={this.helmRepo.name} onChange={v => this.helmRepo.name = v}
/>
<Input
required
placeholder={`URL`}
placeholder="URL"
validators={isUrl}
value={this.helmRepo.url} onChange={v => this.helmRepo.url = v}
/>
@@ -162,7 +162,7 @@ export class AddHelmRepoDialog extends React.Component<Props> {
More
<Icon
small
tooltip={`More`}
tooltip="More"
material={this.showOptions ? "remove" : "add"}
/>
</Button>
@@ -1,8 +1,17 @@
import type { RouteProps } from "react-router";
import { commandRegistry } from "../../../extensions/registries/command-registry";
import { buildURL } from "../../../common/utils/buildUrl";
import { navigate } from "../../navigation";
export const preferencesRoute: RouteProps = {
path: "/preferences"
};
export const preferencesURL = buildURL(preferencesRoute.path);
commandRegistry.add({
id: "app.showPreferences",
title: "Preferences: Open",
scope: "global",
action: () => navigate(preferencesURL())
});
@@ -122,7 +122,7 @@ export class Preferences extends React.Component {
<h2>HTTP Proxy</h2>
<Input
theme="round-black"
placeholder={`Type HTTP proxy url (example: http://proxy.acme.org:8080)`}
placeholder="Type HTTP proxy url (example: http://proxy.acme.org:8080)"
value={this.httpProxy}
onChange={v => this.httpProxy = v}
onBlur={() => preferences.httpsProxy = this.httpProxy}
@@ -10,14 +10,22 @@ import { KubeObjectDetailsProps } from "../kube-object";
import { StorageClass } from "../../api/endpoints";
import { KubeObjectMeta } from "../kube-object/kube-object-meta";
import { kubeObjectDetailRegistry } from "../../api/kube-object-detail-registry";
import { storageClassStore } from "./storage-class.store";
import { VolumeDetailsList } from "../+storage-volumes/volume-details-list";
import { volumesStore } from "../+storage-volumes/volumes.store";
interface Props extends KubeObjectDetailsProps<StorageClass> {
}
@observer
export class StorageClassDetails extends React.Component<Props> {
async componentDidMount() {
volumesStore.reloadAll();
}
render() {
const { object: storageClass } = this.props;
const persistentVolumes = storageClassStore.getPersistentVolumes(storageClass);
if (!storageClass) return null;
const { provisioner, parameters, mountOptions } = storageClass;
@@ -45,7 +53,7 @@ export class StorageClassDetails extends React.Component<Props> {
)}
{parameters && (
<>
<DrawerTitle title={`Parameters`}/>
<DrawerTitle title="Parameters"/>
{
Object.entries(parameters).map(([name, value]) => (
<DrawerItem key={name + value} name={startCase(name)}>
@@ -55,6 +63,7 @@ export class StorageClassDetails extends React.Component<Props> {
}
</>
)}
<VolumeDetailsList persistentVolumes={persistentVolumes}/>
</div>
);
}
@@ -2,10 +2,15 @@ import { KubeObjectStore } from "../../kube-object.store";
import { autobind } from "../../utils";
import { StorageClass, storageClassApi } from "../../api/endpoints/storage-class.api";
import { apiManager } from "../../api/api-manager";
import { volumesStore } from "../+storage-volumes/volumes.store";
@autobind()
export class StorageClassStore extends KubeObjectStore<StorageClass> {
api = storageClassApi;
getPersistentVolumes(storageClass: StorageClass) {
return volumesStore.getByStorageClass(storageClass);
}
}
export const storageClassStore = new StorageClassStore();
@@ -9,10 +9,11 @@ import { IStorageClassesRouteParams } from "./storage-classes.route";
import { storageClassStore } from "./storage-class.store";
import { KubeObjectStatusIcon } from "../kube-object-status-icon";
enum sortBy {
enum columnId {
name = "name",
age = "age",
provisioner = "provision",
default = "default",
reclaimPolicy = "reclaim",
}
@@ -24,13 +25,15 @@ export class StorageClasses extends React.Component<Props> {
render() {
return (
<KubeObjectListLayout
isConfigurable
tableId="storage_classes"
className="StorageClasses"
store={storageClassStore} isClusterScoped
sortingCallbacks={{
[sortBy.name]: (item: StorageClass) => item.getName(),
[sortBy.age]: (item: StorageClass) => item.metadata.creationTimestamp,
[sortBy.provisioner]: (item: StorageClass) => item.provisioner,
[sortBy.reclaimPolicy]: (item: StorageClass) => item.reclaimPolicy,
[columnId.name]: (item: StorageClass) => item.getName(),
[columnId.age]: (item: StorageClass) => item.getTimeDiffFromNow(),
[columnId.provisioner]: (item: StorageClass) => item.provisioner,
[columnId.reclaimPolicy]: (item: StorageClass) => item.reclaimPolicy,
}}
searchFilters={[
(item: StorageClass) => item.getSearchFields(),
@@ -38,12 +41,12 @@ export class StorageClasses extends React.Component<Props> {
]}
renderHeaderTitle="Storage Classes"
renderTableHeader={[
{ title: "Name", className: "name", sortBy: sortBy.name },
{ className: "warning" },
{ title: "Provisioner", className: "provisioner", sortBy: sortBy.provisioner },
{ title: "Reclaim Policy", className: "reclaim-policy", sortBy: sortBy.reclaimPolicy },
{ title: "Default", className: "is-default" },
{ title: "Age", className: "age", sortBy: sortBy.age },
{ title: "Name", className: "name", sortBy: columnId.name, id: columnId.name },
{ className: "warning", showWithColumn: columnId.name },
{ title: "Provisioner", className: "provisioner", sortBy: columnId.provisioner, id: columnId.provisioner },
{ title: "Reclaim Policy", className: "reclaim-policy", sortBy: columnId.reclaimPolicy, id: columnId.reclaimPolicy },
{ title: "Default", className: "is-default", id: columnId.default },
{ title: "Age", className: "age", sortBy: columnId.age, id: columnId.age },
]}
renderTableContents={(storageClass: StorageClass) => [
storageClass.getName(),
@@ -71,7 +71,7 @@ export class PersistentVolumeClaimDetails extends React.Component<Props> {
{volumeClaim.getStatus()}
</DrawerItem>
<DrawerTitle title={`Selector`}/>
<DrawerTitle title="Selector"/>
<DrawerItem name="Match Labels" labelsOnly>
{volumeClaim.getMatchLabels().map(label => <Badge key={label} label={label}/>)}
@@ -13,7 +13,7 @@ import { stopPropagation } from "../../utils";
import { storageClassApi } from "../../api/endpoints";
import { KubeObjectStatusIcon } from "../kube-object-status-icon";
enum sortBy {
enum columnId {
name = "name",
namespace = "namespace",
pods = "pods",
@@ -31,17 +31,19 @@ export class PersistentVolumeClaims extends React.Component<Props> {
render() {
return (
<KubeObjectListLayout
isConfigurable
tableId="storage_volume_claims"
className="PersistentVolumeClaims"
store={volumeClaimStore}
dependentStores={[podsStore]}
sortingCallbacks={{
[sortBy.name]: (pvc: PersistentVolumeClaim) => pvc.getName(),
[sortBy.namespace]: (pvc: PersistentVolumeClaim) => pvc.getNs(),
[sortBy.pods]: (pvc: PersistentVolumeClaim) => pvc.getPods(podsStore.items).map(pod => pod.getName()),
[sortBy.status]: (pvc: PersistentVolumeClaim) => pvc.getStatus(),
[sortBy.size]: (pvc: PersistentVolumeClaim) => unitsToBytes(pvc.getStorage()),
[sortBy.storageClass]: (pvc: PersistentVolumeClaim) => pvc.spec.storageClassName,
[sortBy.age]: (pvc: PersistentVolumeClaim) => pvc.metadata.creationTimestamp,
[columnId.name]: (pvc: PersistentVolumeClaim) => pvc.getName(),
[columnId.namespace]: (pvc: PersistentVolumeClaim) => pvc.getNs(),
[columnId.pods]: (pvc: PersistentVolumeClaim) => pvc.getPods(podsStore.items).map(pod => pod.getName()),
[columnId.status]: (pvc: PersistentVolumeClaim) => pvc.getStatus(),
[columnId.size]: (pvc: PersistentVolumeClaim) => unitsToBytes(pvc.getStorage()),
[columnId.storageClass]: (pvc: PersistentVolumeClaim) => pvc.spec.storageClassName,
[columnId.age]: (pvc: PersistentVolumeClaim) => pvc.getTimeDiffFromNow(),
}}
searchFilters={[
(item: PersistentVolumeClaim) => item.getSearchFields(),
@@ -49,14 +51,14 @@ export class PersistentVolumeClaims extends React.Component<Props> {
]}
renderHeaderTitle="Persistent Volume Claims"
renderTableHeader={[
{ title: "Name", className: "name", sortBy: sortBy.name },
{ className: "warning" },
{ title: "Namespace", className: "namespace", sortBy: sortBy.namespace },
{ title: "Storage class", className: "storageClass", sortBy: sortBy.storageClass },
{ title: "Size", className: "size", sortBy: sortBy.size },
{ title: "Pods", className: "pods", sortBy: sortBy.pods },
{ title: "Age", className: "age", sortBy: sortBy.age },
{ title: "Status", className: "status", sortBy: sortBy.status },
{ title: "Name", className: "name", sortBy: columnId.name, id: columnId.name },
{ className: "warning", showWithColumn: columnId.name },
{ title: "Namespace", className: "namespace", sortBy: columnId.namespace, id: columnId.namespace },
{ title: "Storage class", className: "storageClass", sortBy: columnId.storageClass, id: columnId.storageClass },
{ title: "Size", className: "size", sortBy: columnId.size, id: columnId.size },
{ title: "Pods", className: "pods", sortBy: columnId.pods, id: columnId.pods },
{ title: "Age", className: "age", sortBy: columnId.age, id: columnId.age },
{ title: "Status", className: "status", sortBy: columnId.status, id: columnId.status },
]}
renderTableContents={(pvc: PersistentVolumeClaim) => {
const pods = pvc.getPods(podsStore.items);
@@ -0,0 +1,31 @@
@import "../+storage/storage-mixins";
.VolumeDetailsList {
position: relative;
.Table {
margin: 0 (-$margin * 3);
&.virtual {
height: 500px; // applicable for 100+ items
}
}
.TableCell {
&:first-child {
margin-left: $margin;
}
&:last-child {
margin-right: $margin;
}
&.name {
flex-grow: 2;
}
&.status {
@include pv-status-colors;
}
}
}
@@ -0,0 +1,88 @@
import "./volume-details-list.scss";
import React from "react";
import { observer } from "mobx-react";
import { PersistentVolume } from "../../api/endpoints/persistent-volume.api";
import { autobind } from "../../../common/utils/autobind";
import { TableRow } from "../table/table-row";
import { cssNames, prevDefault } from "../../utils";
import { showDetails } from "../kube-object/kube-object-details";
import { TableCell } from "../table/table-cell";
import { Spinner } from "../spinner/spinner";
import { DrawerTitle } from "../drawer/drawer-title";
import { Table } from "../table/table";
import { TableHead } from "../table/table-head";
import { volumesStore } from "./volumes.store";
import kebabCase from "lodash/kebabCase";
interface Props {
persistentVolumes: PersistentVolume[];
}
enum sortBy {
name = "name",
status = "status",
capacity = "capacity",
}
@observer
export class VolumeDetailsList extends React.Component<Props> {
private sortingCallbacks = {
[sortBy.name]: (volume: PersistentVolume) => volume.getName(),
[sortBy.capacity]: (volume: PersistentVolume) => volume.getCapacity(),
[sortBy.status]: (volume: PersistentVolume) => volume.getStatus(),
};
@autobind()
getTableRow(uid: string) {
const { persistentVolumes } = this.props;
const volume = persistentVolumes.find(volume => volume.getId() === uid);
return (
<TableRow
key={volume.getId()}
sortItem={volume}
nowrap
onClick={prevDefault(() => showDetails(volume.selfLink, false))}
>
<TableCell className="name">{volume.getName()}</TableCell>
<TableCell className="capacity">{volume.getCapacity()}</TableCell>
<TableCell className={cssNames("status", kebabCase(volume.getStatus()))}>{volume.getStatus()}</TableCell>
</TableRow>
);
}
render() {
const { persistentVolumes } = this.props;
const virtual = persistentVolumes.length > 100;
if (!persistentVolumes.length) {
return !volumesStore.isLoaded && <Spinner center/>;
}
return (
<div className="VolumeDetailsList flex column">
<DrawerTitle title="Persistent Volumes"/>
<Table
items={persistentVolumes}
selectable
virtual={virtual}
sortable={this.sortingCallbacks}
sortByDefault={{ sortBy: sortBy.name, orderBy: "desc" }}
sortSyncWithUrl={false}
getTableRow={this.getTableRow}
className="box grow"
>
<TableHead>
<TableCell className="name" sortBy={sortBy.name}>Name</TableCell>
<TableCell className="capacity" sortBy={sortBy.capacity}>Capacity</TableCell>
<TableCell className="status" sortBy={sortBy.status}>Status</TableCell>
</TableHead>
{
!virtual && persistentVolumes.map(volume => this.getTableRow(volume.getId()))
}
</Table>
</div>
);
}
}
@@ -26,7 +26,7 @@
flex-grow: 3;
}
.status {
&.status {
@include pv-status-colors;
}
@@ -2,10 +2,17 @@ import { KubeObjectStore } from "../../kube-object.store";
import { autobind } from "../../utils";
import { PersistentVolume, persistentVolumeApi } from "../../api/endpoints/persistent-volume.api";
import { apiManager } from "../../api/api-manager";
import { StorageClass } from "../../api/endpoints/storage-class.api";
@autobind()
export class PersistentVolumesStore extends KubeObjectStore<PersistentVolume> {
api = persistentVolumeApi;
getByStorageClass(storageClass: StorageClass): PersistentVolume[] {
return this.items.filter(volume =>
volume.getStorageClassName() === storageClass.getName()
);
}
}
export const volumesStore = new PersistentVolumesStore();
@@ -11,10 +11,11 @@ import { volumesStore } from "./volumes.store";
import { pvcApi, storageClassApi } from "../../api/endpoints";
import { KubeObjectStatusIcon } from "../kube-object-status-icon";
enum sortBy {
enum columnId {
name = "name",
storageClass = "storage-class",
capacity = "capacity",
claim = "claim",
status = "status",
age = "age",
}
@@ -27,14 +28,16 @@ export class PersistentVolumes extends React.Component<Props> {
render() {
return (
<KubeObjectListLayout
isConfigurable
tableId="storage_volumes"
className="PersistentVolumes"
store={volumesStore} isClusterScoped
sortingCallbacks={{
[sortBy.name]: (item: PersistentVolume) => item.getName(),
[sortBy.storageClass]: (item: PersistentVolume) => item.spec.storageClassName,
[sortBy.capacity]: (item: PersistentVolume) => item.getCapacity(true),
[sortBy.status]: (item: PersistentVolume) => item.getStatus(),
[sortBy.age]: (item: PersistentVolume) => item.metadata.creationTimestamp,
[columnId.name]: (item: PersistentVolume) => item.getName(),
[columnId.storageClass]: (item: PersistentVolume) => item.getStorageClass(),
[columnId.capacity]: (item: PersistentVolume) => item.getCapacity(true),
[columnId.status]: (item: PersistentVolume) => item.getStatus(),
[columnId.age]: (item: PersistentVolume) => item.getTimeDiffFromNow(),
}}
searchFilters={[
(item: PersistentVolume) => item.getSearchFields(),
@@ -42,13 +45,13 @@ export class PersistentVolumes extends React.Component<Props> {
]}
renderHeaderTitle="Persistent Volumes"
renderTableHeader={[
{ title: "Name", className: "name", sortBy: sortBy.name },
{ className: "warning" },
{ title: "Storage Class", className: "storageClass", sortBy: sortBy.storageClass },
{ title: "Capacity", className: "capacity", sortBy: sortBy.capacity },
{ title: "Claim", className: "claim" },
{ title: "Age", className: "age", sortBy: sortBy.age },
{ title: "Status", className: "status", sortBy: sortBy.status },
{ title: "Name", className: "name", sortBy: columnId.name, id: columnId.name },
{ className: "warning", showWithColumn: columnId.name },
{ title: "Storage Class", className: "storageClass", sortBy: columnId.storageClass, id: columnId.storageClass },
{ title: "Capacity", className: "capacity", sortBy: columnId.capacity, id: columnId.capacity },
{ title: "Claim", className: "claim", id: columnId.claim },
{ title: "Age", className: "age", sortBy: columnId.age, id: columnId.age },
{ title: "Status", className: "status", sortBy: columnId.status, id: columnId.status },
]}
renderTableContents={(volume: PersistentVolume) => {
const { claimRef, storageClassName } = volume.spec;
Loaded 100 of 383 files, more files were not shown because too many files have changed in this diff. Show more