Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
darnautov committed Dec 27, 2023
1 parent 392d53c commit 527062d
Show file tree
Hide file tree
Showing 10 changed files with 189 additions and 140 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 { 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 { 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 { 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,25 +12,25 @@ 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 { 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 { 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 {
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 { 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>;
Expand Down Expand Up @@ -159,6 +159,7 @@ const MlAnomalyAlertTrigger: FC<MlAnomalyAlertTriggerProps> = ({
return (
<EuiForm data-test-subj={'mlAnomalyAlertForm'}>
<JobSelectorControl
allowCreateNew
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,131 @@
/*
* 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 { TriggersAndActionsUIPublicPluginSetup } from '@kbn/triggers-actions-ui-plugin/public';
import { PluginSetupContract as AlertingSetup } from '@kbn/alerting-plugin/public';
import { i18n } from '@kbn/i18n';
import { lazy } from 'react';
import { ML_ALERT_TYPES } from '../../../common';
import type { MlAnomalyDetectionAlertParams } from '../../../common/types/alerts';
import { validateLookbackInterval, validateTopNBucket } from '../validators';

export function registerAnomalyDetectionRule(
triggersActionsUi: TriggersAndActionsUIPublicPluginSetup,
alerting?: AlertingSetup
) {
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: lazy(() => import('./ml_anomaly_alert_trigger')),
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\\}\\}\\})
`,
}
),
});
}
23 changes: 22 additions & 1 deletion x-pack/plugins/ml/public/alerting/job_selector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ export interface JobSelectorControlProps {
* Allows selecting all jobs, even those created afterward.
*/
allowSelectAll?: boolean;
/** Adds an option to create a new anomaly detection job */
allowCreateNew?: boolean;
/**
* Available options to select. By default suggest all existing jobs.
*/
Expand All @@ -47,6 +49,7 @@ export const JobSelectorControl: FC<JobSelectorControlProps> = ({
multiSelect = false,
label,
allowSelectAll = false,
allowCreateNew = false,
options: defaultOptions,
}) => {
const [options, setOptions] = useState<Array<EuiComboBoxOptionOption<string>>>([]);
Expand All @@ -69,6 +72,7 @@ export const JobSelectorControl: FC<JobSelectorControlProps> = ({
jobIdOptions.forEach((v) => {
jobIds.add(v);
});

groupIdOptions.forEach((v) => {
groupIds.add(v);
});
Expand All @@ -91,11 +95,24 @@ export const JobSelectorControl: FC<JobSelectorControlProps> = ({
},
]
: []),

{
label: i18n.translate('xpack.ml.jobSelector.jobOptionsLabel', {
defaultMessage: 'Jobs',
}),
options: jobIdOptions.map((v) => ({ label: v })),
options: [
...(allowCreateNew
? [
{
label: i18n.translate('xpack.ml.jobSelector.createNewLabel', {
defaultMessage: '---Create new---',
}),
value: 'createNew',
},
]
: []),
...jobIdOptions.map((v) => ({ label: v })),
],
},
...(multiSelect
? [
Expand All @@ -122,6 +139,10 @@ export const JobSelectorControl: FC<JobSelectorControlProps> = ({
return;
}

if (selectionUpdate.some((selectedOption) => selectedOption.value === 'createNew')) {
// Redirect to the job wizard page
}

const selectedJobIds: JobId[] = [];
const selectedGroupIds: string[] = [];
selectionUpdate.forEach(({ label: selectedLabel }: { label: string }) => {
Expand Down
Loading

0 comments on commit 527062d

Please sign in to comment.