Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ISPN-16332 Add and remove aliases #489

Merged
merged 1 commit into from
Sep 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion src/app/CacheManagers/CacheTableDisplay.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,11 @@ import { onSearch } from '@app/utils/searchFilter';
import { DeleteCache } from '@app/Caches/DeleteCache';
import { IgnoreCache } from '@app/Caches/IgnoreCache';
import { SetAvailableCache } from '@app/Caches/SetAvailableCache';
import { UpdateAliasCache } from '@app/Caches/UpdateAliasCache';

interface CacheAction {
cacheName: string;
action: '' | 'ignore' | 'undo' | 'delete' | 'available';
action: '' | 'ignore' | 'undo' | 'delete' | 'available' | 'aliases';
}

const CacheTableDisplay = (props: { setCachesCount: (count: number) => void; isVisible: boolean }) => {
Expand Down Expand Up @@ -191,6 +192,13 @@ const CacheTableDisplay = (props: { setCachesCount: (count: number) => void; isV
});
};

const openUpdateAliasesCacheModal = (cacheName: string) => {
setCacheAction({
cacheName: cacheName,
action: 'aliases'
});
};

const openAvailableCacheModal = (cacheName: string) => {
setCacheAction({
cacheName: cacheName,
Expand Down Expand Up @@ -405,6 +413,12 @@ const CacheTableDisplay = (props: { setCachesCount: (count: number) => void; isV
let actions: IAction[] = [];

if (isAdmin) {
actions.push({
'aria-label': 'updateAliasesCacheAction',
title: t('cache-managers.update-aliases'),
onClick: () => openUpdateAliasesCacheModal(cacheName)
});

actions.push({
'aria-label': 'ignoreCacheAction',
title: t('cache-managers.ignore'),
Expand Down Expand Up @@ -834,6 +848,11 @@ const CacheTableDisplay = (props: { setCachesCount: (count: number) => void; isV
isModalOpen={cacheAction.action == 'available'}
closeModal={() => setCacheAction({ cacheName: '', action: '' })}
/>
<UpdateAliasCache
cacheName={cacheAction.cacheName}
isModalOpen={cacheAction.action == 'aliases'}
closeModal={() => setCacheAction({ cacheName: '', action: '' })}
/>
</CardBody>
</Card>
)}
Expand Down
106 changes: 106 additions & 0 deletions src/app/Caches/UpdateAliasCache.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import React, { useEffect } from 'react';
import { Alert, Button, Form, FormGroup, Modal, Spinner, Text, TextContent } from '@patternfly/react-core';
import { useTranslation } from 'react-i18next';
import { useCacheAliases } from '@app/services/configHook';
import { SelectMultiWithChips } from '@app/Common/SelectMultiWithChips';

/**
* Update Alias Cache modal
*/
const UpdateAliasCache = (props: { cacheName: string; isModalOpen: boolean; closeModal: (boolean) => void }) => {
const { loading, setLoading, error, aliases, setAliases, update } = useCacheAliases(props.cacheName);

const { t } = useTranslation();

useEffect(() => {
setLoading(props.isModalOpen);
}, [props.isModalOpen]);

const clearUpdateAliasesModal = (updateDone: boolean) => {
props.closeModal(updateDone);
};

const helperAddAlias = (selection) => {
if (!aliases.some((alias) => alias === selection)) {
setAliases([...aliases, selection]);
} else {
setAliases(aliases.filter((alias) => alias !== selection));
}
};

const displayError = () => {
if (error.length == 0) {
return <></>;
}

return <Alert variant="danger" isInline title={error} />;
};
const buildContent = () => {
if (loading) {
return <Spinner size={'md'} />;
}

return (
<Form
onSubmit={(e) => {
e.preventDefault();
}}
>
{displayError()}
<TextContent>
<Text>{t('caches.aliases.body1', { cacheName: props.cacheName })}</Text>
<Text>{t('caches.aliases.body2', { cacheName: props.cacheName })}</Text>
</TextContent>

<FormGroup isInline fieldId="field-aliases" label={t('caches.aliases.values')}>
<SelectMultiWithChips
id="aliasesSelector"
placeholder={t('caches.aliases.values')}
options={[]}
onSelect={helperAddAlias}
onClear={() => setAliases([])}
create={true}
selection={aliases}
/>
</FormGroup>
</Form>
);
};

return (
<Modal
data-cy={`updateAliasCacheModal`}
id="updateAliasCacheModal"
titleIconVariant={'warning'}
width={'70%'}
isOpen={props.isModalOpen}
title={t('caches.aliases.title', { cacheName: props.cacheName })}
onClose={() => clearUpdateAliasesModal(false)}
aria-label={'Update aliases modal'}
actions={[
<Button
aria-label={'Update'}
variant={'danger'}
key={'update-aliases-modal-button'}
onClick={() => update(props.cacheName)}
data-cy={'updateAliasesButton'}
>
{t('common.actions.update')}
</Button>,
<Button
aria-label="Close"
key="close"
variant="link"
onClick={() => clearUpdateAliasesModal(false)}
data-cy="closeAction"
>
{t('common.actions.close')}
</Button>
]}
>
{buildContent()}
</Modal>
);
};

export { UpdateAliasCache };
5 changes: 4 additions & 1 deletion src/app/Common/SelectMultiWithChips.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,10 @@ const SelectMultiWithChips = (props: {
);

// When no options are found after filtering, display creation option
if (!newSelectOptions.length) {
if (!newSelectOptions.length && props.create) {
newSelectOptions = [{ isDisabled: false, children: `Create "${inputValue}"`, value: 'create' }];
} else if (!newSelectOptions.length) {
newSelectOptions = [{ isDisabled: false, children: 'no results', value: 'no results' }];
}

// Open the menu when the input value changes and the new value is not empty
Expand Down Expand Up @@ -104,6 +106,7 @@ const SelectMultiWithChips = (props: {
setIsOpen((prevIsOpen) => !prevIsOpen);
} else if (isOpen && focusedItem.value !== 'no results') {
onSelect(focusedItem.value as string);
setInputValue('');
}
break;
case 'Tab':
Expand Down
10 changes: 9 additions & 1 deletion src/app/assets/languages/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@
"delete": "Delete",
"remove": "Remove",
"clear": "Clear",
"update": "Update"
"update": "Update",
"close": "Close"
},
"loading-empty-message": "No result found.",
"loading-error-message": "There was an error retrieving data. Check your connection and try again.",
Expand Down Expand Up @@ -99,6 +100,7 @@
"cache-health": "Health",
"cache-features": "Features",
"cache-status": "",
"update-aliases": "Edit aliases",
"ignore": "Hide",
"undo-ignore": "Show",
"ignored-status": "Hidden",
Expand Down Expand Up @@ -214,6 +216,12 @@
"cache-setup-title": "Select a way to configure your cache"
}
},
"aliases": {
"title": "Update aliases of cache \"{{cacheName}}\"?",
"body1": "Add cache aliases to access \"{{cacheName}}\" using different names.",
"body2": "If you remove existing cache aliases, the old alias will no longer access the \"{{cacheName}}\" cache. You can always add aliases after.",
"values": "Aliases"
},
"delete": {
"title": "Permanently delete cache?",
"body": "and all of its data will be deleted.",
Expand Down
57 changes: 56 additions & 1 deletion src/app/services/configHook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ export function useFetchTracingConfig(cacheName: string) {
const parseCategories = (value: string): string[] => {
try {
const parsed: string = JSON.parse(value);
if (parsed === '[]') {
return [];
}
return parsed.replace('[', '').replace(']', '').split(', ');
} catch {
return [];
Expand All @@ -33,7 +36,7 @@ export function useFetchTracingConfig(cacheName: string) {
.then((actionResponse) => {
if (tracingCategories.length > 0) {
ConsoleServices.caches()
.setConfigAttribute(cacheName, 'tracing.categories', tracingCategories.toString())
.setConfigAttribute(cacheName, 'tracing.categories', tracingCategories.join(' '))
.then((actionResponse) => {
addAlert(actionResponse);
});
Expand Down Expand Up @@ -81,6 +84,58 @@ export function useFetchTracingConfig(cacheName: string) {
return { loading, error, tracingEnabled, tracingCategories, setTracingEnabled, setTracingCategories, update };
}

export function useCacheAliases(cacheName: string) {
const { addAlert } = useApiAlert();
const [aliases, setAliases] = useState<string[]>([]);
const [error, setError] = useState('');
const [loading, setLoading] = useState(false);

const update = (cacheName: string) => {
const newAliases = aliases.join(' ');
ConsoleServices.caches()
.setConfigAttribute(cacheName, 'aliases', newAliases)
.then((actionResponse) => {
if (actionResponse.success) {
addAlert(actionResponse);
} else {
setError(actionResponse.message);
}
});
};

const parseAliases = (value: string): string[] => {
try {
const parsed: string = JSON.parse(value);
if (parsed === '[]') {
return [];
}
return parsed.replace('[', '').replace(']', '').split(', ');
} catch {
return [];
}
};

useEffect(() => {
if (loading) {
setError('');
ConsoleServices.caches()
.getConfigAttribute(cacheName, 'aliases')
.then((r) => {
if (r.isRight()) {
setAliases(parseAliases(r.value));
} else {
setError(r.value.message);
}
})
.finally(() => {
setLoading(false);
});
}
}, [loading]);

return { loading, setLoading, error, aliases, setAliases, update };
}

export function useFetchConfigurationYAML(cacheName: string) {
const [configuration, setConfiguration] = useState('');
const [error, setError] = useState('');
Expand Down
8 changes: 5 additions & 3 deletions src/services/cacheService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -505,14 +505,16 @@ export class CacheService {
* @param configAttributeValue
*/
public async setConfigAttribute(cacheName: string, configAttribute: string, value: string): Promise<ActionResponse> {
const url =
let url =
this.endpoint +
'/caches/' +
encodeURIComponent(cacheName) +
'?action=set-mutable-attribute&attribute-name=' +
configAttribute +
'&attribute-value=' +
encodeURIComponent(value);
'&attribute-value=';
if (value.length > 0) {
url = url + encodeURIComponent(value);
}
return this.fetchCaller.post({
url: url,
successMessage: `Cache ${cacheName} successfully updated.`,
Expand Down
Loading