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

[ResponseOps][Alerts] Add alerts grouping aggregations endpoint #186475

Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
ac35282
Add get alerts group aggregations endpoint
umbopepato Jun 19, 2024
15f9aa7
Add alerts group aggregation endpoint tests
umbopepato Jun 19, 2024
46fea59
Merge branch 'main' of github.com:elastic/kibana into 186383-alerts-g…
umbopepato Jun 19, 2024
a47b66f
Fix import
umbopepato Jun 19, 2024
e091401
Automatically add unitsCount subaggregation in groupByField aggregation
umbopepato Jun 19, 2024
ae8b482
Merge branch 'main' of github.com:elastic/kibana into 186383-alerts-g…
umbopepato Jun 19, 2024
0529905
Make aggregations field optional, improve documentation
umbopepato Jun 19, 2024
6f57233
Merge branch 'main' of github.com:elastic/kibana into 186383-alerts-g…
umbopepato Jun 19, 2024
e39bfa5
Merge branch 'main' of github.com:elastic/kibana into 186383-alerts-g…
umbopepato Jun 20, 2024
d848db0
Fix tests
umbopepato Jun 20, 2024
46fb4fd
Add tests and improve AlertsClient.find errors handling
umbopepato Jun 20, 2024
eaa7bd6
Merge branch 'main' of github.com:elastic/kibana into 186383-alerts-g…
umbopepato Jun 20, 2024
52485c3
Merge branch 'main' of github.com:elastic/kibana into 186383-alerts-g…
umbopepato Jun 21, 2024
e8b0329
Revert error response transformation
umbopepato Jun 21, 2024
de6c865
Use type instead of interface for validation
umbopepato Jun 21, 2024
62194c9
Merge branch 'main' of github.com:elastic/kibana into 186383-alerts-g…
umbopepato Jun 25, 2024
238e803
Restrict filters and pagination options validation
umbopepato Jun 25, 2024
1c1a1fd
Merge branch 'main' of github.com:elastic/kibana into 186383-alerts-g…
umbopepato Jun 26, 2024
0731496
Fix test
umbopepato Jun 26, 2024
ca88557
Merge branch 'main' of github.com:elastic/kibana into 186383-alerts-g…
umbopepato Jul 3, 2024
8869584
Improve typings and validations
umbopepato Jul 3, 2024
11ac1fc
Fix AlertsClient.find not returning result
umbopepato Jul 3, 2024
6fc8aee
Merge branch 'main' of github.com:elastic/kibana into 186383-alerts-g…
umbopepato Jul 3, 2024
cb2e535
Move alert group aggregations pagination tests
umbopepato Jul 3, 2024
90a86d1
Improve filters validation schema and searchAlerts control flow
umbopepato Jul 4, 2024
39e0ae2
Merge branch 'main' of github.com:elastic/kibana into 186383-alerts-g…
umbopepato Jul 4, 2024
c962e1f
Fix filter keys validation schema type assertion
umbopepato Jul 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
1 change: 1 addition & 0 deletions packages/kbn-alerts-ui-shared/src/common/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,4 @@ export * from './use_load_alerting_framework_health';
export * from './use_create_rule';
export * from './use_update_rule';
export * from './use_resolve_rule';
export * from './use_get_alerts_group_aggregations_query';
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/*
* 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 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import { i18n } from '@kbn/i18n';
import { useQuery } from '@tanstack/react-query';
import type { HttpStart } from '@kbn/core-http-browser';
import type { ToastsStart } from '@kbn/core-notifications-browser';
import { SearchResponseBody } from '@elastic/elasticsearch/lib/api/types';
import { AlertConsumers } from '@kbn/rule-data-utils';
import type {
AggregationsAggregationContainer,
QueryDslQueryContainer,
SortCombinations,
} from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { BASE_RAC_ALERTS_API_PATH } from '../constants';

export interface UseGetAlertsGroupAggregationsQueryProps {
http: HttpStart;
toasts: ToastsStart;
enabled?: boolean;
params: {
featureIds: AlertConsumers[];
groupByField: string;
aggregations?: Record<string, AggregationsAggregationContainer>;
filters?: QueryDslQueryContainer[];
sort?: SortCombinations[];
pageIndex?: number;
pageSize?: number;
};
}

/**
* Fetches alerts aggregations for a given groupByField.
*
* Some default aggregations are applied:
* - `groupByFields`, to get the buckets based on the provided grouping field,
* - `unitsCount`, to count the number of alerts in each bucket,
* - `unitsCount`, to count the total number of alerts targeted by the query,
* - `groupsCount`, to count the total number of groups.
*
* The provided `aggregations` are applied within `groupByFields`. Here the `groupByField` runtime
* field can be used to perform grouping-based aggregations.
*
* Applies alerting RBAC through featureIds.
*/
export const useGetAlertsGroupAggregationsQuery = <T>({
Copy link
Contributor

@adcoelho adcoelho Jun 20, 2024

Choose a reason for hiding this comment

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

Could you please add tests for this in packages/kbn-alerts-ui-shared/src/common/hooks/use_get_alerts_group_aggregations_query.test.ts? Stuff like displays error toast if params are not JSON or API gets called with the correct body..

http,
toasts,
enabled = true,
params,
}: UseGetAlertsGroupAggregationsQueryProps) => {
const onErrorFn = (error: Error) => {
if (error) {
toasts.addDanger(
i18n.translate(
'alertsUIShared.hooks.useFindAlertsQuery.unableToFetchAlertsGroupingAggregations',
{
defaultMessage: 'Unable to fetch alerts grouping aggregations',
}
)
);
}
};

return useQuery({
queryKey: ['getAlertsGroupAggregations', JSON.stringify(params)],
queryFn: () =>
http.post<SearchResponseBody<{}, T>>(`${BASE_RAC_ALERTS_API_PATH}/_group_aggregations`, {
body: JSON.stringify(params),
}),
onError: onErrorFn,
refetchOnWindowFocus: false,
enabled,
});
};
5 changes: 5 additions & 0 deletions x-pack/plugins/rule_registry/common/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,11 @@ export const bucketAggsSchemas = t.intersection([
),
]);

export const alertsAggregationsSchema = t.record(
t.string,
t.intersection([metricsAggsSchemas, bucketAggsSchemas])
);

export type PutIndexTemplateRequest = estypes.IndicesPutIndexTemplateRequest & {
body?: { composed_of?: string[] };
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const createAlertsClientMock = () => {
bulkUpdate: jest.fn(),
bulkUpdateCases: jest.fn(),
find: jest.fn(),
getGroupAggregations: jest.fn(),
getFeatureIdsByRegistrationContexts: jest.fn(),
getBrowserFields: jest.fn(),
getAlertSummary: jest.fn(),
Expand Down
146 changes: 126 additions & 20 deletions x-pack/plugins/rule_registry/server/alert_data_client/alerts_client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
* 2.0.
*/
import Boom from '@hapi/boom';
import { v4 as uuid } from 'uuid';
Copy link
Contributor

Choose a reason for hiding this comment

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

super nit:

Suggested change
import { v4 as uuid } from 'uuid';
import { v4 as uuidv4 } from 'uuid';

import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { PublicMethodsOf } from '@kbn/utility-types';
import { Filter, buildEsQuery, EsQueryConfig } from '@kbn/es-query';
Expand All @@ -27,6 +28,7 @@ import {

import {
InlineScript,
MappingRuntimeFields,
QueryDslQueryContainer,
} from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { RuleTypeParams, PluginStartContract as AlertingStart } from '@kbn/alerting-plugin/server';
Expand All @@ -41,6 +43,8 @@ import { AuditLogger } from '@kbn/security-plugin/server';
import { FieldDescriptor, IndexPatternsFetcher } from '@kbn/data-plugin/server';
import { isEmpty } from 'lodash';
import { RuleTypeRegistry } from '@kbn/alerting-plugin/server/types';
import { TypeOf } from 'io-ts';
import { DEFAULT_ALERTS_GROUP_BY_FIELD_SIZE, MAX_ALERTS_GROUPING_QUERY_SIZE } from './constants';
import { BrowserFields } from '../../common';
import { alertAuditEvent, operationAlertAuditActionMap } from './audit_events';
import {
Expand All @@ -53,6 +57,7 @@ import { ParsedTechnicalFields } from '../../common/parse_technical_fields';
import { IRuleDataService } from '../rule_data_plugin_service';
import { getAuthzFilter, getSpacesFilter } from '../lib';
import { fieldDescriptorToBrowserFieldMapper } from './browser_fields';
import { alertsAggregationsSchema } from '../../common/types';

// TODO: Fix typings https://github.com/elastic/kibana/issues/101776
type NonNullableProps<Obj extends {}, Props extends keyof Obj> = Omit<Obj, Props> & {
Expand Down Expand Up @@ -88,15 +93,15 @@ export interface ConstructorOptions {
export interface UpdateOptions<Params extends RuleTypeParams> {
id: string;
status: string;
_version: string | undefined;
_version?: string;
index: string;
}

export interface BulkUpdateOptions<Params extends RuleTypeParams> {
ids: string[] | undefined | null;
ids?: string[] | null;
status: STATUS_VALUES;
index: string;
query: object | string | undefined | null;
query?: object | string | null;
}

interface MgetAndAuditAlert {
Expand Down Expand Up @@ -129,17 +134,18 @@ interface GetAlertSummaryParams {
}

interface SingleSearchAfterAndAudit {
id?: string | null | undefined;
query?: string | object | undefined;
aggs?: Record<string, any> | undefined;
id?: string | null;
query?: string | object;
aggs?: Record<string, any>;
index?: string;
_source?: string[] | undefined;
_source?: string[] | false;
Copy link
Contributor

Choose a reason for hiding this comment

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

curious about this type, why can it be false?

Copy link
Member Author

Choose a reason for hiding this comment

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

To disable the _source field (docs)

track_total_hits?: boolean | number;
size?: number | undefined;
size?: number;
operation: WriteOperations.Update | ReadOperations.Find | ReadOperations.Get;
sort?: estypes.SortOptions[] | undefined;
lastSortIds?: Array<string | number> | undefined;
sort?: estypes.SortOptions[];
lastSortIds?: Array<string | number>;
featureIds?: string[];
runtimeMappings?: MappingRuntimeFields;
}

/**
Expand Down Expand Up @@ -213,13 +219,10 @@ export class AlertsClient {
items: Array<{
_id: string;
// this is typed kind of crazy to fit the output of es api response to this
_source?:
| {
[ALERT_RULE_TYPE_ID]?: string | null | undefined;
[ALERT_RULE_CONSUMER]?: string | null | undefined;
}
| null
| undefined;
_source?: {
[ALERT_RULE_TYPE_ID]?: string | null;
[ALERT_RULE_CONSUMER]?: string | null;
} | null;
}>,
operation: ReadOperations.Find | ReadOperations.Get | WriteOperations.Update
) {
Expand All @@ -236,8 +239,8 @@ export class AlertsClient {
{ hitIds: [], ownersAndRuleTypeIds: [] } as {
hitIds: string[];
ownersAndRuleTypeIds: Array<{
[ALERT_RULE_TYPE_ID]: string | null | undefined;
[ALERT_RULE_CONSUMER]: string | null | undefined;
[ALERT_RULE_TYPE_ID]?: string | null;
[ALERT_RULE_CONSUMER]?: string | null;
}>;
}
);
Expand Down Expand Up @@ -289,6 +292,7 @@ export class AlertsClient {
sort,
lastSortIds = [],
featureIds,
runtimeMappings,
}: SingleSearchAfterAndAudit) {
try {
const alertSpaceId = this.spaceId;
Expand Down Expand Up @@ -322,6 +326,7 @@ export class AlertsClient {
},
},
],
runtime_mappings: runtimeMappings,
};

if (lastSortIds.length > 0) {
Expand Down Expand Up @@ -982,6 +987,7 @@ export class AlertsClient {
sort,
track_total_hits: trackTotalHits,
_source,
runtimeMappings,
}: {
aggs?: object;
featureIds?: string[];
Expand All @@ -991,7 +997,8 @@ export class AlertsClient {
size?: number;
sort?: estypes.SortOptions[];
track_total_hits?: boolean | number;
_source?: string[];
_source?: string[] | false;
runtimeMappings?: MappingRuntimeFields;
}) {
try {
let indexToUse = index;
Expand All @@ -1013,6 +1020,7 @@ export class AlertsClient {
operation: ReadOperations.Find,
sort,
lastSortIds: searchAfter,
runtimeMappings,
});

if (alertsSearchResponse == null) {
Expand All @@ -1028,6 +1036,104 @@ export class AlertsClient {
}
}

/**
* Performs a `find` query to extract aggregations on alert groups
*/
public getGroupAggregations({
Copy link
Contributor

Choose a reason for hiding this comment

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

How about adding something like x-pack/plugins/rule_registry/server/alert_data_client/tests/getGroupAggregations.test.ts that tests this?

Nothing too elaborate, to ensure that find is called with the correct params and no changes break this function.

I know we do some testing in x-pack/plugins/rule_registry/server/routes/get_alerts_group_aggregations.test.ts but that is like "indirectly" 😛

Copy link
Member

Choose a reason for hiding this comment

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

+1

featureIds,
groupByField,
aggregations,
filters,
pageIndex = 0,
pageSize = DEFAULT_ALERTS_GROUP_BY_FIELD_SIZE,
sort = [{ unitsCount: { order: 'desc' } }],
}: {
/**
* The feature ids the alerts belong to, used for authorization
*/
featureIds: string[];
/**
* The field to group by
* @example "kibana.alert.rule.name"
*/
groupByField: string;
/**
* The aggregations to perform on the groupByField buckets
*/
aggregations?: TypeOf<typeof alertsAggregationsSchema>;
/**
* The filters to apply to the query
*/
filters?: estypes.QueryDslQueryContainer[];
/**
* Any sort options to apply to the groupByField aggregations
*/
sort?: object[];
Copy link
Member

Choose a reason for hiding this comment

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

In the useGetAlertsGroupAggregationsQuery you used the SortCombinations type for the sort. Should we use the same here?

/**
* The page index to start from
*/
pageIndex?: number;
/**
* The page size
*/
pageSize?: number;
}) {
const uniqueValue = uuid();
return this.find({
Copy link
Contributor

@adcoelho adcoelho Jun 20, 2024

Choose a reason for hiding this comment

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

Like you were saying yesterday, QueryDSL gives me headaches 😄

aggs: {
groupByField: {
terms: {
field: 'groupByField',
size: MAX_ALERTS_GROUPING_QUERY_SIZE,
},
aggs: {
unitsCount: { value_count: { field: 'groupByField' } },
bucket_truncate: {
bucket_sort: {
sort,
from: pageIndex * pageSize,
size: pageSize,
},
},
...(aggregations ?? {}),
},
},
unitsCount: { value_count: { field: 'groupByField' } },
groupsCount: { cardinality: { field: 'groupByField' } },
},
featureIds,
query: {
bool: {
filter: filters,
},
},
runtimeMappings: {
groupByField: {
type: 'keyword',
script: {
source:
// When size()==0, emits a uniqueValue as the value to represent this group else join by uniqueValue.
"if (doc[params['selectedGroup']].size()==0) { emit(params['uniqueValue']) }" +
Copy link
Contributor

Choose a reason for hiding this comment

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

nitpick: can use `` to avoid concatenating the strings

Copy link
Member Author

@umbopepato umbopepato Jul 4, 2024

Choose a reason for hiding this comment

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

Yep, I thought it was worth keeping it as it was originally written by Security though, to comment the two parts separately 🙂

// Else, join the values with uniqueValue. We cannot simply emit the value like doc[params['selectedGroup']].value,
// the runtime field will only return the first value in an array.
// The docs advise that if the field has multiple values, "Scripts can call the emit method multiple times to emit multiple values."
// However, this gives us a group for each value instead of combining the values like we're aiming for.
// Instead of .value, we can retrieve all values with .join().
// Instead of joining with a "," we should join with a unique value to avoid splitting a value that happens to contain a ",".
// We will format into a proper array in parseGroupingQuery .
" else { emit(doc[params['selectedGroup']].join(params['uniqueValue']))}",
params: {
selectedGroup: groupByField,
uniqueValue,
},
},
},
},
size: 0,
_source: false,
});
}

public async getAuthorizedAlertsIndices(featureIds: string[]): Promise<string[] | undefined> {
try {
const authorizedRuleTypes = await this.authorization.getAuthorizedRuleTypes(
Expand Down
18 changes: 18 additions & 0 deletions x-pack/plugins/rule_registry/server/alert_data_client/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/*
* 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.
*/

/**
* The maximum number of alert groups to render
*/
export const DEFAULT_ALERTS_GROUP_BY_FIELD_SIZE = 10;

/**
* Grouping pagination breaks if the field cardinality exceeds this number
*
* @external https://github.com/elastic/kibana/issues/151913
*/
export const MAX_ALERTS_GROUPING_QUERY_SIZE = 10000;
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,7 @@ describe('find()', () => {
"should": Array [],
},
},
"runtime_mappings": undefined,
"size": undefined,
"sort": Array [
Object {
Expand Down Expand Up @@ -314,6 +315,7 @@ describe('find()', () => {
"should": Array [],
},
},
"runtime_mappings": undefined,
"size": undefined,
"sort": Array [
Object {
Expand Down
Loading