-
Notifications
You must be signed in to change notification settings - Fork 8.3k
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
[ES Query] Fix saving ECS group by fields for query DSL rule #203769
Merged
maryam-saeidi
merged 7 commits into
elastic:main
from
maryam-saeidi:203472-save-ecs-groups-in-aad-query-dsl
Dec 16, 2024
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
b67d38f
Fix saving ECS group by fields for query DQL rule
maryam-saeidi 4c62761
Add API integration test
maryam-saeidi ed667bd
Add more test
maryam-saeidi 3de69ce
Rename test name
maryam-saeidi 6eeba81
Merge branch 'main' into 203472-save-ecs-groups-in-aad-query-dsl
maryam-saeidi 02c84b2
Revert "Add more test"
maryam-saeidi 6697ad2
Merge branch 'main' into 203472-save-ecs-groups-in-aad-query-dsl
maryam-saeidi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
15 changes: 15 additions & 0 deletions
15
...ck/test/api_integration/deployment_agnostic/apis/observability/alerting/es_query/index.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
/* | ||
* 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 { DeploymentAgnosticFtrProviderContext } from '../../../../ftr_provider_context'; | ||
|
||
export default function ({ loadTestFile }: DeploymentAgnosticFtrProviderContext) { | ||
describe('ElasticSearch query rule', () => { | ||
loadTestFile(require.resolve('./query_dsl')); | ||
loadTestFile(require.resolve('./query_dsl_with_group_by')); | ||
}); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
207 changes: 207 additions & 0 deletions
207
...ation/deployment_agnostic/apis/observability/alerting/es_query/query_dsl_with_group_by.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,207 @@ | ||
/* | ||
* 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 expect from '@kbn/expect'; | ||
import { cleanup, generate, Dataset, PartialConfig } from '@kbn/data-forge'; | ||
import { RoleCredentials, InternalRequestHeader } from '@kbn/ftr-common-functional-services'; | ||
import { DeploymentAgnosticFtrProviderContext } from '../../../../ftr_provider_context'; | ||
import { ActionDocument } from './types'; | ||
|
||
export default function ({ getService }: DeploymentAgnosticFtrProviderContext) { | ||
const esClient = getService('es'); | ||
const logger = getService('log'); | ||
const samlAuth = getService('samlAuth'); | ||
const supertestWithoutAuth = getService('supertestWithoutAuth'); | ||
const esDeleteAllIndices = getService('esDeleteAllIndices'); | ||
const alertingApi = getService('alertingApi'); | ||
const config = getService('config'); | ||
const isServerless = config.get('serverless'); | ||
const expectedConsumer = isServerless ? 'observability' : 'logs'; | ||
|
||
let adminRoleAuthc: RoleCredentials; | ||
let internalReqHeader: InternalRequestHeader; | ||
|
||
describe('Query DQL with group by field', () => { | ||
const RULE_TYPE_ID = '.es-query'; | ||
const ALERT_ACTION_INDEX = 'alert-action-es-query'; | ||
const RULE_ALERT_INDEX = '.alerts-stack.alerts-default'; | ||
const INDEX = 'kbn-data-forge-fake_hosts.fake_hosts-*'; | ||
let dataForgeConfig: PartialConfig; | ||
let dataForgeIndices: string[]; | ||
let actionId: string; | ||
let ruleId: string; | ||
|
||
before(async () => { | ||
adminRoleAuthc = await samlAuth.createM2mApiKeyWithRoleScope('admin'); | ||
internalReqHeader = samlAuth.getInternalRequestHeader(); | ||
dataForgeConfig = { | ||
schedule: [ | ||
{ | ||
template: 'good', | ||
start: 'now-10m', | ||
end: 'now+5m', | ||
metrics: [ | ||
{ name: 'system.cpu.user.pct', method: 'linear', start: 2.5, end: 2.5 }, | ||
{ name: 'system.cpu.total.pct', method: 'linear', start: 0.5, end: 0.5 }, | ||
{ name: 'system.cpu.total.norm.pct', method: 'linear', start: 0.8, end: 0.8 }, | ||
], | ||
}, | ||
], | ||
indexing: { | ||
dataset: 'fake_hosts' as Dataset, | ||
eventsPerCycle: 1, | ||
interval: 60000, | ||
alignEventsToInterval: true, | ||
}, | ||
}; | ||
dataForgeIndices = await generate({ client: esClient, config: dataForgeConfig, logger }); | ||
await alertingApi.waitForDocumentInIndex({ | ||
indexName: dataForgeIndices.join(','), | ||
docCountTarget: 45, | ||
}); | ||
}); | ||
|
||
after(async () => { | ||
await supertestWithoutAuth | ||
.delete(`/api/alerting/rule/${ruleId}`) | ||
.set(adminRoleAuthc.apiKeyHeader) | ||
.set(internalReqHeader); | ||
await supertestWithoutAuth | ||
.delete(`/api/actions/connector/${actionId}`) | ||
.set(adminRoleAuthc.apiKeyHeader) | ||
.set(internalReqHeader); | ||
await esClient.deleteByQuery({ | ||
index: RULE_ALERT_INDEX, | ||
query: { term: { 'kibana.alert.rule.uuid': ruleId } }, | ||
conflicts: 'proceed', | ||
}); | ||
await esClient.deleteByQuery({ | ||
index: '.kibana-event-log-*', | ||
query: { term: { 'rule.id': ruleId } }, | ||
conflicts: 'proceed', | ||
}); | ||
await esDeleteAllIndices([ALERT_ACTION_INDEX, ...dataForgeIndices]); | ||
await cleanup({ client: esClient, config: dataForgeConfig, logger }); | ||
await samlAuth.invalidateM2mApiKeyWithRoleScope(adminRoleAuthc); | ||
}); | ||
|
||
describe('Rule creation', () => { | ||
it('creates rule successfully', async () => { | ||
actionId = await alertingApi.createIndexConnector({ | ||
roleAuthc: adminRoleAuthc, | ||
name: 'Index Connector: Alerting API test', | ||
indexName: ALERT_ACTION_INDEX, | ||
}); | ||
|
||
const createdRule = await alertingApi.helpers.createEsQueryRule({ | ||
roleAuthc: adminRoleAuthc, | ||
consumer: expectedConsumer, | ||
name: 'always fire', | ||
ruleTypeId: RULE_TYPE_ID, | ||
params: { | ||
size: 100, | ||
thresholdComparator: '>', | ||
threshold: [1], | ||
index: [INDEX], | ||
timeField: '@timestamp', | ||
esQuery: `{\n \"query\":{\n \"match_all\" : {}\n }\n}`, | ||
timeWindowSize: 1, | ||
timeWindowUnit: 'm', | ||
groupBy: 'top', | ||
termField: 'host.name', | ||
termSize: 1, | ||
}, | ||
actions: [ | ||
{ | ||
group: 'query matched', | ||
id: actionId, | ||
params: { | ||
documents: [ | ||
{ | ||
ruleId: '{{rule.id}}', | ||
ruleName: '{{rule.name}}', | ||
ruleParams: '{{rule.params}}', | ||
spaceId: '{{rule.spaceId}}', | ||
tags: '{{rule.tags}}', | ||
alertId: '{{alert.id}}', | ||
alertActionGroup: '{{alert.actionGroup}}', | ||
instanceContextValue: '{{context.instanceContextValue}}', | ||
instanceStateValue: '{{state.instanceStateValue}}', | ||
}, | ||
], | ||
}, | ||
frequency: { | ||
notify_when: 'onActiveAlert', | ||
throttle: null, | ||
summary: false, | ||
}, | ||
}, | ||
], | ||
}); | ||
ruleId = createdRule.id; | ||
expect(ruleId).not.to.be(undefined); | ||
}); | ||
|
||
it('should be active', async () => { | ||
const executionStatus = await alertingApi.waitForRuleStatus({ | ||
roleAuthc: adminRoleAuthc, | ||
ruleId, | ||
expectedStatus: 'active', | ||
}); | ||
expect(executionStatus).to.be('active'); | ||
}); | ||
|
||
it('should find the created rule with correct information about the consumer', async () => { | ||
const match = await alertingApi.findInRules(adminRoleAuthc, ruleId); | ||
expect(match).not.to.be(undefined); | ||
expect(match.consumer).to.be(expectedConsumer); | ||
}); | ||
|
||
it('should set correct information in the alert document', async () => { | ||
const resp = await alertingApi.waitForAlertInIndex({ | ||
indexName: RULE_ALERT_INDEX, | ||
ruleId, | ||
}); | ||
|
||
expect(resp.hits.hits[0]._source).property('host.name', 'host-0'); | ||
expect(resp.hits.hits[0]._source).property('kibana.alert.rule.consumer', expectedConsumer); | ||
expect(resp.hits.hits[0]._source).property( | ||
'kibana.alert.reason', | ||
'Document count is 3 in the last 1m for host-0 in kbn-data-forge-fake_hosts.fake_hosts-* index. Alert when greater than 1.' | ||
); | ||
expect(resp.hits.hits[0]._source).property( | ||
'kibana.alert.evaluation.conditions', | ||
'Number of matching documents for group "host-0" is greater than 1' | ||
); | ||
expect(resp.hits.hits[0]._source).property('kibana.alert.evaluation.value', '3'); | ||
expect(resp.hits.hits[0]._source).property('kibana.alert.evaluation.threshold', 1); | ||
expect(resp.hits.hits[0]._source).property('kibana.alert.rule.name', 'always fire'); | ||
expect(resp.hits.hits[0]._source).property('event.action', 'open'); | ||
expect(resp.hits.hits[0]._source).property('kibana.alert.action_group', 'query matched'); | ||
expect(resp.hits.hits[0]._source).property('kibana.alert.status', 'active'); | ||
expect(resp.hits.hits[0]._source).property('kibana.alert.workflow_status', 'open'); | ||
expect(resp.hits.hits[0]._source).property( | ||
'kibana.alert.rule.category', | ||
'Elasticsearch query' | ||
); | ||
}); | ||
|
||
it('should set correct action variables', async () => { | ||
const resp = await alertingApi.waitForDocumentInIndex<ActionDocument>({ | ||
indexName: ALERT_ACTION_INDEX, | ||
}); | ||
|
||
expect(resp.hits.hits[0]._source?.ruleId).eql(ruleId); | ||
expect(resp.hits.hits[0]._source?.ruleName).eql('always fire'); | ||
expect(resp.hits.hits[0]._source?.ruleParams).eql( | ||
'{"size":100,"thresholdComparator":">","threshold":[1],"index":["kbn-data-forge-fake_hosts.fake_hosts-*"],"timeField":"@timestamp","esQuery":"{\\n \\"query\\":{\\n \\"match_all\\" : {}\\n }\\n}","timeWindowSize":1,"timeWindowUnit":"m","groupBy":"top","termField":"host.name","termSize":1,"excludeHitsFromPreviousRun":true,"aggType":"count","searchType":"esQuery"}' | ||
); | ||
expect(resp.hits.hits[0]._source?.alertActionGroup).eql('query matched'); | ||
}); | ||
}); | ||
}); | ||
} |
16 changes: 16 additions & 0 deletions
16
...ck/test/api_integration/deployment_agnostic/apis/observability/alerting/es_query/types.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
/* | ||
* 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 interface ActionDocument { | ||
ruleId: string; | ||
ruleName: string; | ||
ruleParams: string; | ||
spaceId: string; | ||
tags: string; | ||
alertId: string; | ||
alertActionGroup: string; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This part of the test fails without this fix.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Oh wow. I thought the change would just be to some grouping properties. I guess that
termField
also has some play in the "extra" properties we create, likehost.name
.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ah, right, this fix is related to the logic that was added in this PR.
Regarding adding group-by information to the alert document, I will create a separate PR. This one only focuses on fixing the bug.