-
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
[APM] Anomaly detection integration with transaction duration chart #71230
Merged
ogupte
merged 6 commits into
elastic:master
from
ogupte:apm-70859-transaction-duration-anomaly-detection
Jul 13, 2020
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
e5ea84c
Reintroduces the previous anomaly detection ML integration back into the
ogupte 0020367
PR feedback
ogupte c2c7f6a
Merge branch 'master' into apm-70859-transaction-duration-anomaly-det…
elasticmachine d3824d0
Code improvements from PR feedback
ogupte 7f10bcc
handle errors thrown when fetching ml job for current environment
ogupte 4d33aa2
Merge branch 'master' into apm-70859-transaction-duration-anomaly-det…
elasticmachine 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
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
93 changes: 93 additions & 0 deletions
93
x-pack/plugins/apm/server/lib/transactions/charts/get_anomaly_data/fetcher.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,93 @@ | ||
/* | ||
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
* or more contributor license agreements. Licensed under the Elastic License; | ||
* you may not use this file except in compliance with the Elastic License. | ||
*/ | ||
|
||
import { Logger } from 'kibana/server'; | ||
import { PromiseReturnType } from '../../../../../../observability/typings/common'; | ||
import { Setup, SetupTimeRange } from '../../../helpers/setup_request'; | ||
|
||
export type ESResponse = Exclude< | ||
PromiseReturnType<typeof anomalySeriesFetcher>, | ||
undefined | ||
>; | ||
|
||
export async function anomalySeriesFetcher({ | ||
serviceName, | ||
transactionType, | ||
intervalString, | ||
mlBucketSize, | ||
setup, | ||
jobId, | ||
logger, | ||
}: { | ||
serviceName: string; | ||
transactionType: string; | ||
intervalString: string; | ||
mlBucketSize: number; | ||
setup: Setup & SetupTimeRange; | ||
jobId: string; | ||
logger: Logger; | ||
}) { | ||
const { ml, start, end } = setup; | ||
if (!ml) { | ||
return; | ||
} | ||
|
||
// move the start back with one bucket size, to ensure to get anomaly data in the beginning | ||
// this is required because ML has a minimum bucket size (default is 900s) so if our buckets are smaller, we might have several null buckets in the beginning | ||
const newStart = start - mlBucketSize * 1000; | ||
|
||
const params = { | ||
body: { | ||
size: 0, | ||
query: { | ||
bool: { | ||
filter: [ | ||
{ term: { job_id: jobId } }, | ||
{ exists: { field: 'bucket_span' } }, | ||
{ term: { result_type: 'model_plot' } }, | ||
{ term: { partition_field_value: serviceName } }, | ||
{ term: { by_field_value: transactionType } }, | ||
{ | ||
range: { | ||
timestamp: { gte: newStart, lte: end, format: 'epoch_millis' }, | ||
}, | ||
}, | ||
], | ||
}, | ||
}, | ||
aggs: { | ||
ml_avg_response_times: { | ||
date_histogram: { | ||
field: 'timestamp', | ||
fixed_interval: intervalString, | ||
min_doc_count: 0, | ||
extended_bounds: { min: newStart, max: end }, | ||
}, | ||
aggs: { | ||
anomaly_score: { max: { field: 'anomaly_score' } }, | ||
lower: { min: { field: 'model_lower' } }, | ||
upper: { max: { field: 'model_upper' } }, | ||
}, | ||
}, | ||
}, | ||
}, | ||
}; | ||
|
||
try { | ||
const response = await ml.mlSystem.mlAnomalySearch(params); | ||
return response; | ||
} catch (err) { | ||
const isHttpError = 'statusCode' in err; | ||
if (isHttpError) { | ||
logger.info( | ||
`Status code "${err.statusCode}" while retrieving ML anomalies for APM` | ||
); | ||
return; | ||
} | ||
logger.error('An error occurred while retrieving ML anomalies for APM'); | ||
logger.error(err); | ||
} | ||
} |
61 changes: 61 additions & 0 deletions
61
x-pack/plugins/apm/server/lib/transactions/charts/get_anomaly_data/get_ml_bucket_size.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,61 @@ | ||
/* | ||
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
* or more contributor license agreements. Licensed under the Elastic License; | ||
* you may not use this file except in compliance with the Elastic License. | ||
*/ | ||
|
||
import { Logger } from 'kibana/server'; | ||
import { Setup, SetupTimeRange } from '../../../helpers/setup_request'; | ||
|
||
interface IOptions { | ||
setup: Setup & SetupTimeRange; | ||
jobId: string; | ||
logger: Logger; | ||
} | ||
|
||
interface ESResponse { | ||
bucket_span: number; | ||
} | ||
|
||
export async function getMlBucketSize({ | ||
setup, | ||
jobId, | ||
logger, | ||
}: IOptions): Promise<number | undefined> { | ||
const { ml, start, end } = setup; | ||
if (!ml) { | ||
return; | ||
} | ||
|
||
const params = { | ||
body: { | ||
_source: 'bucket_span', | ||
size: 1, | ||
terminateAfter: 1, | ||
query: { | ||
bool: { | ||
filter: [ | ||
{ term: { job_id: jobId } }, | ||
{ exists: { field: 'bucket_span' } }, | ||
{ | ||
range: { | ||
timestamp: { gte: start, lte: end, format: 'epoch_millis' }, | ||
}, | ||
}, | ||
], | ||
}, | ||
}, | ||
}, | ||
}; | ||
|
||
try { | ||
const resp = await ml.mlSystem.mlAnomalySearch<ESResponse>(params); | ||
return resp.hits.hits[0]?._source.bucket_span; | ||
} catch (err) { | ||
const isHttpError = 'statusCode' in err; | ||
if (isHttpError) { | ||
return; | ||
} | ||
logger.error(err); | ||
} | ||
} |
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 |
---|---|---|
|
@@ -3,32 +3,37 @@ | |
* or more contributor license agreements. Licensed under the Elastic License; | ||
* you may not use this file except in compliance with the Elastic License. | ||
*/ | ||
|
||
import { Logger } from 'kibana/server'; | ||
import { isNumber } from 'lodash'; | ||
import { getBucketSize } from '../../../helpers/get_bucket_size'; | ||
import { | ||
Setup, | ||
SetupTimeRange, | ||
SetupUIFilters, | ||
} from '../../../helpers/setup_request'; | ||
import { Coordinate, RectCoordinate } from '../../../../../typings/timeseries'; | ||
|
||
interface AnomalyTimeseries { | ||
anomalyBoundaries: Coordinate[]; | ||
anomalyScore: RectCoordinate[]; | ||
} | ||
import { anomalySeriesFetcher } from './fetcher'; | ||
import { getMlBucketSize } from './get_ml_bucket_size'; | ||
import { anomalySeriesTransform } from './transform'; | ||
import { getMLJobIds } from '../../../service_map/get_service_anomalies'; | ||
import { UIFilters } from '../../../../../typings/ui_filters'; | ||
|
||
export async function getAnomalySeries({ | ||
serviceName, | ||
transactionType, | ||
transactionName, | ||
timeSeriesDates, | ||
setup, | ||
logger, | ||
uiFilters, | ||
}: { | ||
serviceName: string; | ||
transactionType: string | undefined; | ||
transactionName: string | undefined; | ||
timeSeriesDates: number[]; | ||
setup: Setup & SetupTimeRange & SetupUIFilters; | ||
}): Promise<void | AnomalyTimeseries> { | ||
logger: Logger; | ||
uiFilters: UIFilters; | ||
}) { | ||
// don't fetch anomalies for transaction details page | ||
if (transactionName) { | ||
return; | ||
|
@@ -39,8 +44,12 @@ export async function getAnomalySeries({ | |
return; | ||
} | ||
|
||
// don't fetch anomalies if uiFilters are applied | ||
if (setup.uiFiltersES.length > 0) { | ||
// don't fetch anomalies if unknown uiFilters are applied | ||
const knownFilters = ['environment', 'serviceName']; | ||
const uiFilterNames = Object.keys(uiFilters); | ||
if ( | ||
uiFilterNames.some((uiFilterName) => !knownFilters.includes(uiFilterName)) | ||
) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Thanks much better 👍 |
||
return; | ||
} | ||
|
||
|
@@ -55,6 +64,45 @@ export async function getAnomalySeries({ | |
return; | ||
} | ||
|
||
// TODO [APM ML] return a series of anomaly scores, upper & lower bounds for the given timeSeriesDates | ||
return; | ||
let mlJobIds: string[] = []; | ||
try { | ||
mlJobIds = await getMLJobIds(setup.ml, uiFilters.environment); | ||
} catch (error) { | ||
logger.error(error); | ||
return; | ||
} | ||
|
||
// don't fetch anomalies if there are isn't exaclty 1 ML job match for the given environment | ||
if (mlJobIds.length !== 1) { | ||
return; | ||
} | ||
const jobId = mlJobIds[0]; | ||
|
||
const mlBucketSize = await getMlBucketSize({ setup, jobId, logger }); | ||
if (!isNumber(mlBucketSize)) { | ||
return; | ||
} | ||
|
||
const { start, end } = setup; | ||
const { intervalString, bucketSize } = getBucketSize(start, end, 'auto'); | ||
|
||
const esResponse = await anomalySeriesFetcher({ | ||
serviceName, | ||
transactionType, | ||
intervalString, | ||
mlBucketSize, | ||
setup, | ||
jobId, | ||
logger, | ||
}); | ||
|
||
if (esResponse && mlBucketSize > 0) { | ||
return anomalySeriesTransform( | ||
esResponse, | ||
mlBucketSize, | ||
bucketSize, | ||
timeSeriesDates, | ||
jobId | ||
); | ||
} | ||
} |
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.
Perhaps add
terminateAfter: 1
since we only need a single result