1
0
mirror of https://github.com/lensapp/lens.git synced 2025-05-20 05:10:56 +00:00

Fix local cluster delete flow

- Now checks for the cluster being the current cluster and confirms the
  action

- <ConfirmDialog> is fixed to work with several confirmations happinging
  at once

Signed-off-by: Sebastian Malton <sebastian@malton.name>
This commit is contained in:
Sebastian Malton 2021-07-21 12:33:17 -04:00
parent 8312cdd1f8
commit 0e1a4a6fa8
7 changed files with 303 additions and 129 deletions

View File

@ -21,13 +21,12 @@
import { catalogCategoryRegistry } from "../catalog/catalog-category-registry";
import { CatalogEntity, CatalogEntityActionContext, CatalogEntityContextMenuContext, CatalogEntityMetadata, CatalogEntityStatus } from "../catalog";
import { clusterActivateHandler, clusterDeleteHandler, clusterDisconnectHandler } from "../cluster-ipc";
import { clusterActivateHandler, clusterDisconnectHandler } from "../cluster-ipc";
import { ClusterStore } from "../cluster-store";
import { requestMain } from "../ipc";
import { CatalogCategory, CatalogCategorySpec } from "../catalog";
import { app } from "electron";
import type { CatalogEntitySpec } from "../catalog/catalog-entity";
import { HotbarStore } from "../hotbar-store";
export interface KubernetesClusterPrometheusMetrics {
address?: {
@ -102,25 +101,11 @@ export class KubernetesCluster extends CatalogEntity<KubernetesClusterMetadata,
async onContextMenuOpen(context: CatalogEntityContextMenuContext) {
if (!this.metadata.source || this.metadata.source === "local") {
context.menuItems.push(
{
title: "Settings",
icon: "edit",
onClick: () => context.navigate(`/entity/${this.metadata.uid}/settings`)
},
{
title: "Delete",
icon: "delete",
onClick: () => {
HotbarStore.getInstance().removeAllHotbarItems(this.getId());
requestMain(clusterDeleteHandler, this.metadata.uid);
},
confirm: {
// TODO: change this to be a <p> tag with better formatting once this code can accept it.
message: `Delete the "${this.metadata.name}" context from "${this.spec.kubeconfigPath}"?`
}
},
);
context.menuItems.push({
title: "Settings",
icon: "edit",
onClick: () => context.navigate(`/entity/${this.metadata.uid}/settings`)
});
}
switch (this.status.phase) {

View File

@ -25,5 +25,7 @@ export const clusterVisibilityHandler = "cluster:visibility";
export const clusterRefreshHandler = "cluster:refresh";
export const clusterDisconnectHandler = "cluster:disconnect";
export const clusterDeleteHandler = "cluster:delete";
export const clusterSetDeletingHandler = "cluster:deleting:set";
export const clusterClearDeletingHandler = "cluster:deleting:clear";
export const clusterKubectlApplyAllHandler = "cluster:kubectl-apply-all";
export const clusterKubectlDeleteAllHandler = "cluster:kubectl-delete-all";

View File

@ -26,6 +26,11 @@ export function noop<T extends any[]>(...args: T): void {
return void args;
}
export enum ControlFlow {
Stop,
Continue
}
export * from "./app-version";
export * from "./autobind";
export * from "./base64";

View File

@ -22,16 +22,13 @@
import { BrowserWindow, dialog, IpcMainInvokeEvent } from "electron";
import { KubernetesCluster } from "../../common/catalog-entities";
import { clusterFrameMap } from "../../common/cluster-frames";
import { clusterActivateHandler, clusterSetFrameIdHandler, clusterVisibilityHandler, clusterRefreshHandler, clusterDisconnectHandler, clusterKubectlApplyAllHandler, clusterKubectlDeleteAllHandler, clusterDeleteHandler } from "../../common/cluster-ipc";
import { ClusterStore } from "../../common/cluster-store";
import { clusterActivateHandler, clusterSetFrameIdHandler, clusterVisibilityHandler, clusterRefreshHandler, clusterDisconnectHandler, clusterKubectlApplyAllHandler, clusterKubectlDeleteAllHandler, clusterDeleteHandler, clusterSetDeletingHandler, clusterClearDeletingHandler } from "../../common/cluster-ipc";
import type { ClusterId } from "../../common/cluster-types";
import { ClusterStore } from "../../common/cluster-store";
import { appEventBus } from "../../common/event-bus";
import { dialogShowOpenDialogHandler, ipcMainHandle } from "../../common/ipc";
import { catalogEntityRegistry } from "../catalog";
import { ClusterManager } from "../cluster-manager";
import { bundledKubectlPath } from "../kubectl";
import logger from "../logger";
import { promiseExecFile } from "../promise-exec";
import { ResourceApplier } from "../resource-applier";
import { WindowManager } from "../window-manager";
@ -79,27 +76,23 @@ export function initIpcMainHandlers() {
}
});
ipcMainHandle(clusterDeleteHandler, async (event, clusterId: ClusterId) => {
appEventBus.emit({ name: "cluster", action: "remove" });
ipcMainHandle(clusterDeleteHandler, (event, clusterId: ClusterId) => {
const cluster = ClusterStore.getInstance().getById(clusterId);
if (!cluster) {
return;
}
ClusterManager.getInstance().deleting.add(clusterId);
cluster.disconnect();
clusterFrameMap.delete(cluster.id);
const kubectlPath = bundledKubectlPath();
const args = ["config", "delete-context", cluster.contextName, "--kubeconfig", cluster.kubeConfigPath];
});
try {
await promiseExecFile(kubectlPath, args);
} catch ({ stderr }) {
logger.error(`[CLUSTER-REMOVE]: failed to remove cluster: ${stderr}`, { clusterId, context: cluster.contextName });
ipcMainHandle(clusterSetDeletingHandler, (event, clusterId: string) => {
ClusterManager.getInstance().deleting.add(clusterId);
});
throw `Failed to remove cluster: ${stderr}`;
}
ipcMainHandle(clusterClearDeletingHandler, (event, clusterId: string) => {
ClusterManager.getInstance().deleting.delete(clusterId);
});
ipcMainHandle(clusterKubectlApplyAllHandler, async (event, clusterId: ClusterId, resources: string[], extraArgs: string[]) => {

View File

@ -22,17 +22,20 @@
import "./confirm-dialog.scss";
import React, { ReactNode } from "react";
import { observable, makeObservable } from "mobx";
import { action, observable } from "mobx";
import { observer } from "mobx-react";
import { cssNames, noop, prevDefault } from "../../utils";
import { Button, ButtonProps } from "../button";
import { Dialog, DialogProps } from "../dialog";
import { Icon } from "../icon";
import { Notifications } from "../notifications";
export interface ConfirmDialogProps extends Partial<DialogProps> {
}
export interface ConfirmDialogRootProps {
className?: string;
}
export interface ConfirmDialogParams extends ConfirmDialogBooleanParams {
ok?: () => any | Promise<any>;
cancel?: () => any | Promise<any>;
@ -47,23 +50,24 @@ export interface ConfirmDialogBooleanParams {
cancelButtonProps?: Partial<ButtonProps>;
}
const dialogState = observable.object({
isOpen: false,
params: null as ConfirmDialogParams,
});
const dialogState = observable.set<ConfirmDialogParams>([], { deep: false });
@observer
export class ConfirmDialog extends React.Component<ConfirmDialogProps> {
@observable isSaving = false;
constructor(props: ConfirmDialogProps) {
super(props);
makeObservable(this);
}
export class ConfirmDialog extends React.Component<ConfirmDialogRootProps> {
static defaultParams: Partial<ConfirmDialogParams> = {
ok: noop,
cancel: noop,
labelOk: "Ok",
labelCancel: "Cancel",
icon: <Icon big material="warning" />,
};
@action
static open(params: ConfirmDialogParams) {
dialogState.isOpen = true;
dialogState.params = params;
dialogState.add({
...ConfirmDialog.defaultParams,
...params,
});
}
static confirm(params: ConfirmDialogBooleanParams): Promise<boolean> {
@ -76,92 +80,62 @@ export class ConfirmDialog extends React.Component<ConfirmDialogProps> {
});
}
static defaultParams: Partial<ConfirmDialogParams> = {
ok: noop,
cancel: noop,
labelOk: "Ok",
labelCancel: "Cancel",
icon: <Icon big material="warning"/>,
};
get params(): ConfirmDialogParams {
return Object.assign({}, ConfirmDialog.defaultParams, dialogState.params);
}
ok = async () => {
ok = async (params: ConfirmDialogParams) => {
try {
this.isSaving = true;
await (async () => this.params.ok())();
} catch (error) {
Notifications.error(
<>
<p>Confirmation action failed:</p>
<p>{error?.message ?? error?.toString?.() ?? "Unknown error"}</p>
</>
);
} finally {
this.isSaving = false;
dialogState.isOpen = false;
await params.ok();
} catch {} finally {
dialogState.delete(params);
}
};
onClose = () => {
this.isSaving = false;
};
close = async () => {
close = async (params: ConfirmDialogParams) => {
try {
await Promise.resolve(this.params.cancel());
} catch (error) {
Notifications.error(
<>
<p>Cancelling action failed:</p>
<p>{error?.message ?? error?.toString?.() ?? "Unknown error"}</p>
</>
);
} finally {
this.isSaving = false;
dialogState.isOpen = false;
await params.cancel();
} catch { } finally {
dialogState.delete(params);
}
};
render() {
const { className, ...dialogProps } = this.props;
const {
icon, labelOk, labelCancel, message,
okButtonProps = {},
cancelButtonProps = {},
} = this.params;
const { className } = this.props;
return (
<Dialog
{...dialogProps}
className={cssNames("ConfirmDialog", className)}
isOpen={dialogState.isOpen}
onClose={this.onClose}
close={this.close}
>
<div className="confirm-content">
{icon} {message}
</div>
<div className="confirm-buttons">
<Button
plain
className="cancel"
label={labelCancel}
onClick={prevDefault(this.close)}
{...cancelButtonProps}
/>
<Button
autoFocus primary
className="ok"
label={labelOk}
onClick={prevDefault(this.ok)}
waiting={this.isSaving}
{...okButtonProps}
/>
</div>
</Dialog>
);
return [...dialogState].reduce<JSX.Element>((prev, params) => {
const {
icon, labelOk, labelCancel, message,
okButtonProps = {},
cancelButtonProps = {},
} = params;
return (
<>
{prev}
<Dialog
className={cssNames("ConfirmDialog", className)}
isOpen={true}
close={() => this.close(params)}
>
<div className="confirm-content">
{icon} {message}
</div>
<div className="confirm-buttons">
<Button
plain
className="cancel"
label={labelCancel}
onClick={prevDefault(() => this.close(params))}
{...cancelButtonProps}
/>
<Button
autoFocus primary
className="ok"
label={labelOk}
onClick={prevDefault(() => this.ok(params))}
{...okButtonProps}
/>
</div>
</Dialog>
</>
);
}, null);
}
}

View File

@ -0,0 +1,77 @@
/**
* Copyright (c) 2021 OpenLens Authors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import type { KubeConfig } from "@kubernetes/client-node";
import React from "react";
import type { Cluster } from "../../../main/cluster";
import { ControlFlow, iter } from "../../utils";
import { ConfirmDialog } from "../confirm-dialog";
import { Select } from "../select";
export interface DeleteClusterDialogArgs {
config: KubeConfig;
cluster: Cluster;
}
export async function deleteClusterConfirmDialog({ config, cluster }: DeleteClusterDialogArgs): Promise<[ControlFlow.Stop] | [ControlFlow.Continue, string | false]> {
const contextNames = new Set(config.getContexts().map(({ name }) => name));
contextNames.delete(cluster.contextName);
if (config.currentContext !== cluster.contextName || contextNames.size === 0) {
return [ControlFlow.Continue, false];
}
const options = [
{
label: "--unset current-context--",
value: false,
},
...iter.map(contextNames, name => ({
label: name,
value: name,
})),
];
let selectedOption: string | false = false;
const didConfirm = await ConfirmDialog.confirm({
labelOk: "Select context",
message: (
<>
<p>
The context you are deleting is the <code>current-context</code> in the <code>{cluster.kubeConfigPath}</code> file.
Please select one of the other contexts to replace it with.
</p>
<br />
<Select
options={options}
onChange={({ value }) => selectedOption = value}
themeName="light"
/>
</>
)
});
if (didConfirm) {
return [ControlFlow.Continue, selectedOption];
}
return [ControlFlow.Stop];
}

View File

@ -20,14 +20,152 @@
*/
import React from "react";
import fs from "fs";
import path from "path";
import tempy from "tempy";
import "../../common/catalog-entities/kubernetes-cluster";
import { WebLinkCategory } from "../../common/catalog-entities";
import { ClusterStore } from "../../common/cluster-store";
import { appEventBus } from "../../common/event-bus";
import { catalogCategoryRegistry } from "../api/catalog-category-registry";
import { WeblinkAddCommand } from "../components/catalog-entities/weblink-add-command";
import { CommandOverlay } from "../components/command-palette";
import { Notifications } from "../components/notifications";
import { loadConfigFromString } from "../../common/kube-helpers";
import { requestMain } from "../../common/ipc";
import { clusterClearDeletingHandler, clusterDeleteHandler, clusterSetDeletingHandler } from "../../common/cluster-ipc";
import { ControlFlow } from "../utils";
import { HotbarStore } from "../../common/hotbar-store";
import type { ClusterId } from "../../common/cluster-types";
import type { Cluster } from "../../main/cluster";
import { deleteClusterConfirmDialog } from "../components/dialog/delete-cluster-dialog";
function initWebLinks() {
WebLinkCategory.onAdd = () => CommandOverlay.open(<WeblinkAddCommand />);
}
function initKubernetesClusters() {
catalogCategoryRegistry
.getForGroupKind("entity.k8slens.dev", "KubernetesCluster")
.on("contextMenuOpen", (entity, context) => {
context.menuItems.push({
title: "Delete",
icon: "delete",
onClick: () => deleteLocalCluster(entity.metadata.uid),
confirm: {
// TODO: change this to be a <p> tag with better formatting once this code can accept it.
message: `Delete the "${entity.metadata.name}" context from "${entity.spec.kubeconfigPath}"?`
}
});
});
}
export function initCatalog() {
initWebLinks();
initKubernetesClusters();
}
async function setDeleting(cluster: Cluster): Promise<ControlFlow> {
await requestMain(clusterSetDeletingHandler, cluster.id);
try {
await fs.promises.access(cluster.kubeConfigPath, fs.constants.W_OK | fs.constants.R_OK);
} catch {
await requestMain(clusterClearDeletingHandler, cluster.id);
Notifications.error(
<p>Cannot remove cluster, missing write permissions for <code>{cluster.kubeConfigPath}</code></p>
);
return ControlFlow.Stop;
}
return ControlFlow.Continue;
}
async function aquireConfigLock(cluster: Cluster, lockFilePath: string): Promise<ControlFlow> {
try {
const fd = await fs.promises.open(lockFilePath, "wx");
await fd.close(); // close immeditaly as we will want to delete the file later
} catch (error) {
await requestMain(clusterClearDeletingHandler, cluster.id);
console.warn("[KUBERNETES-CLUSTER]: failed to lock config file", error);
switch (error.code) {
case "EEXIST":
case "EISDIR":
Notifications.error("Cannot remove cluster, failed to aquire lock file. Already held.");
break;
case "EPERM":
case "EACCES":
Notifications.error("Cannot remove cluster, failed to aquire lock file. Permission denied.");
break;
default:
Notifications.error(`Cannot remove cluster, failed to aquire lock file. ${error}`);
break;
}
return ControlFlow.Stop;
}
return ControlFlow.Continue;
}
export async function deleteLocalCluster(clusterId: ClusterId): Promise<void> {
appEventBus.emit({ name: "cluster", action: "remove" });
const cluster = ClusterStore.getInstance().getById(clusterId);
if (!cluster) {
return console.warn("[KUBERNETES-CLUSTER]: cannot delete cluster, does not exist in store", { clusterId });
}
switch (await setDeleting(cluster)) {
case ControlFlow.Stop:
return;
}
const lockFilePath = `${path.resolve(cluster.kubeConfigPath)}.lock`;
switch (await aquireConfigLock(cluster, lockFilePath)) {
case ControlFlow.Stop:
return;
}
try {
const { config, error } = loadConfigFromString(await fs.promises.readFile(cluster.kubeConfigPath, "utf-8"));
if (error) {
throw error;
}
const [cf, selectedOption] = await deleteClusterConfirmDialog({ config, cluster });
switch (cf) {
case ControlFlow.Stop:
return void await requestMain(clusterClearDeletingHandler, cluster.id);
}
if (selectedOption === false) {
config.setCurrentContext(undefined);
} else {
config.setCurrentContext(selectedOption);
}
config.contexts = config.contexts.filter(context => context.name !== cluster.contextName);
const tmpFilePath = tempy.file();
await fs.promises.writeFile(tmpFilePath, config.exportConfig());
await fs.promises.rename(tmpFilePath, cluster.kubeConfigPath);
await requestMain(clusterDeleteHandler, clusterId);
HotbarStore.getInstance().removeAllHotbarItems(clusterId);
} catch (error) {
await requestMain(clusterClearDeletingHandler, clusterId);
console.warn("[KUBERNETES-CLUSTER]: failed to read or parse kube config file", error);
return void Notifications.error(`Cannot remove cluster, failed to process config file. ${error}`);
} finally {
await fs.promises.unlink(lockFilePath); // always unlink the file
}
}