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

[Alerting] Add more rule execution context #117504

Merged
merged 15 commits into from
Nov 28, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
42 changes: 41 additions & 1 deletion x-pack/plugins/alerting/server/task_runner/task_runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import apm from 'elastic-apm-node';
import type { PublicMethodsOf } from '@kbn/utility-types';
import { Dictionary, pickBy, mapValues, without, cloneDeep } from 'lodash';
import type { Request } from '@hapi/hapi';
Expand Down Expand Up @@ -483,6 +483,17 @@ export class TaskRunner<
// Ensure API key is still valid and user has access
try {
alert = await rulesClient.get({ id: alertId });

if (apm.currentTransaction) {
apm.currentTransaction.name = `Execute Alerting Rule: "${alert.name}"`;
apm.currentTransaction.addLabels({
alerting_rule_consumer: alert.consumer,
alerting_rule_name: alert.name,
alerting_rule_tags: alert.tags.join(', '),
alerting_rule_type_id: alert.alertTypeId,
alerting_rule_params: JSON.stringify(alert.params),
});
}
} catch (err) {
throw new ErrorWithReason(AlertExecutionStatusErrorReasons.Read, err);
}
Expand Down Expand Up @@ -512,6 +523,13 @@ export class TaskRunner<
schedule: taskSchedule,
} = this.taskInstance;

if (apm.currentTransaction) {
apm.currentTransaction.name = `Execute Alerting Rule`;
cyrille-leclerc marked this conversation as resolved.
Show resolved Hide resolved
apm.currentTransaction.addLabels({
alerting_rule_id: alertId,
});
}

const runDate = new Date();
const runDateString = runDate.toISOString();
this.logger.debug(`executing alert ${this.alertType.id}:${alertId} at ${runDateString}`);
Expand Down Expand Up @@ -567,6 +585,14 @@ export class TaskRunner<
executionStatus.lastExecutionDate = new Date(event.event.start);
}

if (apm.currentTransaction) {
if (executionStatus.status === 'ok') {
Copy link
Member

Choose a reason for hiding this comment

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

The valid status values for this field are here:

export const AlertExecutionStatusValues = ['ok', 'active', 'error', 'pending', 'unknown'] as const;
export type AlertExecutionStatuses = typeof AlertExecutionStatusValues[number];

pending means it hasn't run yet, so should never go through this path.

unknown indicates some unexpected issue, so should probably be categorized as 'failure'.

active is a flavor of ok - the difference between the two is active indicates there are active alert instances, ok indicates there are not (the last run did not schedule any alert instances). So active should also be listed as success.

Copy link
Member Author

Choose a reason for hiding this comment

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

Handled both suggested cases 👍

apm.currentTransaction.setOutcome('success');
} else if (executionStatus.status === 'error') {
apm.currentTransaction.setOutcome('failure');
}
}

this.logger.debug(
`alertExecutionStatus for ${this.alertType.id}:${alertId}: ${JSON.stringify(executionStatus)}`
);
Expand Down Expand Up @@ -749,6 +775,12 @@ function generateNewAndRecoveredInstanceEvents<
const recoveredAlertInstanceIds = Object.keys(recoveredAlertInstances);
const newIds = without(currentAlertInstanceIds, ...originalAlertInstanceIds);

if (apm.currentTransaction) {
apm.currentTransaction.addLabels({
alerting_new_instances: newIds.length,
Copy link
Contributor

Choose a reason for hiding this comment

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

Following our updated terminology, I believe this should be alerting_new_alerts, alerting_active_alerts, alerting_recovered_alerts

});
}

for (const id of recoveredAlertInstanceIds) {
const { group: actionGroup, subgroup: actionSubgroup } =
recoveredAlertInstances[id].getLastScheduledActions() ?? {};
Expand Down Expand Up @@ -929,6 +961,14 @@ function logActiveAndRecoveredInstances<
const { logger, activeAlertInstances, recoveredAlertInstances, alertLabel } = params;
const activeInstanceIds = Object.keys(activeAlertInstances);
const recoveredInstanceIds = Object.keys(recoveredAlertInstances);

if (apm.currentTransaction) {
apm.currentTransaction.addLabels({
alerting_active_instances: activeInstanceIds.length,
alerting_recovered_instances: recoveredInstanceIds.length,
});
}

if (activeInstanceIds.length > 0) {
logger.debug(
`alert ${alertLabel} has ${activeInstanceIds.length} active alert instances: ${JSON.stringify(
Expand Down
8 changes: 7 additions & 1 deletion x-pack/plugins/task_manager/server/task_scheduling.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,15 @@ export class TaskScheduling {
...options,
taskInstance: ensureDeprecatedFieldsAreCorrected(taskInstance, this.logger),
});

const traceparent =
agent.currentTransaction && agent.currentTransaction.type !== 'request'
? agent.currentTraceparent
: '';

return await this.store.schedule({
...modifiedTask,
traceparent: agent.currentTraceparent ?? '',
traceparent: traceparent || '',
});
}

Expand Down