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

[EEM][POC] The POC for creating entity-centric indices using entity definitions #183205

Merged
merged 17 commits into from
May 17, 2024
Merged
Show file tree
Hide file tree
Changes from 4 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
1 change: 1 addition & 0 deletions .github/CODEOWNERS
Validating CODEOWNERS rules …
Original file line number Diff line number Diff line change
Expand Up @@ -600,6 +600,7 @@ src/plugins/newsfeed @elastic/kibana-core
test/common/plugins/newsfeed @elastic/kibana-core
src/plugins/no_data_page @elastic/appex-sharedux
x-pack/plugins/notifications @elastic/appex-sharedux
x-pack/packages/kbn-oam-schema @elastic/obs-knowledge-team
packages/kbn-object-versioning @elastic/appex-sharedux
x-pack/plugins/observability_solution/observability_ai_assistant_app @elastic/obs-ai-assistant
x-pack/plugins/observability_solution/observability_ai_assistant_management @elastic/obs-ai-assistant
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -621,6 +621,7 @@
"@kbn/newsfeed-test-plugin": "link:test/common/plugins/newsfeed",
"@kbn/no-data-page-plugin": "link:src/plugins/no_data_page",
"@kbn/notifications-plugin": "link:x-pack/plugins/notifications",
"@kbn/oam-schema": "link:x-pack/packages/kbn-oam-schema",
"@kbn/object-versioning": "link:packages/kbn-object-versioning",
"@kbn/observability-ai-assistant-app-plugin": "link:x-pack/plugins/observability_solution/observability_ai_assistant_app",
"@kbn/observability-ai-assistant-management-plugin": "link:x-pack/plugins/observability_solution/observability_ai_assistant_management",
Expand Down
2 changes: 2 additions & 0 deletions tsconfig.base.json
Original file line number Diff line number Diff line change
Expand Up @@ -1194,6 +1194,8 @@
"@kbn/no-data-page-plugin/*": ["src/plugins/no_data_page/*"],
"@kbn/notifications-plugin": ["x-pack/plugins/notifications"],
"@kbn/notifications-plugin/*": ["x-pack/plugins/notifications/*"],
"@kbn/oam-schema": ["x-pack/packages/kbn-oam-schema"],
"@kbn/oam-schema/*": ["x-pack/packages/kbn-oam-schema/*"],
"@kbn/object-versioning": ["packages/kbn-object-versioning"],
"@kbn/object-versioning/*": ["packages/kbn-object-versioning/*"],
"@kbn/observability-ai-assistant-app-plugin": ["x-pack/plugins/observability_solution/observability_ai_assistant_app"],
Expand Down
3 changes: 3 additions & 0 deletions x-pack/packages/kbn-oam-schema/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# @kbn/oam-schema

Empty package generated by @kbn/generate
10 changes: 10 additions & 0 deletions x-pack/packages/kbn-oam-schema/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/*
* 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.
*/

export * from './src/schema/oam_definition';
export * from './src/schema/asset';
export * from './src/schema/common';
12 changes: 12 additions & 0 deletions x-pack/packages/kbn-oam-schema/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/*
* 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.
*/

module.exports = {
preset: '@kbn/test',
rootDir: '../../..',
roots: ['<rootDir>/x-pack/packages/kbn-oam-schema'],
};
5 changes: 5 additions & 0 deletions x-pack/packages/kbn-oam-schema/kibana.jsonc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"type": "shared-common",
"id": "@kbn/oam-schema",
"owner": "@elastic/obs-knowledge-team"
}
6 changes: 6 additions & 0 deletions x-pack/packages/kbn-oam-schema/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"name": "@kbn/oam-schema",
"private": true,
"version": "1.0.0",
"license": "Elastic License 2.0"
}
22 changes: 22 additions & 0 deletions x-pack/packages/kbn-oam-schema/src/schema/asset.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/*
* 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 { z } from 'zod';
import { arrayOfStringsSchema } from './common';

export const assetSchema = z.intersection(
z.object({
asset: z.object({
id: z.string(),
indexPattern: arrayOfStringsSchema,
simianhacker marked this conversation as resolved.
Show resolved Hide resolved
category: arrayOfStringsSchema,
simianhacker marked this conversation as resolved.
Show resolved Hide resolved
identityField: arrayOfStringsSchema,
metric: z.record(z.string(), z.number()),
}),
}),
z.record(z.string(), z.string().or(z.number()))
);
99 changes: 99 additions & 0 deletions x-pack/packages/kbn-oam-schema/src/schema/common.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
/*
* 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 { z } from 'zod';
import moment from 'moment';

export enum AssetType {
service = 'service',
host = 'host',
pod = 'pod',
node = 'node',
}

export const arrayOfStringsSchema = z.array(z.string());

export const assetTypeSchema = z.nativeEnum(AssetType);

export enum BasicAggregations {
avg = 'avg',
max = 'max',
min = 'min',
sum = 'sum',
cardinality = 'cardinality',
last_value = 'last_value',
std_deviation = 'std_deviation',
}

export const basicAggregationsSchema = z.nativeEnum(BasicAggregations);

const metricNameSchema = z
.string()
.length(1)
.regex(/[a-zA-Z]/)
.toUpperCase();

export const filterSchema = z.optional(z.string());

export const basicMetricWithFieldSchema = z.object({
name: metricNameSchema,
aggregation: basicAggregationsSchema,
field: z.string(),
filter: filterSchema,
});

export const docCountMetricSchema = z.object({
name: metricNameSchema,
aggregation: z.literal('doc_count'),
filter: filterSchema,
});

export const durationSchema = z
.string()
.regex(/\d+[m|d|s|h]/)
.transform((val: string) => {
const parts = val.match(/(\d+)([m|s|h|d])/);
if (parts === null) {
throw new Error('Unable to parse duration');
}
const value = parseInt(parts[1], 10);
const unit = parts[2] as 'm' | 's' | 'h' | 'd';
const duration = moment.duration(value, unit);
return { ...duration, toJSON: () => val };
});

export const percentileMetricSchema = z.object({
name: metricNameSchema,
aggregation: z.literal('percentile'),
field: z.string(),
percentile: z.number(),
filter: filterSchema,
});

export const metricSchema = z.discriminatedUnion('aggregation', [
basicMetricWithFieldSchema,
docCountMetricSchema,
percentileMetricSchema,
]);

export type Metric = z.infer<typeof metricSchema>;

export const keyMetricSchema = z.object({
name: z.string(),
metrics: z.array(metricSchema),
equation: z.string(),
});

export type KeyMetric = z.infer<typeof keyMetricSchema>;

export const metadataSchema = z
.object({
source: z.string(),
destination: z.optional(z.string()),
limit: z.optional(z.number().default(1000)),
})
.or(z.string().transform((value) => ({ source: value, destination: value, limit: 1000 })));
42 changes: 42 additions & 0 deletions x-pack/packages/kbn-oam-schema/src/schema/oam_definition.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/*
* 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 { z } from 'zod';
import {
arrayOfStringsSchema,
assetTypeSchema,
keyMetricSchema,
metadataSchema,
filterSchema,
durationSchema,
} from './common';

export const oamDefinitionSchema = z.object({
id: z.string().regex(/^[\w-]+$/),
name: z.string(),
description: z.optional(z.string()),
type: assetTypeSchema,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this implies that only definitions using known types are alllowed?

we should discuss this again with chris d to ensure it's extensible wrt user-defined entity definitions.

filter: filterSchema,
indexPatterns: arrayOfStringsSchema,
identityFields: arrayOfStringsSchema,
identityTemplate: z.string(),
categories: arrayOfStringsSchema,
metadata: z.optional(z.array(metadataSchema)),
metrics: z.optional(z.array(keyMetricSchema)),
staticFields: z.optional(z.record(z.string(), z.string())),
lookback: durationSchema,
timestampField: z.string(),
settings: z.optional(
z.object({
syncField: z.optional(z.string()),
syncDelay: z.optional(z.string()),
frequency: z.optional(z.string()),
})
),
});

export type OAMDefinition = z.infer<typeof oamDefinitionSchema>;
18 changes: 18 additions & 0 deletions x-pack/packages/kbn-oam-schema/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"extends": "../../../tsconfig.base.json",
"compilerOptions": {
"outDir": "target/types",
"types": [
"jest",
"node"
]
},
"include": [
"**/*.ts"
],
"exclude": [
"target/**/*"
],
"kbn_references": [
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/*
* 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.
*/

export const OAM_VERSION = 'v1';
export const OAM_BASE_PREFIX = `.oam-observability.asset-${OAM_VERSION}`;
export const OAM_TRANSFORM_PREFIX = `oam-observability-asset-${OAM_VERSION}`;
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
*/

import {
ClusterPutComponentTemplateRequest,
IndicesGetIndexTemplateResponse,
IndicesPutIndexTemplateRequest,
} from '@elastic/elasticsearch/lib/api/types';
Expand Down Expand Up @@ -47,21 +48,18 @@ function templateExists(
});
}

// interface IndexPatternJson {
// index_patterns: string[];
// name: string;
// template: {
// mappings: Record<string, any>;
// settings: Record<string, any>;
// };
// }

interface TemplateManagementOptions {
esClient: ElasticsearchClient;
template: IndicesPutIndexTemplateRequest;
logger: Logger;
}

interface ComponentManagementOptions {
esClient: ElasticsearchClient;
component: ClusterPutComponentTemplateRequest;
logger: Logger;
}

export async function maybeCreateTemplate({
esClient,
template,
Expand Down Expand Up @@ -93,9 +91,6 @@ export async function maybeCreateTemplate({
}

export async function upsertTemplate({ esClient, template, logger }: TemplateManagementOptions) {
const pattern = ASSETS_INDEX_PREFIX + '*';
template.index_patterns = [pattern];

try {
await esClient.indices.putIndexTemplate(template);
} catch (error: any) {
Expand All @@ -108,3 +103,17 @@ export async function upsertTemplate({ esClient, template, logger }: TemplateMan
);
logger.debug(`Asset manager index template: ${JSON.stringify(template)}`);
}

export async function upsertComponent({ esClient, component, logger }: ComponentManagementOptions) {
try {
await esClient.cluster.putComponentTemplate(component);
} catch (error: any) {
logger.error(`Error updating asset manager component template: ${error.message}`);
return;
}

logger.info(
`Asset manager component template is up to date (use debug logging to see what was installed)`
);
logger.debug(`Asset manager component template: ${JSON.stringify(component)}`);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
* 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 { ElasticsearchClient, Logger } from '@kbn/core/server';
import { OAMDefinition } from '@kbn/oam-schema';
import { generateProcessors } from './ingest_pipeline/generate_processors';
import { retryTransientEsErrors } from './helpers/retry';
import { OAMSecurityException } from './errors/oam_security_exception';
import { generateIngestPipelineId } from './ingest_pipeline/generate_ingest_pipeline_id';

export async function createAndInstallIngestPipeline(
esClient: ElasticsearchClient,
definition: OAMDefinition,
logger: Logger
) {
const processors = generateProcessors(definition);
const id = generateIngestPipelineId(definition);
try {
await retryTransientEsErrors(
() =>
esClient.ingest.putPipeline({
id,
processors,
}),
{ logger }
);
} catch (e) {
logger.error(`Cannot create OAM tranform for [${definition.id}] asset defintion`);
simianhacker marked this conversation as resolved.
Show resolved Hide resolved
if (e.meta?.body?.error?.type === 'security_exception') {
throw new OAMSecurityException(e.meta.body.error.reason, definition);
}
throw e;
}
return id;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/*
* 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 { ElasticsearchClient, Logger } from '@kbn/core/server';
import { OAMDefinition } from '@kbn/oam-schema';
import { generateTransform } from './transform/generate_transform';
import { retryTransientEsErrors } from './helpers/retry';
import { OAMSecurityException } from './errors/oam_security_exception';

export async function createAndInstallTransform(
esClient: ElasticsearchClient,
definition: OAMDefinition,
logger: Logger
) {
const transform = generateTransform(definition);
try {
await retryTransientEsErrors(() => esClient.transform.putTransform(transform), { logger });
} catch (e) {
logger.error(`Cannot create OAM transform for [${definition.id}] asset definition`);
if (e.meta?.body?.error?.type === 'security_exception') {
throw new OAMSecurityException(e.meta.body.error.reason, definition);
}
throw e;
}
return transform.transform_id;
}
Loading