Skip to content

Commit

Permalink
[ML] Link to Anomaly detection job creation from the alerting rule fo…
Browse files Browse the repository at this point in the history
…rm (#174016)

## Summary

Closes #173654

Adds an option to create a new anomaly detection job from the job
selector control.

<img width="614" alt="image"
src="https://github.com/elastic/kibana/assets/5236598/1dc19cb9-b7e5-471c-9dec-3018103efb69">

### Checklist

- [ ] Any text added follows [EUI's writing
guidelines](https://elastic.github.io/eui/#/guidelines/writing), uses
sentence case text and includes [i18n
support](https://github.com/elastic/kibana/blob/main/packages/kbn-i18n/README.md)
- [ ]
[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)
was added for features that require explanation or tutorials
- [ ] [Unit or functional
tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)
were updated or added to match the most common scenarios
- [x] Any UI touched in this PR is usable by keyboard only (learn more
about [keyboard accessibility](https://webaim.org/techniques/keyboard/))
- [x] Any UI touched in this PR does not create any new axe failures
(run axe in browser:
[FF](https://addons.mozilla.org/en-US/firefox/addon/axe-devtools/),
[Chrome](https://chrome.google.com/webstore/detail/axe-web-accessibility-tes/lhdoppojpmngadmnindnejefpokejbdd?hl=en-US))
- [x] This renders correctly on smaller devices using a responsive
layout. (You can test this [in your
browser](https://www.browserstack.com/guide/responsive-testing-on-local-server))
- [x] This was checked for [cross-browser
compatibility](https://www.elastic.co/support/matrix#matrix_browsers)
  • Loading branch information
darnautov authored Jan 3, 2024
1 parent 52f458c commit 085da72
Show file tree
Hide file tree
Showing 11 changed files with 278 additions and 151 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ import {
EuiSpacer,
EuiText,
} from '@elastic/eui';
import { MlAnomalyDetectionAlertAdvancedSettings } from '../../common/types/alerts';
import { TimeIntervalControl } from './time_interval_control';
import { TOP_N_BUCKETS_COUNT } from '../../common/constants/alerts';
import { type MlAnomalyDetectionAlertAdvancedSettings } from '../../../common/types/alerts';
import { TimeIntervalControl } from '../time_interval_control';
import { TOP_N_BUCKETS_COUNT } from '../../../common/constants/alerts';

interface AdvancedSettingsProps {
value: MlAnomalyDetectionAlertAdvancedSettings;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@ import React, { FC } from 'react';

import { FormattedMessage } from '@kbn/i18n-react';
import { EuiCallOut, EuiSpacer } from '@elastic/eui';
import { parseInterval } from '../../common/util/parse_interval';
import { CombinedJobWithStats } from '../../common/types/anomaly_detection_jobs';
import { DATAFEED_STATE } from '../../common/constants/states';
import { MlAnomalyDetectionAlertParams } from '../../common/types/alerts';
import { MlAnomalyAlertTriggerProps } from './ml_anomaly_alert_trigger';
import { TOP_N_BUCKETS_COUNT } from '../../common/constants/alerts';
import { parseInterval } from '../../../common/util/parse_interval';
import { type CombinedJobWithStats } from '../../../common/types/anomaly_detection_jobs';
import { DATAFEED_STATE } from '../../../common/constants/states';
import { type MlAnomalyDetectionAlertParams } from '../../../common/types/alerts';
import { type MlAnomalyAlertTriggerProps } from './ml_anomaly_alert_trigger';
import { TOP_N_BUCKETS_COUNT } from '../../../common/constants/alerts';

interface ConfigValidatorProps {
alertInterval: string;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/*
* 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 { registerAnomalyDetectionRule } from './register_anomaly_detection_rule';
Original file line number Diff line number Diff line change
Expand Up @@ -12,28 +12,34 @@ import { i18n } from '@kbn/i18n';
import { RuleTypeParamsExpressionProps } from '@kbn/triggers-actions-ui-plugin/public';
import { isDefined } from '@kbn/ml-is-defined';
import { ML_ANOMALY_RESULT_TYPE, ML_ANOMALY_THRESHOLD } from '@kbn/ml-anomaly-utils';
import { JobSelectorControl } from './job_selector';
import { useMlKibana } from '../application/contexts/kibana';
import { jobsApiProvider } from '../application/services/ml_api_service/jobs';
import { HttpService } from '../application/services/http_service';
import { useToastNotificationService } from '../application/services/toast_notification_service';
import { SeverityControl } from '../application/components/severity_control';
import { useKibana } from '@kbn/kibana-react-plugin/public';
import type { MlCapabilities } from '../../../common/types/capabilities';
import { ML_PAGES } from '../../../common/constants/locator';
import type { MlCoreSetup } from '../../plugin';
import { JobSelectorControl } from '../job_selector';
import { jobsApiProvider } from '../../application/services/ml_api_service/jobs';
import { HttpService } from '../../application/services/http_service';
import { useToastNotificationService } from '../../application/services/toast_notification_service';
import { SeverityControl } from '../../application/components/severity_control';
import { ResultTypeSelector } from './result_type_selector';
import { alertingApiProvider } from '../application/services/ml_api_service/alerting';
import { alertingApiProvider } from '../../application/services/ml_api_service/alerting';
import { PreviewAlertCondition } from './preview_alert_condition';
import {
import type {
MlAnomalyDetectionAlertAdvancedSettings,
MlAnomalyDetectionAlertParams,
} from '../../common/types/alerts';
} from '../../../common/types/alerts';
import { InterimResultsControl } from './interim_results_control';
import { ConfigValidator } from './config_validator';
import { CombinedJobWithStats } from '../../common/types/anomaly_detection_jobs';
import { type CombinedJobWithStats } from '../../../common/types/anomaly_detection_jobs';
import { AdvancedSettings } from './advanced_settings';
import { getLookbackInterval, getTopNBuckets } from '../../common/util/alerts';
import { parseInterval } from '../../common/util/parse_interval';
import { getLookbackInterval, getTopNBuckets } from '../../../common/util/alerts';
import { parseInterval } from '../../../common/util/parse_interval';

export type MlAnomalyAlertTriggerProps =
RuleTypeParamsExpressionProps<MlAnomalyDetectionAlertParams>;
RuleTypeParamsExpressionProps<MlAnomalyDetectionAlertParams> & {
getStartServices: MlCoreSetup['getStartServices'];
mlCapabilities: MlCapabilities;
};

const MlAnomalyAlertTrigger: FC<MlAnomalyAlertTriggerProps> = ({
ruleParams,
Expand All @@ -42,11 +48,36 @@ const MlAnomalyAlertTrigger: FC<MlAnomalyAlertTriggerProps> = ({
errors,
ruleInterval,
alertNotifyWhen,
getStartServices,
mlCapabilities,
}) => {
const {
services: { http },
} = useMlKibana();
const mlHttpService = useMemo(() => new HttpService(http), [http]);
} = useKibana();

const [newJobUrl, setNewJobUrl] = useState<string | undefined>(undefined);

useEffect(() => {
let mounted = true;

if (!mlCapabilities.canCreateJob) return;

getStartServices().then((startServices) => {
const locator = startServices[2].locator;
if (!locator) return;
locator.getUrl({ page: ML_PAGES.ANOMALY_DETECTION_CREATE_JOB }).then((url) => {
if (mounted) {
setNewJobUrl(url);
}
});
});

return () => {
mounted = false;
};
}, [getStartServices, mlCapabilities]);

const mlHttpService = useMemo(() => new HttpService(http!), [http]);
const adJobsApiService = useMemo(() => jobsApiProvider(mlHttpService), [mlHttpService]);
const alertingApiService = useMemo(() => alertingApiProvider(mlHttpService), [mlHttpService]);
const { displayErrorToast } = useToastNotificationService();
Expand Down Expand Up @@ -159,6 +190,7 @@ const MlAnomalyAlertTrigger: FC<MlAnomalyAlertTriggerProps> = ({
return (
<EuiForm data-test-subj={'mlAnomalyAlertForm'}>
<JobSelectorControl
createJobUrl={newJobUrl}
jobsAndGroupIds={jobsAndGroupIds}
adJobsApiService={adJobsApiService}
// eslint-disable-next-line react-hooks/exhaustive-deps
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,12 @@ import {
EuiSpacer,
EuiText,
} from '@elastic/eui';
import type { AlertingApiService } from '../application/services/ml_api_service/alerting';
import { MlAnomalyDetectionAlertParams, PreviewResponse } from '../../common/types/alerts';
import { composeValidators } from '../../common';
import { requiredValidator, timeIntervalInputValidator } from '../../common/util/validators';
import { invalidTimeIntervalMessage } from '../application/jobs/new_job/common/job_validator/util';
import { ALERT_PREVIEW_SAMPLE_SIZE } from '../../common/constants/alerts';
import type { AlertingApiService } from '../../application/services/ml_api_service/alerting';
import { MlAnomalyDetectionAlertParams, PreviewResponse } from '../../../common/types/alerts';
import { composeValidators } from '../../../common';
import { requiredValidator, timeIntervalInputValidator } from '../../../common/util/validators';
import { invalidTimeIntervalMessage } from '../../application/jobs/new_job/common/job_validator/util';
import { ALERT_PREVIEW_SAMPLE_SIZE } from '../../../common/constants/alerts';

export interface PreviewAlertConditionProps {
alertingApiService: AlertingApiService;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
/*
* 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 RuleTypeParamsExpressionProps,
type TriggersAndActionsUIPublicPluginSetup,
} from '@kbn/triggers-actions-ui-plugin/public';
import { i18n } from '@kbn/i18n';
import React, { lazy } from 'react';
import type { MlCapabilities } from '../../../common/types/capabilities';
import type { MlCoreSetup } from '../../plugin';
import { ML_ALERT_TYPES } from '../../../common';
import type { MlAnomalyDetectionAlertParams } from '../../../common/types/alerts';
import { validateLookbackInterval, validateTopNBucket } from '../validators';

export function registerAnomalyDetectionRule(
triggersActionsUi: TriggersAndActionsUIPublicPluginSetup,
getStartServices: MlCoreSetup['getStartServices'],
mlCapabilities: MlCapabilities
) {
triggersActionsUi.ruleTypeRegistry.register({
id: ML_ALERT_TYPES.ANOMALY_DETECTION,
description: i18n.translate('xpack.ml.alertTypes.anomalyDetection.description', {
defaultMessage: 'Alert when anomaly detection jobs results match the condition.',
}),
iconClass: 'bell',
documentationUrl(docLinks) {
return docLinks.links.ml.alertingRules;
},
ruleParamsExpression: (props: RuleTypeParamsExpressionProps<MlAnomalyDetectionAlertParams>) => {
const MlAlertTrigger = lazy(() => import('./ml_anomaly_alert_trigger'));
return (
<MlAlertTrigger
{...props}
getStartServices={getStartServices}
mlCapabilities={mlCapabilities}
/>
);
},
validate: (ruleParams: MlAnomalyDetectionAlertParams) => {
const validationResult = {
errors: {
jobSelection: new Array<string>(),
severity: new Array<string>(),
resultType: new Array<string>(),
topNBuckets: new Array<string>(),
lookbackInterval: new Array<string>(),
} as Record<keyof MlAnomalyDetectionAlertParams, string[]>,
};

if (!ruleParams.jobSelection?.jobIds?.length && !ruleParams.jobSelection?.groupIds?.length) {
validationResult.errors.jobSelection.push(
i18n.translate('xpack.ml.alertTypes.anomalyDetection.jobSelection.errorMessage', {
defaultMessage: 'Job selection is required',
})
);
}

// Since 7.13 we support single job selection only
if (
(Array.isArray(ruleParams.jobSelection?.groupIds) &&
ruleParams.jobSelection?.groupIds.length > 0) ||
(Array.isArray(ruleParams.jobSelection?.jobIds) &&
ruleParams.jobSelection?.jobIds.length > 1)
) {
validationResult.errors.jobSelection.push(
i18n.translate('xpack.ml.alertTypes.anomalyDetection.singleJobSelection.errorMessage', {
defaultMessage: 'Only one job per rule is allowed',
})
);
}

if (ruleParams.severity === undefined) {
validationResult.errors.severity.push(
i18n.translate('xpack.ml.alertTypes.anomalyDetection.severity.errorMessage', {
defaultMessage: 'Anomaly severity is required',
})
);
}

if (ruleParams.resultType === undefined) {
validationResult.errors.resultType.push(
i18n.translate('xpack.ml.alertTypes.anomalyDetection.resultType.errorMessage', {
defaultMessage: 'Result type is required',
})
);
}

if (!!ruleParams.lookbackInterval && validateLookbackInterval(ruleParams.lookbackInterval)) {
validationResult.errors.lookbackInterval.push(
i18n.translate('xpack.ml.alertTypes.anomalyDetection.lookbackInterval.errorMessage', {
defaultMessage: 'Lookback interval is invalid',
})
);
}

if (
typeof ruleParams.topNBuckets === 'number' &&
validateTopNBucket(ruleParams.topNBuckets)
) {
validationResult.errors.topNBuckets.push(
i18n.translate('xpack.ml.alertTypes.anomalyDetection.topNBuckets.errorMessage', {
defaultMessage: 'Number of buckets is invalid',
})
);
}

return validationResult;
},
requiresAppContext: false,
defaultActionMessage: i18n.translate(
'xpack.ml.alertTypes.anomalyDetection.defaultActionMessage',
{
defaultMessage: `[\\{\\{rule.name\\}\\}] Elastic Stack Machine Learning Alert:
- Job IDs: \\{\\{context.jobIds\\}\\}
- Time: \\{\\{context.timestampIso8601\\}\\}
- Anomaly score: \\{\\{context.score\\}\\}
\\{\\{context.message\\}\\}
\\{\\{#context.topInfluencers.length\\}\\}
Top influencers:
\\{\\{#context.topInfluencers\\}\\}
\\{\\{influencer_field_name\\}\\} = \\{\\{influencer_field_value\\}\\} [\\{\\{score\\}\\}]
\\{\\{/context.topInfluencers\\}\\}
\\{\\{/context.topInfluencers.length\\}\\}
\\{\\{#context.topRecords.length\\}\\}
Top records:
\\{\\{#context.topRecords\\}\\}
\\{\\{function\\}\\}(\\{\\{field_name\\}\\}) \\{\\{by_field_value\\}\\}\\{\\{over_field_value\\}\\}\\{\\{partition_field_value\\}\\} [\\{\\{score\\}\\}]. Typical: \\{\\{typical\\}\\}, Actual: \\{\\{actual\\}\\}
\\{\\{/context.topRecords\\}\\}
\\{\\{/context.topRecords.length\\}\\}
\\{\\{! Replace kibanaBaseUrl if not configured in Kibana \\}\\}
[Open in Anomaly Explorer](\\{\\{\\{kibanaBaseUrl\\}\\}\\}\\{\\{\\{context.anomalyExplorerUrl\\}\\}\\})
`,
}
),
});
}
Loading

0 comments on commit 085da72

Please sign in to comment.