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

[WIP][Inventory] Change discover link to use entity definition #201433

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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 x-pack/plugins/entity_manager/public/lib/entity_client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,9 @@ import {
isHttpFetchError,
} from '@kbn/server-route-repository-client';
import { type KueryNode, nodeTypes, toKqlExpression } from '@kbn/es-query';
import type { EntityInstance, EntityMetadata } from '@kbn/entities-schema';
import type { EntityDefinition, EntityInstance, EntityMetadata } from '@kbn/entities-schema';
import { castArray } from 'lodash';
import type { EntityDefinitionWithState } from '../../server/lib/entities/types';
import {
DisableManagedEntityResponse,
EnableManagedEntityResponse,
Expand Down Expand Up @@ -87,6 +88,24 @@ export class EntityClient {
}
}

async getEntityDefinition(
id: string
): Promise<{ definitions: EntityDefinition[] | EntityDefinitionWithState[] }> {
try {
return await this.repositoryClient('GET /internal/entities/definition/{id}', {
params: {
path: { id },
query: { page: 1, perPage: 1 },
},
});
} catch (err) {
if (isHttpFetchError(err) && err.body?.statusCode === 403) {
throw new EntityManagerUnauthorizedError(err.body.message);
}
throw err;
}
}

asKqlFilter(
entityInstance: {
entity: Pick<EntityInstance['entity'], 'identity_fields'>;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,14 @@ import {
import { i18n } from '@kbn/i18n';
import { FormattedDate, FormattedMessage, FormattedTime } from '@kbn/i18n-react';
import { last } from 'lodash';
import React, { useCallback, useMemo } from 'react';
import React, { useCallback, useMemo, useState } from 'react';
import { ENTITY_TYPE } from '@kbn/observability-shared-plugin/common';
import { EntityColumnIds, InventoryEntity } from '../../../common/entities';
import { BadgeFilterWithPopover } from '../badge_filter_with_popover';
import { getColumns } from './grid_columns';
import { AlertsBadge } from '../alerts_badge/alerts_badge';
import { EntityName } from './entity_name';
import { EntityActions } from '../entity_actions';
import { useDiscoverRedirect } from '../../hooks/use_discover_redirect';

interface Props {
loading: boolean;
Expand All @@ -45,7 +44,7 @@ export function EntitiesGrid({
onChangePage,
onChangeSort,
}: Props) {
const { getDiscoverRedirectUrl } = useDiscoverRedirect();
const [showActions, setShowActions] = useState<boolean>(true);

const onSort: EuiDataGridSorting['onSort'] = useCallback(
(newSortingColumns) => {
Expand All @@ -62,8 +61,6 @@ export function EntitiesGrid({
[entities]
);

const showActions = useMemo(() => !!getDiscoverRedirectUrl(), [getDiscoverRedirectUrl]);

const columnVisibility = useMemo(
() => ({
visibleColumns: getColumns({ showAlertsColumn, showActions }).map(({ id }) => id),
Expand All @@ -81,7 +78,6 @@ export function EntitiesGrid({

const columnEntityTableId = columnId as EntityColumnIds;
const entityType = entity.entityType;
const discoverUrl = getDiscoverRedirectUrl(entity);

switch (columnEntityTableId) {
case 'alertsCount':
Expand Down Expand Up @@ -119,19 +115,12 @@ export function EntitiesGrid({
case 'entityDisplayName':
return <EntityName entity={entity} />;
case 'actions':
return (
discoverUrl && (
<EntityActions
discoverUrl={discoverUrl}
entityIdentifyingValue={entity.entityDisplayName}
/>
)
);
return <EntityActions entity={entity} setShowActions={setShowActions} />;
default:
return null;
}
},
[entities, getDiscoverRedirectUrl]
[entities]
);

if (loading) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,24 +7,36 @@

import { EuiButtonIcon, EuiContextMenuItem, EuiContextMenuPanel, EuiPopover } from '@elastic/eui';
import { i18n } from '@kbn/i18n';
import React from 'react';
import React, { type SetStateAction } from 'react';
import { useBoolean } from '@kbn/react-hooks';
import type { Dispatch } from '@kbn/kibana-utils-plugin/common';
import type { InventoryEntity } from '../../../common/entities';
import { useDiscoverRedirect } from '../../hooks/use_discover_redirect';

interface Props {
discoverUrl: string;
entityIdentifyingValue?: string;
entity: InventoryEntity;
setShowActions: Dispatch<SetStateAction<boolean>>;
}

export const EntityActions = ({ discoverUrl, entityIdentifyingValue }: Props) => {
export const EntityActions = ({ entity, setShowActions }: Props) => {
const [isPopoverOpen, { toggle: togglePopover, off: closePopover }] = useBoolean(false);
const actionButtonTestSubject = entityIdentifyingValue
? `inventoryEntityActionsButton-${entityIdentifyingValue}`
const actionButtonTestSubject = entity.identifyingValue
? `inventoryEntityActionsButton-${entity.identifyingValue}`
: 'inventoryEntityActionsButton';

const { getDiscoverEntitiesRedirectUrl } = useDiscoverRedirect(entity);

const discoverUrl = getDiscoverEntitiesRedirectUrl();

if (!discoverUrl) {
setShowActions(false);
return null;
}

const actions = [
<EuiContextMenuItem
data-test-subj="inventoryEntityActionOpenInDiscover"
key={`openInDiscover-${entityIdentifyingValue}`}
key={`openInDiscover-${entity.identifyingValue}`}
color="text"
icon="discoverApp"
href={discoverUrl}
Expand All @@ -36,27 +48,25 @@ export const EntityActions = ({ discoverUrl, entityIdentifyingValue }: Props) =>
];

return (
<>
<EuiPopover
isOpen={isPopoverOpen}
panelPaddingSize="none"
anchorPosition="upCenter"
button={
<EuiButtonIcon
data-test-subj={actionButtonTestSubject}
aria-label={i18n.translate(
'xpack.inventory.entityActions.euiButtonIcon.showActionsLabel',
{ defaultMessage: 'Show actions' }
)}
iconType="boxesHorizontal"
color="text"
onClick={togglePopover}
/>
}
closePopover={closePopover}
>
<EuiContextMenuPanel items={actions} size="s" />
</EuiPopover>
</>
<EuiPopover
isOpen={isPopoverOpen}
panelPaddingSize="none"
anchorPosition="upCenter"
button={
<EuiButtonIcon
data-test-subj={actionButtonTestSubject}
aria-label={i18n.translate(
'xpack.inventory.entityActions.euiButtonIcon.showActionsLabel',
{ defaultMessage: 'Show actions' }
)}
iconType="boxesHorizontal"
color="text"
onClick={togglePopover}
/>
}
closePopover={closePopover}
>
<EuiContextMenuPanel items={actions} size="s" />
</EuiPopover>
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
import React, { createContext, useContext, type ReactChild } from 'react';
import { Subject } from 'rxjs';
import { DataView } from '@kbn/data-views-plugin/common';
import { useAdHocInventoryDataView } from '../../hooks/use_adhoc_inventory_data_view';
import { ENTITIES_LATEST_ALIAS } from '../../../common/entities';
import { useAdHocDataView } from '../../hooks/use_adhoc_data_view';

interface InventorySearchBarContextType {
searchBarContentSubject$: Subject<{
Expand All @@ -24,7 +25,7 @@ const InventorySearchBarContext = createContext<InventorySearchBarContextType>({
});

export function InventorySearchBarContextProvider({ children }: { children: ReactChild }) {
const { dataView } = useAdHocInventoryDataView();
const { dataView } = useAdHocDataView(ENTITIES_LATEST_ALIAS);
return (
<InventorySearchBarContext.Provider
value={{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,8 @@ import { DataView } from '@kbn/data-views-plugin/common';
import { i18n } from '@kbn/i18n';
import { useEffect, useState } from 'react';
import { useKibana } from './use_kibana';
import { ENTITIES_LATEST_ALIAS } from '../../common/entities';

export function useAdHocInventoryDataView() {
export function useAdHocDataView(title: string) {
const {
services: { dataViews, notifications },
} = useKibana();
Expand All @@ -21,7 +20,7 @@ export function useAdHocInventoryDataView() {
async function fetchDataView() {
try {
const displayError = false;
return await dataViews.create({ title: ENTITIES_LATEST_ALIAS }, undefined, displayError);
return await dataViews.create({ title }, undefined, displayError);
} catch (e) {
const noDataScreen = e.message.includes('No matching indices found');
if (noDataScreen) {
Expand All @@ -40,7 +39,7 @@ export function useAdHocInventoryDataView() {
}

fetchDataView().then(setDataView);
}, [dataViews, notifications.toasts]);
}, [dataViews, title, notifications.toasts]);

return { dataView };
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,74 +4,66 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
import {
ENTITY_DEFINITION_ID,
ENTITY_DISPLAY_NAME,
ENTITY_LAST_SEEN,
ENTITY_TYPE,
} from '@kbn/observability-shared-plugin/common';
import { useCallback } from 'react';
import { useCallback, useMemo } from 'react';
import type { InventoryEntity } from '../../common/entities';
import { useKibana } from './use_kibana';
import { useUnifiedSearchContext } from './use_unified_search_context';
import { useEntityDefinition } from './use_entity_definition';
import { useAdHocDataView } from './use_adhoc_data_view';

const ACTIVE_COLUMNS = [ENTITY_DISPLAY_NAME, ENTITY_TYPE, ENTITY_LAST_SEEN];

export const useDiscoverRedirect = () => {
export const useDiscoverRedirect = (entity: InventoryEntity) => {
const {
services: { share, application, entityManager },
} = useKibana();
const { entityDefinitions } = useEntityDefinition(entity.entityDefinitionId);

const title = useMemo(
() =>
entityDefinitions && entityDefinitions?.length > 0
? entityDefinitions[0]?.indexPatterns?.join(',')
: '',
[entityDefinitions]
);

const { dataView } = useAdHocDataView(title);

const {
dataView,
searchState: { query, filters, panelFilters },
} = useUnifiedSearchContext();

const discoverLocator = share.url.locators.get('DISCOVER_APP_LOCATOR');

const getDiscoverEntitiesRedirectUrl = useCallback(
(entity?: InventoryEntity) => {
const entityKqlFilter = entity
? entityManager.entityClient.asKqlFilter({
entity: {
identity_fields: entity.entityIdentityFields,
},
...entity,
})
: '';
const getDiscoverEntitiesRedirectUrl = useCallback(() => {
const entityKqlFilter = entity
? entityManager.entityClient.asKqlFilter({
entity: {
identity_fields: entity.entityIdentityFields,
},
...entity,
})
: '';

const kueryWithEntityDefinitionFilters = [
query.query,
entityKqlFilter,
`${ENTITY_DEFINITION_ID} : builtin*`,
]
.filter(Boolean)
.join(' AND ');
const kueryWithEntityDefinitionFilters = [query.query, entityKqlFilter]
.filter(Boolean)
.join(' AND ');

return application.capabilities.discover?.show
? discoverLocator?.getRedirectUrl({
indexPatternId: dataView?.id ?? '',
columns: ACTIVE_COLUMNS,
query: { query: kueryWithEntityDefinitionFilters, language: 'kuery' },
filters: [...filters, ...panelFilters],
})
: undefined;
},
[
application.capabilities.discover?.show,
dataView?.id,
discoverLocator,
entityManager.entityClient,
filters,
panelFilters,
query.query,
]
);

const getDiscoverRedirectUrl = useCallback(
(entity?: InventoryEntity) => getDiscoverEntitiesRedirectUrl(entity),
[getDiscoverEntitiesRedirectUrl]
);
return application.capabilities.discover?.show
? discoverLocator?.getRedirectUrl({
indexPatternId: dataView?.id ?? '',
query: { query: kueryWithEntityDefinitionFilters, language: 'kuery' },
filters: [...filters, ...panelFilters],
})
: undefined;
}, [
application.capabilities.discover?.show,
dataView?.id,
discoverLocator,
entity,
entityManager.entityClient,
filters,
panelFilters,
query.query,
]);

return { getDiscoverRedirectUrl };
return { getDiscoverEntitiesRedirectUrl };
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { useAbortableAsync } from '@kbn/observability-utils-browser/hooks/use_abortable_async';
import { useKibana } from './use_kibana';

export const useEntityDefinition = (id: string) => {
const {
services: { entityManager },
} = useKibana();

const { value, loading, refresh } = useAbortableAsync(
({ signal }) => {
return entityManager.entityClient.getEntityDefinition(id);
},
[entityManager.entityClient, id]
);

return {
entityDefinitions: value?.definitions,
isEnablementLoading: loading,
refresh,
};
};
Loading