Skip to content

Commit

Permalink
[8.x] [ECO][Inventory] Redirect ECS k8s entities to dashboards (#197222
Browse files Browse the repository at this point in the history
…) (#198815)

# Backport

This will backport the following commits from `main` to `8.x`:
- [[ECO][Inventory] Redirect ECS k8s entities to dashboards
(#197222)](#197222)

<!--- Backport version: 9.4.3 -->

### Questions ?
Please refer to the [Backport tool
documentation](https://github.com/sqren/backport)

<!--BACKPORT [{"author":{"name":"Carlos
Crespo","email":"[email protected]"},"sourceCommit":{"committedDate":"2024-11-04T16:01:05Z","message":"[ECO][Inventory]
Redirect ECS k8s entities to dashboards (#197222)\n\ncloses
[#196142](https://github.com/elastic/kibana/issues/196142)\r\n\r\n##
Summary\r\n\r\nLinks kubernetes ECS entities to their corresponding
dashboards\r\n\r\n> [!IMPORTANT]\r\n> ECS `replicaset` doesn't have a
dedicated dashboard. `container` will\r\nbe handled in a separate
ticket\r\n> Semconv won't link to any dashboard/page\r\n\r\n<img
width=\"800\"
alt=\"image\"\r\nsrc=\"https://github.com/user-attachments/assets/711dbd28-f0ef-4af0-a658-afe7f1595697\">\r\n\r\n\r\n![redirect](https://github.com/user-attachments/assets/77d5d2e1-7ec4-40cd-b7d8-419e07e6b760)\r\n\r\n\r\n###
How to test\r\n- While #196916 is
not merged,\r\nchange `ENTITIES_LATEST_ALIAS` constant to
`'.entities.v1.latest*'`\r\n- Start a local kibana and es instances
\r\n- Run ` node scripts/synthtrace k8s_entities.ts --live --clean
`\r\n- Run `PUT kbn:/internal/entities/managed/enablement` on the
devtools\r\n- Install the kubernetes integration package to have the
dashboards\r\ninstalled.\r\n- Navigate to `Inventory` and click through
the k8s entities\r\n\r\n---------\r\n\r\nCo-authored-by: kibanamachine
<[email protected]>\r\nCo-authored-by:
Elastic Machine
<[email protected]>","sha":"8145cb7c6f483c3a8aa561b492fa098e3ce52027","branchLabelMapping":{"^v9.0.0$":"main","^v8.17.0$":"8.x","^v(\\d+).(\\d+).\\d+$":"$1.$2"}},"sourcePullRequest":{"labels":["release_note:skip","v9.0.0","backport:prev-minor","ci:project-deploy-observability","Team:obs-ux-infra_services"],"title":"[ECO][Inventory]
Redirect ECS k8s entities to
dashboards","number":197222,"url":"https://github.com/elastic/kibana/pull/197222","mergeCommit":{"message":"[ECO][Inventory]
Redirect ECS k8s entities to dashboards (#197222)\n\ncloses
[#196142](https://github.com/elastic/kibana/issues/196142)\r\n\r\n##
Summary\r\n\r\nLinks kubernetes ECS entities to their corresponding
dashboards\r\n\r\n> [!IMPORTANT]\r\n> ECS `replicaset` doesn't have a
dedicated dashboard. `container` will\r\nbe handled in a separate
ticket\r\n> Semconv won't link to any dashboard/page\r\n\r\n<img
width=\"800\"
alt=\"image\"\r\nsrc=\"https://github.com/user-attachments/assets/711dbd28-f0ef-4af0-a658-afe7f1595697\">\r\n\r\n\r\n![redirect](https://github.com/user-attachments/assets/77d5d2e1-7ec4-40cd-b7d8-419e07e6b760)\r\n\r\n\r\n###
How to test\r\n- While #196916 is
not merged,\r\nchange `ENTITIES_LATEST_ALIAS` constant to
`'.entities.v1.latest*'`\r\n- Start a local kibana and es instances
\r\n- Run ` node scripts/synthtrace k8s_entities.ts --live --clean
`\r\n- Run `PUT kbn:/internal/entities/managed/enablement` on the
devtools\r\n- Install the kubernetes integration package to have the
dashboards\r\ninstalled.\r\n- Navigate to `Inventory` and click through
the k8s entities\r\n\r\n---------\r\n\r\nCo-authored-by: kibanamachine
<[email protected]>\r\nCo-authored-by:
Elastic Machine
<[email protected]>","sha":"8145cb7c6f483c3a8aa561b492fa098e3ce52027"}},"sourceBranch":"main","suggestedTargetBranches":[],"targetPullRequestStates":[{"branch":"main","label":"v9.0.0","branchLabelMappingKey":"^v9.0.0$","isSourceBranch":true,"state":"MERGED","url":"https://github.com/elastic/kibana/pull/197222","number":197222,"mergeCommit":{"message":"[ECO][Inventory]
Redirect ECS k8s entities to dashboards (#197222)\n\ncloses
[#196142](https://github.com/elastic/kibana/issues/196142)\r\n\r\n##
Summary\r\n\r\nLinks kubernetes ECS entities to their corresponding
dashboards\r\n\r\n> [!IMPORTANT]\r\n> ECS `replicaset` doesn't have a
dedicated dashboard. `container` will\r\nbe handled in a separate
ticket\r\n> Semconv won't link to any dashboard/page\r\n\r\n<img
width=\"800\"
alt=\"image\"\r\nsrc=\"https://github.com/user-attachments/assets/711dbd28-f0ef-4af0-a658-afe7f1595697\">\r\n\r\n\r\n![redirect](https://github.com/user-attachments/assets/77d5d2e1-7ec4-40cd-b7d8-419e07e6b760)\r\n\r\n\r\n###
How to test\r\n- While #196916 is
not merged,\r\nchange `ENTITIES_LATEST_ALIAS` constant to
`'.entities.v1.latest*'`\r\n- Start a local kibana and es instances
\r\n- Run ` node scripts/synthtrace k8s_entities.ts --live --clean
`\r\n- Run `PUT kbn:/internal/entities/managed/enablement` on the
devtools\r\n- Install the kubernetes integration package to have the
dashboards\r\ninstalled.\r\n- Navigate to `Inventory` and click through
the k8s entities\r\n\r\n---------\r\n\r\nCo-authored-by: kibanamachine
<[email protected]>\r\nCo-authored-by:
Elastic Machine
<[email protected]>","sha":"8145cb7c6f483c3a8aa561b492fa098e3ce52027"}}]}]
BACKPORT-->

Co-authored-by: Carlos Crespo <[email protected]>
  • Loading branch information
kibanamachine and crespocarlos authored Nov 4, 2024
1 parent 312f642 commit 19900a0
Show file tree
Hide file tree
Showing 28 changed files with 715 additions and 369 deletions.
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)$/, '');
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'],
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'],
},
host: {
name: 'my-host',
},
};

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

describe('getIdentityFieldsValue', () => {
it('should return identity fields values', () => {
const entityLatest: EnitityInstance = {
entity: {
...commonEntityFields.entity,
identity_fields: ['service.name', 'service.environment'],
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>);
}
}
12 changes: 0 additions & 12 deletions x-pack/plugins/observability_solution/apm/common/entities/types.ts

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

0 comments on commit 19900a0

Please sign in to comment.