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

[ECO][Inventory] Redirect ECS k8s entities to dashboards #197222

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
31f79b3
Redirect ECS k8s entities to dashboards
crespocarlos Oct 22, 2024
e50ed57
Create entity_client functions
crespocarlos Oct 23, 2024
023b531
Create entity_client functions
crespocarlos Oct 23, 2024
f7c2dfc
Fix entityLatest flatten object
crespocarlos Oct 23, 2024
d3bf958
Fix redirection to service overview
crespocarlos Oct 23, 2024
592039b
Fix redirection to service overview
crespocarlos Oct 23, 2024
07a0050
Add tests
crespocarlos Oct 24, 2024
9b19596
Add tests
crespocarlos Oct 24, 2024
584a3b2
Refactoring and tests
crespocarlos Oct 25, 2024
e5929db
Clean up
crespocarlos Oct 25, 2024
6ed10af
[CI] Auto-commit changed files from 'node scripts/yarn_deduplicate'
kibanamachine Oct 25, 2024
43dcb69
fix after rebase
crespocarlos Oct 25, 2024
72a8c0e
Fix build
crespocarlos Oct 28, 2024
750eeee
Merge branch 'main' into 196142-redirect-ecs-k8s-entities
elasticmachine Oct 28, 2024
753d52f
Fix typo in the file name
crespocarlos Oct 30, 2024
76f572a
CR fixes
crespocarlos Oct 30, 2024
fdccc6c
Merge branch 'main' into 196142-redirect-ecs-k8s-entities
elasticmachine Oct 30, 2024
5fc933c
Merge branch 'main' of github.com:elastic/kibana into 196142-redirect…
crespocarlos Oct 30, 2024
7a5b222
Include k8s cluster dashboard redirection
crespocarlos Nov 1, 2024
c1f63c7
Merge branch 'main' into 196142-redirect-ecs-k8s-entities
elasticmachine Nov 1, 2024
3875f9b
Merge branch 'main' into 196142-redirect-ecs-k8s-entities
elasticmachine Nov 4, 2024
64ec351
Clean up
crespocarlos Nov 4, 2024
fb035c0
Merge branch 'main' into 196142-redirect-ecs-k8s-entities
elasticmachine Nov 4, 2024
201816c
Merge branch 'main' into 196142-redirect-ecs-k8s-entities
elasticmachine Nov 4, 2024
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
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,9 @@ export class K8sEntity extends Serializable<EntityFields> {
super({
...fields,
'entity.type': entityTypeWithSchema,
'entity.definitionId': `builtin_${entityTypeWithSchema}`,
'entity.identityFields': identityFields,
'entity.displayName': getDisplayName({ identityFields, fields }),
'entity.definition_id': `builtin_${entityTypeWithSchema}`,
'entity.identity_fields': identityFields,
'entity.display_name': getDisplayName({ identityFields, fields }),
});
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/*
* 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 type { ESQLSearchResponse } from '@kbn/es-types';
import { esqlResultToPlainObjects } from './esql_result_to_plain_objects';

describe('esqlResultToPlainObjects', () => {
it('should return an empty array for an empty result', () => {
const result: ESQLSearchResponse = {
columns: [],
values: [],
};
const output = esqlResultToPlainObjects(result);
expect(output).toEqual([]);
});

it('should return plain objects', () => {
const result: ESQLSearchResponse = {
columns: [{ name: 'name', type: 'keyword' }],
values: [['Foo Bar']],
};
const output = esqlResultToPlainObjects(result);
expect(output).toEqual([{ name: 'Foo Bar' }]);
});

it('should return columns without "text" or "keyword" in their names', () => {
const result: ESQLSearchResponse = {
columns: [
{ name: 'name.text', type: 'text' },
{ name: 'age', type: 'keyword' },
],
values: [
['Foo Bar', 30],
['Foo Qux', 25],
],
};
const output = esqlResultToPlainObjects(result);
expect(output).toEqual([
{ name: 'Foo Bar', age: 30 },
{ name: 'Foo Qux', age: 25 },
]);
});

it('should handle mixed columns correctly', () => {
const result: ESQLSearchResponse = {
columns: [
{ name: 'name', type: 'text' },
{ name: 'name.text', type: 'text' },
{ name: 'age', type: 'keyword' },
],
values: [
['Foo Bar', 'Foo Bar', 30],
['Foo Qux', 'Foo Qux', 25],
],
};
const output = esqlResultToPlainObjects(result);
expect(output).toEqual([
{ name: 'Foo Bar', age: 30 },
{ name: 'Foo Qux', age: 25 },
]);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,17 @@ export function esqlResultToPlainObjects<T extends Record<string, any>>(
return result.values.map((row) => {
return row.reduce<Record<string, unknown>>((acc, value, index) => {
const column = result.columns[index];
acc[column.name] = value;

if (!column) {
return acc;
}

// Removes the type suffix from the column name
const name = column.name.replace(/\.(text|keyword)$/, '');
crespocarlos marked this conversation as resolved.
Show resolved Hide resolved
if (!acc[name]) {
acc[name] = value;
}

return acc;
}, {});
}) as T[];
Expand Down
139 changes: 139 additions & 0 deletions x-pack/plugins/entity_manager/public/lib/entity_client.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
/*
* 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 { EntityClient, EnitityInstance } from './entity_client';
import { coreMock } from '@kbn/core/public/mocks';

const commonEntityFields: EnitityInstance = {
entity: {
last_seen_timestamp: '2023-10-09T00:00:00Z',
id: '1',
display_name: 'entity_name',
definition_id: 'entity_definition_id',
} as EnitityInstance['entity'],
};

describe('EntityClient', () => {
let entityClient: EntityClient;

beforeEach(() => {
entityClient = new EntityClient(coreMock.createStart());
});

describe('asKqlFilter', () => {
it('should return the kql filter', () => {
const entityLatest: EnitityInstance = {
entity: {
...commonEntityFields.entity,
identity_fields: ['service.name', 'service.environment'],
crespocarlos marked this conversation as resolved.
Show resolved Hide resolved
type: 'service',
},
service: {
name: 'my-service',
},
};

const result = entityClient.asKqlFilter(entityLatest);
expect(result).toEqual('service.name: my-service');
});

it('should return the kql filter when indentity_fields is composed by multiple fields', () => {
const entityLatest: EnitityInstance = {
entity: {
...commonEntityFields.entity,
identity_fields: ['service.name', 'service.environment'],
type: 'service',
},
service: {
name: 'my-service',
environment: 'staging',
},
};

const result = entityClient.asKqlFilter(entityLatest);
expect(result).toEqual('(service.name: my-service AND service.environment: staging)');
});

it('should ignore fields that are not present in the entity', () => {
const entityLatest: EnitityInstance = {
entity: {
...commonEntityFields.entity,
identity_fields: ['host.name', 'foo.bar'],
crespocarlos marked this conversation as resolved.
Show resolved Hide resolved
},
host: {
name: 'my-host',
},
};

const result = entityClient.asKqlFilter(entityLatest);
expect(result).toEqual('host.name: my-host');
});
});

describe('getIdentityFieldsValue', () => {
crespocarlos marked this conversation as resolved.
Show resolved Hide resolved
it('should return identity fields values', () => {
const entityLatest: EnitityInstance = {
entity: {
...commonEntityFields.entity,
identity_fields: ['service.name', 'service.environment'],
crespocarlos marked this conversation as resolved.
Show resolved Hide resolved
type: 'service',
},
service: {
name: 'my-service',
},
};

expect(entityClient.getIdentityFieldsValue(entityLatest)).toEqual({
'service.name': 'my-service',
});
});

it('should return identity fields values when indentity_fields is composed by multiple fields', () => {
const entityLatest: EnitityInstance = {
entity: {
...commonEntityFields.entity,
identity_fields: ['service.name', 'service.environment'],
type: 'service',
},
service: {
name: 'my-service',
environment: 'staging',
},
};

expect(entityClient.getIdentityFieldsValue(entityLatest)).toEqual({
'service.name': 'my-service',
'service.environment': 'staging',
});
});

it('should return identity fields when field is in the root', () => {
const entityLatest: EnitityInstance = {
entity: {
...commonEntityFields.entity,
identity_fields: ['name'],
type: 'service',
},
name: 'foo',
};

expect(entityClient.getIdentityFieldsValue(entityLatest)).toEqual({
name: 'foo',
});
});

it('should throw an error when identity fields are missing', () => {
const entityLatest: EnitityInstance = {
...commonEntityFields,
};

expect(() => entityClient.getIdentityFieldsValue(entityLatest)).toThrow(
'Identity fields are missing'
);
});
});
});
40 changes: 40 additions & 0 deletions x-pack/plugins/entity_manager/public/lib/entity_client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,17 @@
* 2.0.
*/

import { z } from '@kbn/zod';
import { CoreSetup, CoreStart } from '@kbn/core/public';
import {
ClientRequestParamsOf,
RouteRepositoryClient,
createRepositoryClient,
isHttpFetchError,
} from '@kbn/server-route-repository-client';
import { type KueryNode, nodeTypes, toKqlExpression } from '@kbn/es-query';
import { entityLatestSchema } from '@kbn/entities-schema';
import { castArray } from 'lodash';
import {
DisableManagedEntityResponse,
EnableManagedEntityResponse,
Expand All @@ -35,6 +39,8 @@ type CreateEntityDefinitionQuery = QueryParamOf<
ClientRequestParamsOf<EntityManagerRouteRepository, 'PUT /internal/entities/managed/enablement'>
>;

export type EnitityInstance = z.infer<typeof entityLatestSchema>;

export class EntityClient {
public readonly repositoryClient: EntityManagerRepositoryClient['fetch'];

Expand Down Expand Up @@ -83,4 +89,38 @@ export class EntityClient {
throw err;
}
}

asKqlFilter(entityLatest: EnitityInstance) {
const identityFieldsValue = this.getIdentityFieldsValue(entityLatest);

const nodes: KueryNode[] = Object.entries(identityFieldsValue).map(([identityField, value]) => {
return nodeTypes.function.buildNode('is', identityField, value);
});

if (nodes.length === 0) return '';

const kqlExpression = nodes.length > 1 ? nodeTypes.function.buildNode('and', nodes) : nodes[0];

return toKqlExpression(kqlExpression);
}

getIdentityFieldsValue(entityLatest: EnitityInstance) {
const { identity_fields: identityFields } = entityLatest.entity;

if (!identityFields) {
throw new Error('Identity fields are missing');
}

return castArray(identityFields).reduce((acc, field) => {
const value = field.split('.').reduce((obj: any, part: string) => {
return obj && typeof obj === 'object' ? (obj as Record<string, any>)[part] : undefined;
}, entityLatest);

if (value) {
acc[field] = value;
}

return acc;
}, {} as Record<string, string>);
}
}

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@
*/

import * as z from '@kbn/zod';
import { EntityDataStreamType, EntityType } from '@kbn/observability-shared-plugin/common';
import { EntityDataStreamType, ENTITY_TYPES } from '@kbn/observability-shared-plugin/common';
import { useFetcher } from '../../../hooks/use_fetcher';

const EntityTypeSchema = z.union([z.literal(EntityType.HOST), z.literal(EntityType.CONTAINER)]);
const EntityTypeSchema = z.union([z.literal(ENTITY_TYPES.HOST), z.literal(ENTITY_TYPES.CONTAINER)]);
const EntityDataStreamSchema = z.union([
z.literal(EntityDataStreamType.METRICS),
z.literal(EntityDataStreamType.LOGS),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ import {
import { FormattedMessage } from '@kbn/i18n-react';
import { getFieldByType } from '@kbn/metrics-data-access-plugin/common';
import { decodeOrThrow } from '@kbn/io-ts-utils';
import { EntityType } from '@kbn/observability-shared-plugin/common';
import useLocalStorage from 'react-use/lib/useLocalStorage';
import { ENTITY_TYPES } from '@kbn/observability-shared-plugin/common';
import { useSourceContext } from '../../../../containers/metrics_source';
import { isPending, useFetcher } from '../../../../hooks/use_fetcher';
import { parseSearchString } from './parse_search_string';
Expand Down Expand Up @@ -58,7 +58,7 @@ export const Processes = () => {
const { request$ } = useRequestObservable();
const { isActiveTab } = useTabSwitcherContext();
const { dataStreams, status: dataStreamsStatus } = useEntitySummary({
entityType: EntityType.HOST,
entityType: ENTITY_TYPES.HOST,
entityId: asset.name,
});
const addMetricsCalloutId: AddMetricsCalloutKey = 'hostProcesses';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { schema } from '@kbn/config-schema';
import { METRICS_APP_ID } from '@kbn/deeplinks-observability/constants';
import { entityCentricExperience } from '@kbn/observability-plugin/common';
import { createObservabilityEsClient } from '@kbn/observability-utils/es/client/create_observability_es_client';
import { ENTITY_TYPES } from '@kbn/observability-shared-plugin/common';
import { getInfraMetricsClient } from '../../lib/helpers/get_infra_metrics_client';
import { InfraBackendLibs } from '../../lib/infra_types';
import { getDataStreamTypes } from './get_data_stream_types';
Expand All @@ -22,7 +23,10 @@ export const initEntitiesConfigurationRoutes = (libs: InfraBackendLibs) => {
path: '/api/infra/entities/{entityType}/{entityId}/summary',
validate: {
params: schema.object({
entityType: schema.oneOf([schema.literal('host'), schema.literal('container')]),
entityType: schema.oneOf([
schema.literal(ENTITY_TYPES.HOST),
schema.literal(ENTITY_TYPES.CONTAINER),
]),
entityId: schema.string(),
}),
},
Expand Down
Loading