Merge branch 'load_resources_per_namespaces' into fix-1898/watch-api-streaming

This commit is contained in:
Roman committed 2021-01-13 18:33:13 +02:00
commit 195f911342
25 files changed
+290 -237

No files matched your search

+35 -24
View File
@@ -7,38 +7,49 @@ export type KubeResource =
"endpoints" | "customresourcedefinitions" | "horizontalpodautoscalers" | "podsecuritypolicies" | "poddisruptionbudgets";
export interface KubeApiResource {
kind: string; // resource type
resource: KubeResource; // valid resource name
group?: string; // api-group
}
// TODO: auto-populate all resources dynamically (see: kubectl api-resources -o=wide -v=7)
export const apiResources: KubeApiResource[] = [
{ resource: "configmaps" },
{ resource: "cronjobs", group: "batch" },
{ resource: "customresourcedefinitions", group: "apiextensions.k8s.io" },
{ resource: "daemonsets", group: "apps" },
{ resource: "deployments", group: "apps" },
{ resource: "endpoints" },
{ resource: "events" },
{ resource: "horizontalpodautoscalers" },
{ resource: "ingresses", group: "networking.k8s.io" },
{ resource: "jobs", group: "batch" },
{ resource: "namespaces" },
{ resource: "networkpolicies", group: "networking.k8s.io" },
{ resource: "nodes" },
{ resource: "persistentvolumes" },
{ resource: "persistentvolumeclaims" },
{ resource: "pods" },
{ resource: "poddisruptionbudgets" },
{ resource: "podsecuritypolicies" },
{ resource: "resourcequotas" },
{ resource: "replicasets", group: "apps" },
{ resource: "secrets" },
{ resource: "services" },
{ resource: "statefulsets", group: "apps" },
{ resource: "storageclasses", group: "storage.k8s.io" },
{ kind: "ConfigMap", resource: "configmaps" },
{ kind: "CronJob", resource: "cronjobs", group: "batch" },
{ kind: "CustomResourceDefinition", resource: "customresourcedefinitions", group: "apiextensions.k8s.io" },
{ kind: "DaemonSet", resource: "daemonsets", group: "apps" },
{ kind: "Deployment", resource: "deployments", group: "apps" },
{ kind: "Endpoint", resource: "endpoints" },
{ kind: "Event", resource: "events" },
{ kind: "HorizontalPodAutoscaler", resource: "horizontalpodautoscalers" },
{ kind: "Ingress", resource: "ingresses", group: "networking.k8s.io" },
{ kind: "Job", resource: "jobs", group: "batch" },
{ kind: "Namespace", resource: "namespaces" },
{ kind: "NetworkPolicy", resource: "networkpolicies", group: "networking.k8s.io" },
{ kind: "Node", resource: "nodes" },
{ kind: "PersistentVolume", resource: "persistentvolumes" },
{ kind: "PersistentVolumeClaim", resource: "persistentvolumeclaims" },
{ kind: "Pod", resource: "pods" },
{ kind: "PodDisruptionBudget", resource: "poddisruptionbudgets" },
{ kind: "PodSecurityPolicy", resource: "podsecuritypolicies" },
{ kind: "ResourceQuota", resource: "resourcequotas" },
{ kind: "ReplicaSet", resource: "replicasets", group: "apps" },
{ kind: "Secret", resource: "secrets" },
{ kind: "Service", resource: "services" },
{ kind: "StatefulSet", resource: "statefulsets", group: "apps" },
{ kind: "StorageClass", resource: "storageclasses", group: "storage.k8s.io" },
];
export function isAllowedResourceType(kind: string): boolean {
const apiResource = apiResources.find(resource => resource.kind === kind);
if (apiResource) {
return getHostedCluster().allowedResources.includes(apiResource.resource);
}
return true; // allowed by default for other resources
}
export function isAllowedResource(resources: KubeResource | KubeResource[]) {
if (!Array.isArray(resources)) {
resources = [resources];
+2
View File
@@ -28,6 +28,7 @@ export interface UserPreferences {
downloadBinariesPath?: string;
kubectlBinariesPath?: string;
openAtLogin?: boolean;
hiddenTableColumns?: Record<string, string[]>
}
export class UserStore extends BaseStore<UserStoreModel> {
@@ -54,6 +55,7 @@ export class UserStore extends BaseStore<UserStoreModel> {
downloadMirror: "default",
downloadKubectlBinaries: true, // Download kubectl binaries matching cluster version
openAtLogin: false,
hiddenTableColumns: {},
};
protected async handleOnLoad() {
+12 -7
View File
@@ -10,7 +10,7 @@ import { workspaceStore } from "../common/workspace-store";
import { preferencesURL } from "../renderer/components/+preferences/preferences.route";
import { clusterViewURL } from "../renderer/components/cluster-manager/cluster-view.route";
import logger from "./logger";
import { isDevelopment } from "../common/vars";
import { isDevelopment, isWindows } from "../common/vars";
import { exitApp } from "./exit-app";
// note: instance of Tray should be saved somewhere, otherwise it disappears
@@ -29,7 +29,7 @@ export function initTray(windowManager: WindowManager) {
try {
const menu = createTrayMenu(windowManager);
buildTray(getTrayIcon(), menu);
buildTray(getTrayIcon(), menu, windowManager);
} catch (err) {
logger.error(`[TRAY]: building failed: ${err}`);
}
@@ -42,20 +42,25 @@ export function initTray(windowManager: WindowManager) {
};
}
export function buildTray(icon: string | NativeImage, menu: Menu) {
function buildTray(icon: string | NativeImage, menu: Menu, windowManager: WindowManager) {
if (!tray) {
tray = new Tray(icon);
tray.setToolTip(packageInfo.description);
tray.setIgnoreDoubleClickEvents(true);
}
tray.setImage(icon);
tray.setContextMenu(menu);
tray.setImage(icon);
tray.setContextMenu(menu);
if (isWindows) {
tray.on("click", () => {
windowManager.ensureMainWindow();
});
}
}
return tray;
}
export function createTrayMenu(windowManager: WindowManager): Menu {
function createTrayMenu(windowManager: WindowManager): Menu {
return Menu.buildFromTemplate([
{
label: "About Lens",
+15 -1
View File
@@ -78,10 +78,24 @@ export function normalizeMetrics(metrics: IMetrics, frames = 60): IMetrics {
result.forEach(res => {
if (!res.values || !res.values.length) return;
let now = moment().startOf("minute").subtract(1, "minute").unix();
let timestamp = res.values[0][0];
while (timestamp <= now) {
timestamp = moment.unix(timestamp).add(1, "minute").unix();
if (!res.values.find((value) => value[0] === timestamp)) {
res.values.push([timestamp, "0"]);
}
}
while (res.values.length < frames) {
const timestamp = moment.unix(res.values[0][0]).subtract(1, "minute").unix();
res.values.unshift([timestamp, "0"]);
if (!res.values.find((value) => value[0] === timestamp)) {
res.values.unshift([timestamp, "0"]);
}
now = timestamp;
}
});
}
@@ -18,7 +18,7 @@ export const resourceApplierApi = {
.post<KubeJsonApiData[]>("/stack", { data: resource })
.then(data => {
const items = data.map(obj => {
const api = apiManager.getApi(obj.metadata.selfLink);
const api = apiManager.getApiByKind(obj.kind, obj.apiVersion);
if (api) {
return new api.objectConstructor(obj);
+2 -2
View File
@@ -4,7 +4,7 @@ import React, { Fragment } from "react";
import { observer } from "mobx-react";
import { TabLayout } from "../layout/tab-layout";
import { eventStore } from "./event.store";
import { KubeObjectListLayout, KubeObjectListLayoutProps, getDetailsUrl } from "../kube-object";
import { getDetailsUrl, KubeObjectListLayout, KubeObjectListLayoutProps } from "../kube-object";
import { KubeEvent } from "../../api/endpoints/events.api";
import { Tooltip } from "../tooltip";
import { Link } from "react-router-dom";
@@ -65,7 +65,7 @@ export class Events extends React.Component<Props> {
small
material="help_outline"
className="help-icon"
tooltip="Limited to {eventStore.limit}"
tooltip={`Limited to ${eventStore.limit}`}
/>
</>
)
@@ -1,3 +1,4 @@
import { debounce } from "lodash";
import { action, comparer, IReactionDisposer, IReactionOptions, observable, reaction, toJS, when } from "mobx";
import { autobind, createStorage } from "../../utils";
import { KubeObjectStore, KubeObjectStoreLoadingParams } from "../../kube-object.store";
@@ -7,14 +8,14 @@ import { apiManager } from "../../api/api-manager";
import { isAllowedResource } from "../../../common/rbac";
import { clusterStore, 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)
}
});
@@ -51,9 +52,9 @@ export class NamespaceStore extends KubeObjectStore<Namespace> {
await getHostedCluster().whenReady; // wait for cluster-state from main
this.isReady = true;
this.setContext(this.initNamespaces);
this.onSelectedNamespacesChange();
this.onAllowedNamespacesChange();
this.setContext(this.initialNamespaces);
this.autoLoadAllowedNamespaces();
this.autoUpdateUrlAndLocalStorage();
}
public onContextChange(callback: (contextNamespaces: string[]) => void, opts: IReactionOptions = {}): IReactionDisposer {
@@ -63,7 +64,7 @@ export class NamespaceStore extends KubeObjectStore<Namespace> {
});
}
private onSelectedNamespacesChange(): IReactionDisposer {
private autoUpdateUrlAndLocalStorage(): IReactionDisposer {
return this.onContextChange(namespaces => {
storage.set(namespaces); // save to local-storage
namespaceUrlParam.set(namespaces, { replaceHistory: true }); // update url
@@ -73,7 +74,7 @@ export class NamespaceStore extends KubeObjectStore<Namespace> {
});
}
private onAllowedNamespacesChange(): IReactionDisposer {
private autoLoadAllowedNamespaces(): IReactionDisposer {
return reaction(() => this.allowedNamespaces, () => this.loadAll(), {
fireImmediately: true,
equals: comparer.identity,
@@ -84,28 +85,19 @@ export class NamespaceStore extends KubeObjectStore<Namespace> {
return toJS(getHostedCluster().allowedNamespaces);
}
get initNamespaces() {
const allowedNamespaces = new Set(this.allowedNamespaces);
const lastUsedNamespaces = new Set(storage.get());
private get initialNamespaces(): string[] {
const allowed = new Set(this.allowedNamespaces);
const prevSelected = storage.get();
// remove previously saved, but currently disallowed namespaces
lastUsedNamespaces.forEach(namespace => {
if (!allowedNamespaces.has(namespace)) {
lastUsedNamespaces.delete(namespace);
}
});
// return previously saved and currently allowed namespaces
if (lastUsedNamespaces.size) {
return Array.from(lastUsedNamespaces);
if (Array.isArray(prevSelected)) {
return prevSelected.filter(namespace => allowed.has(namespace));
}
// otherwise select "default" or first allowed namespace
else {
if (allowedNamespaces.has("default")) {
return ["default"];
} else if (allowedNamespaces.size) {
return [Array.from(allowedNamespaces)[0]];
}
if (allowed.has("default")) {
return ["default"];
} else if (allowed.size) {
return [Array.from(allowed)[0]];
}
return [];
@@ -132,17 +124,18 @@ export class NamespaceStore extends KubeObjectStore<Namespace> {
return super.subscribe(apis);
}
async loadAll() {
return super.loadAll({
// prevent multiple loading from different sources (e.g. items-list-layout, namespace-select)
private loadAllLazy = debounce(() => {
super.loadAll({
namespaces: this.allowedNamespaces,
});
}, 250);
async loadAll() {
this.loadAllLazy();
}
protected async loadItems({ isAdmin, namespaces }: KubeObjectStoreLoadingParams) {
if (isAdmin) {
return this.api.list();
}
protected async loadItems({ namespaces }: KubeObjectStoreLoadingParams) {
if (!isAllowedResource("namespaces")) {
return namespaces.map(getDummyNamespace);
}
+10 -9
View File
@@ -7,6 +7,7 @@ import { IResourceMetricsValue, ResourceMetricsContext } from "../resource-metri
import { observer } from "mobx-react";
import { ChartOptions, ChartPoint } from "chart.js";
import { themeStore } from "../../theme.store";
import { mapValues } from "lodash";
type IContext = IResourceMetricsValue<Node, { metrics: IClusterMetrics }>;
@@ -15,26 +16,26 @@ export const NodeCharts = observer(() => {
const id = object.getId();
const { chartCapacityColor } = themeStore.activeTheme.colors;
if (!metrics) return null;
if (isMetricsEmpty(metrics)) return <NoMetrics/>;
if (!metrics) {
return null;
}
const values = Object.values(metrics).map(metric =>
normalizeMetrics(metric).data.result[0].values
);
const [
if (isMetricsEmpty(metrics)) {
return <NoMetrics />;
}
const {
memoryUsage,
memoryRequests,
_memoryLimits, // eslint-disable-line unused-imports/no-unused-vars-ts
memoryCapacity,
cpuUsage,
cpuRequests,
_cpuLimits, // eslint-disable-line unused-imports/no-unused-vars-ts
cpuCapacity,
podUsage,
podCapacity,
fsSize,
fsUsage
] = values;
} = mapValues(metrics, metric => normalizeMetrics(metric).data.result[0].values);
const datasets = [
// CPU
@@ -26,10 +26,10 @@ export class RoleBindingsStore extends KubeObjectStore<RoleBinding> {
return clusterRoleBindingApi.get(params);
}
protected async loadItems({ isAdmin, namespaces }: KubeObjectStoreLoadingParams): Promise<RoleBinding[]> {
protected async loadItems(params: KubeObjectStoreLoadingParams): Promise<RoleBinding[]> {
const items = await Promise.all([
super.loadItems({ isAdmin, namespaces, api: clusterRoleBindingApi }),
super.loadItems({ isAdmin, namespaces, api: roleBindingApi }),
super.loadItems({ ...params, api: clusterRoleBindingApi }),
super.loadItems({ ...params, api: roleBindingApi }),
]);
return items.flat();
@@ -24,10 +24,10 @@ export class RolesStore extends KubeObjectStore<Role> {
return clusterRoleApi.get(params);
}
protected async loadItems({ isAdmin, namespaces }: KubeObjectStoreLoadingParams): Promise<Role[]> {
protected async loadItems(params: KubeObjectStoreLoadingParams): Promise<Role[]> {
const items = await Promise.all([
super.loadItems({ isAdmin, namespaces, api: clusterRoleApi }),
super.loadItems({ isAdmin, namespaces, api: roleApi }),
super.loadItems({ ...params, api: clusterRoleApi }),
super.loadItems({ ...params, api: roleApi }),
]);
return items.flat();
@@ -48,7 +48,6 @@ export class WorkloadsOverview extends React.Component<Props> {
if (this.isUnmounting) break;
try {
store.reset();
await store.loadAll();
unsubscribeMap.get(store)?.(); // unsubscribe previous watcher
unsubscribeMap.set(store, store.subscribe());
@@ -74,6 +74,8 @@ export class Pods extends React.Component<Props> {
<KubeObjectListLayout
className="Pods" store={podsStore}
dependentStores={[volumeClaimStore, eventStore]}
tableId = "workloads_pods"
isConfigurable
sortingCallbacks={{
[sortBy.name]: (pod: Pod) => pod.getName(),
[sortBy.namespace]: (pod: Pod) => pod.getNs(),
@@ -94,7 +96,7 @@ export class Pods extends React.Component<Props> {
renderHeaderTitle="Pods"
renderTableHeader={[
{ title: "Name", className: "name", sortBy: sortBy.name },
{ className: "warning" },
{ className: "warning", showWithColumn: "name" },
{ title: "Namespace", className: "namespace", sortBy: sortBy.namespace },
{ title: "Containers", className: "containers", sortBy: sortBy.containers },
{ title: "Restarts", className: "restarts", sortBy: sortBy.restarts },
@@ -22,7 +22,7 @@
height: 18px; // Must be equal to lineHeight variable in pod-log-list.tsx
font-family: var(--font-monospace);
font-size: smaller;
white-space: pre;
white-space: nowrap;
&:hover {
background: var(--logRowHoverBackground);
@@ -1,4 +1,5 @@
import "./item-list-layout.scss";
import "./table-menu.scss";
import groupBy from "lodash/groupBy";
import React, { ReactNode } from "react";
@@ -18,6 +19,11 @@ import { PageFiltersList } from "./page-filters-list";
import { PageFiltersSelect } from "./page-filters-select";
import { NamespaceSelectFilter } from "../+namespaces/namespace-select";
import { themeStore } from "../../theme.store";
import { MenuActions} from "../menu/menu-actions";
import { MenuItem } from "../menu";
import { Checkbox } from "../checkbox";
import { userStore } from "../../../common/user-store";
import logger from "../../../main/logger";
// todo: refactor, split to small re-usable components
@@ -32,6 +38,7 @@ interface IHeaderPlaceholders {
}
export interface ItemListLayoutProps<T extends ItemObject = ItemObject> {
tableId?: string;
className: IClassName;
store: ItemStore<T>;
dependentStores?: ItemStore[];
@@ -50,6 +57,7 @@ export interface ItemListLayoutProps<T extends ItemObject = ItemObject> {
isReady?: boolean; // show loading indicator while not ready
isSelectable?: boolean; // show checkbox in rows for selecting items
isSearchable?: boolean; // apply search-filter & add search-input
isConfigurable?: boolean;
copyClassNameFromHeadCells?: boolean;
sortingCallbacks?: { [sortBy: string]: TableSortCallback };
tableProps?: Partial<TableProps>; // low-level table configuration
@@ -74,6 +82,7 @@ const defaultProps: Partial<ItemListLayoutProps> = {
showHeader: true,
isSearchable: true,
isSelectable: true,
isConfigurable: false,
copyClassNameFromHeadCells: true,
dependentStores: [],
filterItems: [],
@@ -92,6 +101,7 @@ export class ItemListLayout extends React.Component<ItemListLayoutProps> {
private watchDisposers: IReactionDisposer[] = [];
@observable hiddenColumnNames = new Set<string>();
@observable isUnmounting = false;
@observable userSettings: ItemListLayoutUserSettings = {
@@ -112,11 +122,11 @@ export class ItemListLayout extends React.Component<ItemListLayoutProps> {
}
async componentDidMount() {
this.loadStores();
if (!this.props.isClusterScoped) {
disposeOnUnmount(this, [
namespaceStore.onContextChange(() => this.loadStores(), {
fireImmediately: true,
})
namespaceStore.onContextChange(() => this.loadStores())
]);
}
}
@@ -127,7 +137,10 @@ export class ItemListLayout extends React.Component<ItemListLayoutProps> {
}
@computed get stores() {
const { store, dependentStores, isClusterScoped } = this.props;
const { store, dependentStores, isClusterScoped, tableId } = this.props;
if (this.canBeConfigured) this.hiddenColumnNames = new Set(userStore.preferences?.hiddenTableColumns?.[tableId]);
const stores = new Set([store, ...dependentStores]);
if (!isClusterScoped) {
@@ -148,7 +161,6 @@ export class ItemListLayout extends React.Component<ItemListLayoutProps> {
}
try {
store.reset();
await store.loadAll();
this.watchDisposers.push(store.subscribe());
} catch (error) {
@@ -195,9 +207,7 @@ export class ItemListLayout extends React.Component<ItemListLayoutProps> {
};
@computed get isReady() {
const { isReady, store } = this.props;
return typeof isReady == "boolean" ? isReady : store.isLoaded;
return this.props.isReady ?? this.props.store.isLoaded;
}
@computed get filters() {
@@ -243,6 +253,42 @@ export class ItemListLayout extends React.Component<ItemListLayoutProps> {
return this.applyFilters(filterItems, allItems);
}
updateColumnFilter(checkboxValue: boolean, columnName: string) {
if (checkboxValue){
this.hiddenColumnNames.delete(columnName);
} else {
this.hiddenColumnNames.add(columnName);
}
if (this.canBeConfigured) {
userStore.preferences.hiddenTableColumns[this.props.tableId] = Array.from(this.hiddenColumnNames);
}
}
columnIsVisible(index: number): boolean {
const {renderTableHeader} = this.props;
if (!this.canBeConfigured) return true;
return !this.hiddenColumnNames.has(renderTableHeader[index].showWithColumn ?? renderTableHeader[index].className);
}
get canBeConfigured(): boolean {
const { isConfigurable, tableId, renderTableHeader } = this.props;
if (!isConfigurable || !tableId) {
return false;
}
if (!renderTableHeader?.every(({ className }) => className)) {
logger.warning("[ItemObjectList]: cannot configure an object list without all headers being identifiable");
return false;
}
return true;
}
@autobind()
getRow(uid: string) {
const {
@@ -286,7 +332,7 @@ export class ItemListLayout extends React.Component<ItemListLayoutProps> {
}
}
return <TableCell key={index} {...cellProps} />;
return this.columnIsVisible(index) ? <TableCell key={index} {...cellProps} /> : null;
})
}
{renderItemMenu && (
@@ -330,12 +376,7 @@ export class ItemListLayout extends React.Component<ItemListLayoutProps> {
}
renderNoItems() {
const { allItems, items, filters } = this;
const allItemsCount = allItems.length;
const itemsCount = items.length;
const isFiltered = filters.length > 0 && allItemsCount > itemsCount;
if (isFiltered) {
if (this.filters.length > 0) {
return (
<NoItems>
No items found.
@@ -458,14 +499,18 @@ export class ItemListLayout extends React.Component<ItemListLayoutProps> {
onClick={prevDefault(() => store.toggleSelectionAll(items))}
/>
)}
{renderTableHeader.map((cellProps, index) => <TableCell key={index} {...cellProps} />)}
{renderItemMenu && <TableCell className="menu"/>}
{renderTableHeader.map((cellProps, index) => this.columnIsVisible(index) ? <TableCell key={index} {...cellProps} /> : null)}
{renderItemMenu && <TableCell className="menu">
{this.canBeConfigured && this.renderColumnMenu()}
</TableCell>
}
</TableHead>
)}
{
!virtual && items.map(item => this.getRow(item.getId()))
}
</Table>
)}
<AddRemoveButtons
onRemove={selectedItems.length ? removeItemsDialog : null}
@@ -476,6 +521,29 @@ export class ItemListLayout extends React.Component<ItemListLayoutProps> {
);
}
renderColumnMenu() {
const { renderTableHeader} = this.props;
return (
<MenuActions
toolbar = {false}
autoCloseOnSelect = {false}
className={cssNames("KubeObjectMenu")}
>
{renderTableHeader.map((cellProps, index) => (
!cellProps.showWithColumn &&
<MenuItem key={index} className="input">
<Checkbox label = {cellProps.title ?? `<${cellProps.className}>`}
className = "MenuCheckbox"
value ={!this.hiddenColumnNames.has(cellProps.className)}
onChange = {(v) => this.updateColumnFilter(v, cellProps.className)}
/>
</MenuItem>
))}
</MenuActions>
);
}
renderFooter() {
if (this.props.renderFooter) {
return this.props.renderFooter(this);
@@ -0,0 +1,4 @@
.MenuCheckbox {
width: 100%;
height: 100%;
}
@@ -13,6 +13,7 @@ import isString from "lodash/isString";
export interface MenuActionsProps extends Partial<MenuProps> {
className?: string;
toolbar?: boolean; // display menu as toolbar with icons
autoCloseOnSelect?: boolean;
triggerIcon?: string | IconProps | React.ReactNode;
removeConfirmationMessage?: React.ReactNode | (() => React.ReactNode);
updateAction?(): void;
@@ -80,7 +81,7 @@ export class MenuActions extends React.Component<MenuActionsProps> {
render() {
const {
className, toolbar, children, updateAction, removeAction, triggerIcon, removeConfirmationMessage,
className, toolbar, autoCloseOnSelect, children, updateAction, removeAction, triggerIcon, removeConfirmationMessage,
...menuProps
} = this.props;
const menuClassName = cssNames("MenuActions flex", className, {
@@ -98,7 +99,7 @@ export class MenuActions extends React.Component<MenuActionsProps> {
className={menuClassName}
usePortal={autoClose}
closeOnScroll={autoClose}
closeOnClickItem={autoClose}
closeOnClickItem={autoCloseOnSelect ?? autoClose }
closeOnClickOutside={autoClose}
{...menuProps}
>
+2 -1
View File
@@ -15,6 +15,7 @@ export interface TableCellProps extends React.DOMAttributes<HTMLDivElement> {
isChecked?: boolean; // mark checkbox as checked or not
renderBoolean?: boolean; // show "true" or "false" for all of the children elements are "typeof boolean"
sortBy?: TableSortBy; // column name, must be same as key in sortable object <Table sortable={}/>
showWithColumn?: string // className of another column, if it is not empty the current column is not shown in the filter menu, visibility of this one is the same as a specified column, applicable to headers only
_sorting?: Partial<TableSortParams>; // <Table> sorting state, don't use this prop outside (!)
_sort?(sortBy: TableSortBy): void; // <Table> sort function, don't use this prop outside (!)
_nowrap?: boolean; // indicator, might come from parent <TableHead>, don't use this prop outside (!)
@@ -63,7 +64,7 @@ export class TableCell extends React.Component<TableCellProps> {
}
render() {
const { className, checkbox, isChecked, sortBy, _sort, _sorting, _nowrap, children, title, renderBoolean: displayBoolean, ...cellProps } = this.props;
const { className, checkbox, isChecked, sortBy, _sort, _sorting, _nowrap, children, title, renderBoolean: displayBoolean, showWithColumn, ...cellProps } = this.props;
const classNames = cssNames("TableCell", className, {
checkbox,
nowrap: _nowrap,
+1 -1
View File
@@ -9,7 +9,7 @@ export interface ItemObject {
@autobind()
export abstract class ItemStore<T extends ItemObject = ItemObject> {
abstract loadAll(...args: any[]): Promise<any>;
abstract loadAll(...args: any[]): Promise<void>;
protected defaultSorting = (item: T) => item.getName();
+14 -20
View File
@@ -6,10 +6,9 @@ import { ItemStore } from "./item.store";
import { apiManager } from "./api/api-manager";
import { IKubeApiQueryParams, KubeApi } from "./api/kube-api";
import { KubeJsonApiData } from "./api/kube-json-api";
import { getHostedCluster } from "../common/cluster-store";
import { isAllowedResourceType } from "../common/rbac";
export interface KubeObjectStoreLoadingParams {
isAdmin: boolean;
namespaces: string[];
api?: KubeApi;
}
@@ -76,16 +75,18 @@ export abstract class KubeObjectStore<T extends KubeObject = any> extends ItemSt
}
}
protected async loadItems({ isAdmin, namespaces, api }: KubeObjectStoreLoadingParams): Promise<T[]> {
if (!api.isNamespaced) {
if (isAdmin) return api.list({}, this.query);
protected async loadItems({ namespaces, api }: KubeObjectStoreLoadingParams): Promise<T[]> {
if (isAllowedResourceType(api.kind)) {
if (api.isNamespaced) {
return Promise
.all(namespaces.map(namespace => api.list({ namespace })))
.then(items => items.flat());
}
return [];
return api.list({}, this.query);
}
return Promise
.all(namespaces.map(namespace => api.list({ namespace })))
.then(items => items.flat());
return [];
}
protected filterItemsOnLoad(items: T[]) {
@@ -93,28 +94,21 @@ export abstract class KubeObjectStore<T extends KubeObject = any> extends ItemSt
}
@action
async loadAll(params: { namespaces?: string[] } = {}) {
async loadAll({ namespaces: contextNamespaces }: { namespaces?: string[] } = {}) {
this.isLoading = true;
let items: T[];
try {
let contextNamespaces = params.namespaces;
if (!params.namespaces) {
if (!contextNamespaces) {
const { namespaceStore } = await import("./components/+namespaces/namespace.store");
await namespaceStore.whenReady;
contextNamespaces = namespaceStore.getContextNamespaces();
}
items = await this.loadItems({
isAdmin: getHostedCluster().isAdmin,
namespaces: contextNamespaces,
api: this.api,
});
let items = await this.loadItems({ namespaces: contextNamespaces, api: this.api });
items = this.filterItemsOnLoad(items);
items = this.sortItems(items);
this.items.replace(items);
this.isLoaded = true;
} catch (error) {