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

CNV-32097: Add ip search capabilities #1585

Merged
merged 1 commit into from
Oct 18, 2023
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
2 changes: 2 additions & 0 deletions locales/en/plugin__kubevirt-plugin.json
Original file line number Diff line number Diff line change
Expand Up @@ -548,6 +548,7 @@
"Inventory": "Inventory",
"IOPS total: {{input}}": "IOPS total: {{input}}",
"IP address": "IP address",
"IP Address": "IP Address",
"IP addresses": "IP addresses",
"It may take several minutes until the clone is done and the VirtualMachine is ready.": "It may take several minutes until the clone is done and the VirtualMachine is ready.",
"It seems that your browser does not trust the certificate of the upload proxy. {uploadProxyURL && (\n <>\n Please{' '}\n <a href={`https://${uploadProxyURL}`} rel=\"noopener noreferrer\" target=\"_blank\">\n approve this certificate\n </a>{' '}\n and try again\n </>\n )}": "It seems that your browser does not trust the certificate of the upload proxy. {uploadProxyURL && (\n <>\n Please{' '}\n <a href={`https://${uploadProxyURL}`} rel=\"noopener noreferrer\" target=\"_blank\">\n approve this certificate\n </a>{' '}\n and try again\n </>\n )}",
Expand Down Expand Up @@ -911,6 +912,7 @@
"Scripts": "Scripts",
"SCSI": "SCSI",
"Search": "Search",
"Search by {{filterName}}": "Search by {{filterName}}",
"Search by labels...": "Search by labels...",
"Search by name...": "Search by name...",
"Search by reason...": "Search by reason...",
Expand Down
52 changes: 45 additions & 7 deletions src/utils/components/ListPageFilter/ListPageFilter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import React, { FC, useMemo, useState } from 'react';

import useDeepCompareMemoize from '@kubevirt-utils/hooks/useDeepCompareMemoize/useDeepCompareMemoize';
import { useKubevirtTranslation } from '@kubevirt-utils/hooks/useKubevirtTranslation';
import { isEmpty } from '@kubevirt-utils/utils/utils';
import {
ColumnLayout,
FilterValue,
Expand Down Expand Up @@ -63,8 +64,11 @@ const ListPageFilter: FC<ListPageFilterProps> = ({

const [isDropdownOpen, setIsDropdownOpen] = useState<boolean>(false);

const toolbarFilters = rowFilters.filter((filter) => !isEmpty(filter.items));
const searchFilters = rowFilters.filter((filter) => isEmpty(filter.items));

// Generate rowFilter items and counts. Memoize to minimize re-renders.
const generatedRowFilters = useDeepCompareMemoize(generateRowFilters(rowFilters ?? [], data));
const generatedRowFilters = useDeepCompareMemoize(generateRowFilters(toolbarFilters ?? [], data));

// Reduce generatedRowFilters once and memoize
const [filters, filtersNameMap, filterKeys] = useMemo<[Filter, FilterKeys, FilterKeys, string[]]>(
Expand All @@ -77,11 +81,16 @@ const ListPageFilter: FC<ListPageFilterProps> = ({
filters,
});

const textFilters = useSearchFiltersParameters();
const textFilters = useSearchFiltersParameters(searchFilters);

const alreadySearchedParam = searchFilters?.find(
(searchFilter) => textFilters[searchFilter.type],
)?.type;

const [searchType, setSearchType] = useState<keyof typeof STATIC_SEARCH_FILTERS>(
STATIC_SEARCH_FILTERS.name,
const [searchType, setSearchType] = useState<string>(
alreadySearchedParam || STATIC_SEARCH_FILTERS.name,
);

const [searchInputText, setSearchInputText] = useState<string>(
getInitialSearchText(textFilters, searchType),
);
Expand All @@ -105,6 +114,8 @@ const ListPageFilter: FC<ListPageFilterProps> = ({

if (!loaded) return null;

const selectedSearchFilter = searchFilters?.find((f) => f.type === searchType);

return (
<Toolbar
className="co-toolbar-no-padding pf-m-toggle-group-container"
Expand All @@ -119,7 +130,7 @@ const ListPageFilter: FC<ListPageFilterProps> = ({
filters={filters}
filtersNameMap={filtersNameMap}
generatedRowFilters={generatedRowFilters}
rowFilters={rowFilters}
rowFilters={toolbarFilters}
selectedRowFilters={selectedRowFilters}
updateRowFilterSelected={updateRowFilterSelected}
/>
Expand All @@ -135,6 +146,20 @@ const ListPageFilter: FC<ListPageFilterProps> = ({
categoryName={STATIC_SEARCH_FILTERS_LABELS.labels}
chips={textFilters.labels ?? []}
>
{searchFilters.map((filter) => (
<ToolbarFilter
deleteChip={() => {
applyTextFilters(filter.type);
searchType === filter.type && setSearchInputText('');
}}
categoryName={filter.type}
chips={textFilters[filter.type] ? [textFilters[filter.type]] : []}
key={filter.type}
>
<></>
upalatucci marked this conversation as resolved.
Show resolved Hide resolved
</ToolbarFilter>
))}

<ToolbarFilter
deleteChip={() => {
applyTextFilters('name');
Expand All @@ -154,7 +179,7 @@ const ListPageFilter: FC<ListPageFilterProps> = ({
isOpen={isDropdownOpen}
onSelect={onSelect}
onToggle={setIsDropdownOpen}
selections={searchType}
selections={selectedSearchFilter?.filterGroupName || searchType}
variant={SelectVariant.single}
>
<SelectOption value={STATIC_SEARCH_FILTERS.name}>
Expand All @@ -164,6 +189,14 @@ const ListPageFilter: FC<ListPageFilterProps> = ({
<SelectOption value={STATIC_SEARCH_FILTERS.labels}>
{STATIC_SEARCH_FILTERS_LABELS.labels}
</SelectOption>

<>
{searchFilters.map((filter) => (
<SelectOption key={filter.type} value={filter.type}>
{filter.filterGroupName}
</SelectOption>
))}
</>
</Select>

{searchType === STATIC_SEARCH_FILTERS.labels ? (
Expand All @@ -188,8 +221,13 @@ const ListPageFilter: FC<ListPageFilterProps> = ({
setSearchInputText(newSearchInput);
applyTextFiltersWithDebounce(searchType, newSearchInput);
}}
placeholder={
STATIC_SEARCH_FILTERS_PLACEHOLDERS[searchType] ||
t('Search by {{filterName}}', {
filterName: selectedSearchFilter?.filterGroupName,
})
}
data-test={`${searchType}-filter-input`}
placeholder={STATIC_SEARCH_FILTERS_PLACEHOLDERS.name}
value={searchInputText}
/>
)}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { useMemo } from 'react';
import { useLocation } from 'react-router-dom';

export const useSearchFiltersParameters = () => {
import { RowFilter } from '@openshift-console/dynamic-plugin-sdk';

export const useSearchFiltersParameters = (searchFilters: RowFilter[]) => {
const location = useLocation();
const queryParams = useMemo(() => new URLSearchParams(location.search), [location]);

Expand All @@ -11,5 +13,20 @@ export const useSearchFiltersParameters = () => {
[queryParams],
);

return { labels: labelTextFilters, name: nameTextFilter };
const searchTextFilters = useMemo(() => {
const filters = searchFilters?.reduce((acc, filter) => {
const { type } = filter;
const filterValue = queryParams.get(type);

if (filterValue) acc[type] = filterValue;
return acc;
}, {} as { [key in string]: string });

return filters;
}, [queryParams, searchFilters]);

return useMemo(
() => ({ labels: labelTextFilters, name: nameTextFilter, ...searchTextFilters }),
[labelTextFilters, nameTextFilter, searchTextFilters],
);
};
23 changes: 23 additions & 0 deletions src/views/virtualmachines/utils/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,26 @@ export const isLiveMigratable = (vm: V1VirtualMachine, isSingleNodeCluster: bool

export const isRunning = (vm: V1VirtualMachine): boolean =>
vm?.status?.printableStatus === printableVMStatus.Running;

const decimalToBinary = (decimalNumber: number) => (decimalNumber >>> 0).toString(2);

const ipStringToBinary = (ip: string) =>
ip
.split('.')
.map((classes) => decimalToBinary(parseInt(classes)).padStart(8, '0'))
.join('');

export const compareCIDR = (ipSearch: string, ip: string) => {
const [baseIp, range] = ipSearch.split('/');

const baseIpBinary = ipStringToBinary(baseIp);

const ipBinary = ipStringToBinary(ip);

const rangeNumber = parseInt(range);

const baseIpBinarySlice = baseIpBinary.slice(0, rangeNumber);
const ipBinarySlice = ipBinary.slice(0, rangeNumber);

return baseIpBinarySlice === ipBinarySlice;
};
27 changes: 26 additions & 1 deletion src/views/virtualmachines/utils/virtualMachineRowFilter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,10 @@ import {
getOperatingSystem,
getOperatingSystemName,
} from '@kubevirt-utils/resources/vm/utils/operation-system/operationSystem';
import { getVMIIPAddresses } from '@kubevirt-utils/resources/vmi';
import { RowFilter } from '@openshift-console/dynamic-plugin-sdk';

import { isLiveMigratable } from './utils';
import { compareCIDR, isLiveMigratable } from './utils';
import { isErrorPrintableStatus, printableVMStatus } from './virtualMachineStatuses';

type VmiMapper = {
Expand Down Expand Up @@ -192,6 +193,28 @@ const useInstanceTypesFilter = (vms: V1VirtualMachine[]): RowFilter => {
};
};

const useIPSearchFilter = (vmiMapper: VmiMapper): RowFilter => ({
filter: (input, obj) => {
const search = input.selected?.[0];

if (!search) return true;

const vmi = vmiMapper.mapper?.[obj?.metadata?.namespace]?.[obj?.metadata?.name];

const ipAddresses = getVMIIPAddresses(vmi);

if (search.includes('/')) {
return ipAddresses.some((ipAddress) => compareCIDR(search, ipAddress));
}

return ipAddresses.some((ipAddress) => ipAddress?.startsWith(search));
},
filterGroupName: t('IP Address'),
isMatch: () => true,
upalatucci marked this conversation as resolved.
Show resolved Hide resolved
items: [],
type: 'ip',
});

export const useVMListFilters = (
vmis: V1VirtualMachineInstance[],
vms: V1VirtualMachine[],
Expand Down Expand Up @@ -239,6 +262,7 @@ export const useVMListFilters = (
const nodesFilter = useNodesFilter(vmiMapper);
const liveMigratableFilter = useLiveMigratableFilter();
const instanceTypesFilter = useInstanceTypesFilter(vms);
const searchByIP = useIPSearchFilter(vmiMapper);

return {
filters: [
Expand All @@ -248,6 +272,7 @@ export const useVMListFilters = (
liveMigratableFilter,
nodesFilter,
instanceTypesFilter,
searchByIP,
],
vmiMapper,
vmimMapper,
Expand Down
Loading