Skip to content

Commit

Permalink
app: home: Add delete button for clusters
Browse files Browse the repository at this point in the history
Signed-off-by: Vincent T <[email protected]>
  • Loading branch information
vyncent-t committed Dec 19, 2024
1 parent b62a424 commit 12b74de
Show file tree
Hide file tree
Showing 9 changed files with 156 additions and 59 deletions.
39 changes: 37 additions & 2 deletions backend/cmd/headlamp.go
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,18 @@ func serveWithNoCacheHeader(fs http.Handler) http.HandlerFunc {
}
}

// defaultKubeConfigFile returns the default path to the kubeconfig file.
func defaultKubeConfigFile() (string, error) {
homeDir, err := os.UserHomeDir()
if err != nil {
return "", fmt.Errorf("failed to get user home directory: %v", err)
}

kubeConfigFile := filepath.Join(homeDir, ".kube", "config")

return kubeConfigFile, nil
}

// defaultKubeConfigPersistenceDir returns the default directory to store kubeconfig
// files of clusters that are loaded in Headlamp.
func defaultKubeConfigPersistenceDir() (string, error) {
Expand Down Expand Up @@ -1384,6 +1396,30 @@ func (c *HeadlampConfig) deleteCluster(w http.ResponseWriter, r *http.Request) {
return
}

removeKubeConfig := r.URL.Query().Get("removeKubeConfig") == "true"

if removeKubeConfig {
// delete context from actual default kubecofig file
kubeConfigFile, err := defaultKubeConfigFile()
if err != nil {
logger.Log(logger.LevelError, map[string]string{"cluster": name},
err, "failed to get default kubeconfig file path")
http.Error(w, "failed to get default kubeconfig file path", http.StatusInternalServerError)

return
}

// Use kubeConfigFile to remove the context from the default kubeconfig file
err = kubeconfig.RemoveContextFromFile(name, kubeConfigFile)
if err != nil {
logger.Log(logger.LevelError, map[string]string{"cluster": name},
err, "removing context from default kubeconfig file")
http.Error(w, "removing context from default kubeconfig file", http.StatusInternalServerError)

return
}
}

kubeConfigPersistenceFile, err := defaultKubeConfigPersistenceFile()
if err != nil {
logger.Log(logger.LevelError, map[string]string{"cluster": name},
Expand All @@ -1396,8 +1432,7 @@ func (c *HeadlampConfig) deleteCluster(w http.ResponseWriter, r *http.Request) {
logger.Log(logger.LevelInfo, map[string]string{
"cluster": name,
"kubeConfigPersistenceFile": kubeConfigPersistenceFile,
},
nil, "Removing cluster from kubeconfig")
}, nil, "Removing cluster from kubeconfig")

err = kubeconfig.RemoveContextFromFile(name, kubeConfigPersistenceFile)
if err != nil {
Expand Down
65 changes: 37 additions & 28 deletions frontend/src/components/App/Home/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,24 @@ import { ConfirmDialog } from '../../common';
import ResourceTable from '../../common/Resource/ResourceTable';
import RecentClusters from './RecentClusters';

/**
* Gets the origin of a cluster.
*
* @param cluster
* @returns A description of where the cluster is picked up from: dynamic, in-cluster, or from a kubeconfig file.
*/
function getOrigin(cluster: Cluster, t: any): string {
if (cluster?.meta_data?.source === 'kubeconfig') {
const kubeconfigPath = process.env.KUBECONFIG ?? '~/.kube/config';
return `Kubeconfig: ${kubeconfigPath}`;
} else if (cluster.meta_data?.source === 'dynamic_cluster') {
return t('translation|Plugin');
} else if (cluster.meta_data?.source === 'in_cluster') {
return t('translation|In-cluster');
}
return 'Unknown';
}

function ContextMenu({ cluster }: { cluster: Cluster }) {
const { t } = useTranslation(['translation']);
const history = useHistory();
Expand All @@ -33,8 +51,8 @@ function ContextMenu({ cluster }: { cluster: Cluster }) {
const menuId = useId('context-menu');
const [openConfirmDialog, setOpenConfirmDialog] = React.useState(false);

function removeCluster(cluster: Cluster) {
deleteCluster(cluster.name || '')
function removeCluster(cluster: Cluster, removeKubeconfig?: boolean) {
deleteCluster(cluster.name || '', removeKubeconfig)
.then(config => {
dispatch(setConfig(config));
})
Expand Down Expand Up @@ -91,7 +109,8 @@ function ContextMenu({ cluster }: { cluster: Cluster }) {
>
<ListItemText>{t('translation|Settings')}</ListItemText>
</MenuItem>
{helpers.isElectron() && cluster.meta_data?.source === 'dynamic_cluster' && (

{helpers.isElectron() && (
<MenuItem
onClick={() => {
setOpenConfirmDialog(true);
Expand All @@ -105,18 +124,28 @@ function ContextMenu({ cluster }: { cluster: Cluster }) {

<ConfirmDialog
open={openConfirmDialog}
handleClose={() => setOpenConfirmDialog(false)}
handleClose={() => {
setOpenConfirmDialog(false);
}}
onConfirm={() => {
setOpenConfirmDialog(false);
removeCluster(cluster);
if (cluster.meta_data?.source !== 'dynamic_cluster') {
removeCluster(cluster, true);
} else {
removeCluster(cluster);
}
}}
title={t('translation|Delete Cluster')}
description={t(
'translation|Are you sure you want to remove the cluster "{{ clusterName }}"?',
'translation|This action will delete cluster "{{ clusterName }}" from {{ source }}.',
{
clusterName: cluster.name,
source: getOrigin(cluster, t),
}
)}
checkboxDescription={
cluster.meta_data?.source !== 'dynamic_cluster' ? t('Delete from kubeconfig') : ''
}
/>
</>
);
Expand Down Expand Up @@ -238,24 +267,6 @@ function HomeComponent(props: HomeComponentProps) {
.sort();
}

/**
* Gets the origin of a cluster.
*
* @param cluster
* @returns A description of where the cluster is picked up from: dynamic, in-cluster, or from a kubeconfig file.
*/
function getOrigin(cluster: Cluster): string {
if (cluster.meta_data?.source === 'kubeconfig') {
const kubeconfigPath = process.env.KUBECONFIG ?? '~/.kube/config';
return `Kubeconfig: ${kubeconfigPath}`;
} else if (cluster.meta_data?.source === 'dynamic_cluster') {
return t('translation|Plugin');
} else if (cluster.meta_data?.source === 'in_cluster') {
return t('translation|In-cluster');
}
return 'Unknown';
}

const memoizedComponent = React.useMemo(
() => (
<PageGrid>
Expand Down Expand Up @@ -286,10 +297,8 @@ function HomeComponent(props: HomeComponentProps) {
},
{
label: t('Origin'),
getValue: cluster => getOrigin(cluster),
render: ({ name }) => (
<Typography variant="body2">{getOrigin(clusters[name])}</Typography>
),
getValue: cluster => getOrigin(cluster, t),
render: cluster => <Typography variant="body2">{getOrigin(cluster, t)}</Typography>,
},
{
label: t('Status'),
Expand Down
52 changes: 45 additions & 7 deletions frontend/src/components/common/ConfirmDialog.tsx
Original file line number Diff line number Diff line change
@@ -1,28 +1,41 @@
import { Checkbox } from '@mui/material';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import MuiDialog, { DialogProps as MuiDialogProps } from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import DialogContentText from '@mui/material/DialogContentText';
import React, { ReactNode } from 'react';
import React from 'react';
import { useTranslation } from 'react-i18next';
import { DialogTitle } from './Dialog';

export interface ConfirmDialogProps extends MuiDialogProps {
title: string;
description: ReactNode;
description: string | React.ReactNode;
checkboxDescription?: string;
onConfirm: () => void;
handleClose: () => void;
}

export function ConfirmDialog(props: ConfirmDialogProps) {
const { onConfirm, open, handleClose, title, description } = props;
const { t } = useTranslation();
const [checkedChoice, setcheckedChoice] = React.useState(false);

function onConfirmationClicked() {
handleClose();
onConfirm();
}

function closeDialog() {
setcheckedChoice(false);
handleClose();
}

function handleChoiceToggle() {
setcheckedChoice(!checkedChoice);
}

const focusedRef = React.useCallback((node: HTMLElement) => {
if (node !== null) {
node.setAttribute('tabindex', '-1');
Expand All @@ -34,21 +47,46 @@ export function ConfirmDialog(props: ConfirmDialogProps) {
<div>
<MuiDialog
open={open}
onClose={handleClose}
onClose={closeDialog}
aria-labelledby="alert-dialog-title"
aria-describedby="alert-dialog-description"
>
<DialogTitle id="alert-dialog-title">{title}</DialogTitle>
<DialogContent ref={focusedRef}>
<DialogContentText id="alert-dialog-description">{description}</DialogContentText>
{props.checkboxDescription && (
<Box
sx={{
display: 'flex',
alignItems: 'center',
marginTop: '10px',
}}
>
<DialogContentText id="alert-dialog-description">
{props.checkboxDescription}
</DialogContentText>
<Checkbox checked={checkedChoice} onChange={handleChoiceToggle} />
</Box>
)}
</DialogContent>
<DialogActions>
<Button onClick={handleClose} color="primary">
<Button
onClick={() => {
closeDialog();
}}
color="primary"
>
{t('No')}
</Button>
<Button onClick={onConfirmationClicked} color="primary">
{t('Yes')}
</Button>
{props.checkboxDescription ? (
<Button disabled={!checkedChoice} onClick={onConfirmationClicked} color="primary">
{t('I Agree')}
</Button>
) : (
<Button onClick={onConfirmationClicked} color="primary">
{t('Yes')}
</Button>
)}
</DialogActions>
</MuiDialog>
</div>
Expand Down
9 changes: 6 additions & 3 deletions frontend/src/i18n/locales/de/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,16 @@
"Cancel": "Abbrechen",
"Authenticate": "Authentifizieren Sie",
"Error authenticating": "Fehler beim Authentifizieren",
"Plugin": "",
"In-cluster": "",
"Actions": "Aktionen",
"View": "Ansicht",
"Settings": "Einstellungen",
"Delete": "Löschen",
"Delete Cluster": "",
"Are you sure you want to remove the cluster \"{{ clusterName }}\"?": "Sind Sie sicher, dass Sie den Cluster \"{{ clusterName }}\" entfernen möchten?",
"This action will delete cluster \"{{ clusterName }}\" from {{ source }}.": "",
"Delete from kubeconfig": "",
"Active": "Aktiv",
"Plugin": "",
"In-cluster": "",
"Home": "Startseite",
"All Clusters": "Alle Cluster",
"Name": "Name",
Expand Down Expand Up @@ -81,6 +82,7 @@
"Cluster Settings ({{ clusterName }})": "Cluster-Einstellungen ({{ clusterName }})",
"Go to cluster": "",
"Remove Cluster": "Cluster entfernen",
"Are you sure you want to remove the cluster \"{{ clusterName }}\"?": "Sind Sie sicher, dass Sie den Cluster \"{{ clusterName }}\" entfernen möchten?",
"Server": "Server",
"light theme": "helles Design",
"dark theme": "dunkles Design",
Expand Down Expand Up @@ -144,6 +146,7 @@
"Last Seen": "Zuletzt gesehen",
"Offline": "Offline",
"Lost connection to the cluster.": "",
"I Agree": "",
"No": "Nein",
"Yes": "Ja",
"Create {{ name }}": "",
Expand Down
9 changes: 6 additions & 3 deletions frontend/src/i18n/locales/en/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,16 @@
"Cancel": "Cancel",
"Authenticate": "Authenticate",
"Error authenticating": "Error authenticating",
"Plugin": "Plugin",
"In-cluster": "In-cluster",
"Actions": "Actions",
"View": "View",
"Settings": "Settings",
"Delete": "Delete",
"Delete Cluster": "Delete Cluster",
"Are you sure you want to remove the cluster \"{{ clusterName }}\"?": "Are you sure you want to remove the cluster \"{{ clusterName }}\"?",
"This action will delete cluster \"{{ clusterName }}\" from {{ source }}.": "This action will delete cluster \"{{ clusterName }}\" from {{ source }}.",
"Delete from kubeconfig": "Delete from kubeconfig",
"Active": "Active",
"Plugin": "Plugin",
"In-cluster": "In-cluster",
"Home": "Home",
"All Clusters": "All Clusters",
"Name": "Name",
Expand Down Expand Up @@ -81,6 +82,7 @@
"Cluster Settings ({{ clusterName }})": "Cluster Settings ({{ clusterName }})",
"Go to cluster": "Go to cluster",
"Remove Cluster": "Remove Cluster",
"Are you sure you want to remove the cluster \"{{ clusterName }}\"?": "Are you sure you want to remove the cluster \"{{ clusterName }}\"?",
"Server": "Server",
"light theme": "light theme",
"dark theme": "dark theme",
Expand Down Expand Up @@ -144,6 +146,7 @@
"Last Seen": "Last Seen",
"Offline": "Offline",
"Lost connection to the cluster.": "Lost connection to the cluster.",
"I Agree": "I Agree",
"No": "No",
"Yes": "Yes",
"Create {{ name }}": "Create {{ name }}",
Expand Down
9 changes: 6 additions & 3 deletions frontend/src/i18n/locales/es/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,16 @@
"Cancel": "Cancelar",
"Authenticate": "Autenticar",
"Error authenticating": "Error al autenticarse",
"Plugin": "",
"In-cluster": "",
"Actions": "Acciones",
"View": "Ver",
"Settings": "Definiciones",
"Delete": "Borrar",
"Delete Cluster": "",
"Are you sure you want to remove the cluster \"{{ clusterName }}\"?": "¿Está seguro de que desea eliminar el cluster \"{{ clusterName }}\"?",
"This action will delete cluster \"{{ clusterName }}\" from {{ source }}.": "",
"Delete from kubeconfig": "",
"Active": "Activo",
"Plugin": "",
"In-cluster": "",
"Home": "Inicio",
"All Clusters": "Todos los Clusters",
"Name": "Nombre",
Expand Down Expand Up @@ -81,6 +82,7 @@
"Cluster Settings ({{ clusterName }})": "Configuración del cluster ({{ clusterName }})",
"Go to cluster": "",
"Remove Cluster": "Eliminar cluster",
"Are you sure you want to remove the cluster \"{{ clusterName }}\"?": "¿Está seguro de que desea eliminar el cluster \"{{ clusterName }}\"?",
"Server": "Servidor",
"light theme": "tema claro",
"dark theme": "tema oscuro",
Expand Down Expand Up @@ -144,6 +146,7 @@
"Last Seen": "Últi. ocurrencia",
"Offline": "Desconectado",
"Lost connection to the cluster.": "",
"I Agree": "",
"No": "No",
"Yes": "",
"Create {{ name }}": "",
Expand Down
Loading

0 comments on commit 12b74de

Please sign in to comment.