Skip to content

Commit

Permalink
Merge remote-tracking branch 'upstream/7.9' into backport/7.9/pr-73638
Browse files Browse the repository at this point in the history
  • Loading branch information
ogupte committed Jul 30, 2020
2 parents a57a3f1 + b710f75 commit ce8c17d
Show file tree
Hide file tree
Showing 38 changed files with 614 additions and 300 deletions.
23 changes: 5 additions & 18 deletions x-pack/plugins/apm/common/anomaly_detection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,18 @@ export interface ServiceAnomalyStats {
jobId?: string;
}

export const MLErrorMessages: Record<ErrorCode, string> = {
INSUFFICIENT_LICENSE: i18n.translate(
'xpack.apm.anomaly_detection.error.insufficient_license',
export const ML_ERRORS = {
INVALID_LICENSE: i18n.translate(
'xpack.apm.anomaly_detection.error.invalid_license',
{
defaultMessage:
'You must have a platinum license to use Anomaly Detection',
defaultMessage: `To use anomaly detection, you must be subscribed to an Elastic Platinum license. With it, you'll be able to monitor your services with the aid of machine learning.`,
}
),
MISSING_READ_PRIVILEGES: i18n.translate(
'xpack.apm.anomaly_detection.error.missing_read_privileges',
{
defaultMessage:
'You must have "read" privileges to Machine Learning in order to view Anomaly Detection jobs',
'You must have "read" privileges to Machine Learning and APM in order to view Anomaly Detection jobs',
}
),
MISSING_WRITE_PRIVILEGES: i18n.translate(
Expand All @@ -47,16 +46,4 @@ export const MLErrorMessages: Record<ErrorCode, string> = {
defaultMessage: 'Machine learning is not available in the selected space',
}
),
UNEXPECTED: i18n.translate('xpack.apm.anomaly_detection.error.unexpected', {
defaultMessage: 'An unexpected error occurred',
}),
};

export enum ErrorCode {
INSUFFICIENT_LICENSE = 'INSUFFICIENT_LICENSE',
MISSING_READ_PRIVILEGES = 'MISSING_READ_PRIVILEGES',
MISSING_WRITE_PRIVILEGES = 'MISSING_WRITE_PRIVILEGES',
ML_NOT_AVAILABLE = 'ML_NOT_AVAILABLE',
ML_NOT_AVAILABLE_IN_SPACE = 'ML_NOT_AVAILABLE_IN_SPACE',
UNEXPECTED = 'UNEXPECTED',
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import {
EuiEmptyPrompt,
} from '@elastic/eui';
import { i18n } from '@kbn/i18n';
import { MLErrorMessages } from '../../../../../common/anomaly_detection';
import { ML_ERRORS } from '../../../../../common/anomaly_detection';
import { useFetcher, FETCH_STATUS } from '../../../../hooks/useFetcher';
import { useApmPluginContext } from '../../../../hooks/useApmPluginContext';
import { createJobs } from './create_jobs';
Expand Down Expand Up @@ -65,7 +65,7 @@ export const AddEnvironments = ({
<EuiPanel>
<EuiEmptyPrompt
iconType="alert"
body={<>{MLErrorMessages.MISSING_WRITE_PRIVILEGES}</>}
body={<>{ML_ERRORS.MISSING_WRITE_PRIVILEGES}</>}
/>
</EuiPanel>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

import { i18n } from '@kbn/i18n';
import { NotificationsStart } from 'kibana/public';
import { MLErrorMessages } from '../../../../../common/anomaly_detection';
import { callApmApi } from '../../../../services/rest/createCallApmApi';

const errorToastTitle = i18n.translate(
Expand All @@ -27,31 +26,19 @@ export async function createJobs({
toasts: NotificationsStart['toasts'];
}) {
try {
const res = await callApmApi({
await callApmApi({
pathname: '/api/apm/settings/anomaly-detection/jobs',
method: 'POST',
params: {
body: { environments },
},
});

// a known error occurred
if (res?.errorCode) {
toasts.addDanger({
title: errorToastTitle,
text: MLErrorMessages[res.errorCode],
});
return false;
}

// job created successfully
toasts.addSuccess({
title: successToastTitle,
text: getSuccessToastMessage(environments),
});
return true;

// an unknown/unexpected error occurred
} catch (error) {
toasts.addDanger({
title: errorToastTitle,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import React, { useState } from 'react';
import { EuiTitle, EuiSpacer, EuiText } from '@elastic/eui';
import { i18n } from '@kbn/i18n';
import { EuiPanel, EuiEmptyPrompt } from '@elastic/eui';
import { MLErrorMessages } from '../../../../../common/anomaly_detection';
import { ML_ERRORS } from '../../../../../common/anomaly_detection';
import { useApmPluginContext } from '../../../../hooks/useApmPluginContext';
import { JobsList } from './jobs_list';
import { AddEnvironments } from './add_environments';
Expand All @@ -25,7 +25,6 @@ export type AnomalyDetectionApiResponse = APIReturnType<
const DEFAULT_VALUE: AnomalyDetectionApiResponse = {
jobs: [],
hasLegacyJobs: false,
errorCode: undefined,
};

export const AnomalyDetection = () => {
Expand All @@ -49,15 +48,7 @@ export const AnomalyDetection = () => {
if (!hasValidLicense) {
return (
<EuiPanel>
<LicensePrompt
text={i18n.translate(
'xpack.apm.settings.anomaly_detection.license.text',
{
defaultMessage:
"To use anomaly detection, you must be subscribed to an Elastic Platinum license. With it, you'll have the ability monitor your services with the aid of machine learning.",
}
)}
/>
<LicensePrompt text={ML_ERRORS.INVALID_LICENSE} />
</EuiPanel>
);
}
Expand All @@ -67,7 +58,7 @@ export const AnomalyDetection = () => {
<EuiPanel>
<EuiEmptyPrompt
iconType="alert"
body={<>{MLErrorMessages.MISSING_READ_PRIVILEGES}</>}
body={<>{ML_ERRORS.MISSING_READ_PRIVILEGES}</>}
/>
</EuiPanel>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,6 @@ import {
} from '@elastic/eui';
import { i18n } from '@kbn/i18n';
import { FormattedMessage } from '@kbn/i18n/react';
import {
MLErrorMessages,
ErrorCode,
} from '../../../../../common/anomaly_detection';
import { FETCH_STATUS } from '../../../../hooks/useFetcher';
import { ITableColumn, ManagedTable } from '../../../shared/ManagedTable';
import { LoadingStatePrompt } from '../../../shared/LoadingStatePrompt';
Expand Down Expand Up @@ -65,8 +61,9 @@ interface Props {
status: FETCH_STATUS;
onAddEnvironments: () => void;
}
export const JobsList = ({ data, status, onAddEnvironments }: Props) => {
const { jobs, hasLegacyJobs, errorCode } = data;

export function JobsList({ data, status, onAddEnvironments }: Props) {
const { jobs, hasLegacyJobs } = data;

return (
<EuiPanel>
Expand Down Expand Up @@ -115,10 +112,7 @@ export const JobsList = ({ data, status, onAddEnvironments }: Props) => {
</EuiText>
<EuiSpacer size="l" />
<ManagedTable
noItemsMessage={getNoItemsMessage({
status,
errorCode,
})}
noItemsMessage={getNoItemsMessage({ status })}
columns={columns}
items={jobs}
/>
Expand All @@ -127,27 +121,16 @@ export const JobsList = ({ data, status, onAddEnvironments }: Props) => {
{hasLegacyJobs && <LegacyJobsCallout />}
</EuiPanel>
);
};
}

function getNoItemsMessage({
status,
errorCode,
}: {
status: FETCH_STATUS;
errorCode?: ErrorCode;
}) {
function getNoItemsMessage({ status }: { status: FETCH_STATUS }) {
// loading state
const isLoading =
status === FETCH_STATUS.PENDING || status === FETCH_STATUS.LOADING;
if (isLoading) {
return <LoadingStatePrompt />;
}

// A known error occured. Show specific error message
if (errorCode) {
return MLErrorMessages[errorCode];
}

// An unexpected error occurred. Show default error message
if (status === FETCH_STATUS.FAILURE) {
return i18n.translate(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ describe('DiscoverLinks', () => {
} as Location
);

expect(href).toEqual(
`/basepath/app/discover#/?_g=(refreshInterval:(pause:true,value:'0'),time:(from:now%2Fw,to:now))&_a=(index:apm_static_index_pattern_id,interval:auto,query:(language:kuery,query:'processor.event:"transaction" AND transaction.id:"8b60bd32ecc6e150" AND trace.id:"8b60bd32ecc6e1506735a8b6cfcf175c"'))`
expect(href).toMatchInlineSnapshot(
`"/basepath/app/discover#/?_g=(refreshInterval:(pause:!t,value:0),time:(from:now/w,to:now))&_a=(index:apm_static_index_pattern_id,interval:auto,query:(language:kuery,query:'processor.event:\\"transaction\\" AND transaction.id:\\"8b60bd32ecc6e150\\" AND trace.id:\\"8b60bd32ecc6e1506735a8b6cfcf175c\\"'))"`
);
});

Expand All @@ -50,8 +50,8 @@ describe('DiscoverLinks', () => {
'?rangeFrom=now/w&rangeTo=now&refreshPaused=true&refreshInterval=0',
} as Location);

expect(href).toEqual(
`/basepath/app/discover#/?_g=(refreshInterval:(pause:true,value:'0'),time:(from:now%2Fw,to:now))&_a=(index:apm_static_index_pattern_id,interval:auto,query:(language:kuery,query:'span.id:"test-span-id"'))`
expect(href).toMatchInlineSnapshot(
`"/basepath/app/discover#/?_g=(refreshInterval:(pause:!t,value:0),time:(from:now/w,to:now))&_a=(index:apm_static_index_pattern_id,interval:auto,query:(language:kuery,query:'span.id:\\"test-span-id\\"'))"`
);
});

Expand All @@ -72,8 +72,8 @@ describe('DiscoverLinks', () => {
} as Location
);

expect(href).toEqual(
`/basepath/app/discover#/?_g=(refreshInterval:(pause:true,value:'0'),time:(from:now%2Fw,to:now))&_a=(index:apm_static_index_pattern_id,interval:auto,query:(language:kuery,query:'service.name:"service-name" AND error.grouping_key:"grouping-key"'),sort:('@timestamp':desc))`
expect(href).toMatchInlineSnapshot(
`"/basepath/app/discover#/?_g=(refreshInterval:(pause:!t,value:0),time:(from:now/w,to:now))&_a=(index:apm_static_index_pattern_id,interval:auto,query:(language:kuery,query:'service.name:\\"service-name\\" AND error.grouping_key:\\"grouping-key\\"'),sort:('@timestamp':desc))"`
);
});

Expand All @@ -95,8 +95,8 @@ describe('DiscoverLinks', () => {
} as Location
);

expect(href).toEqual(
`/basepath/app/discover#/?_g=(refreshInterval:(pause:true,value:'0'),time:(from:now%2Fw,to:now))&_a=(index:apm_static_index_pattern_id,interval:auto,query:(language:kuery,query:'service.name:"service-name" AND error.grouping_key:"grouping-key" AND some:kuery-string'),sort:('@timestamp':desc))`
expect(href).toMatchInlineSnapshot(
`"/basepath/app/discover#/?_g=(refreshInterval:(pause:!t,value:0),time:(from:now/w,to:now))&_a=(index:apm_static_index_pattern_id,interval:auto,query:(language:kuery,query:'service.name:\\"service-name\\" AND error.grouping_key:\\"grouping-key\\" AND some:kuery-string'),sort:('@timestamp':desc))"`
);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ describe('MLJobLink', () => {
);

expect(href).toMatchInlineSnapshot(
`"/basepath/app/ml#/timeseriesexplorer?_g=(ml:(jobIds:!(myservicename-mytransactiontype-high_mean_response_time)),refreshInterval:(pause:true,value:'0'),time:(from:now%2Fw,to:now-4h))"`
`"/basepath/app/ml#/timeseriesexplorer?_g=(ml:(jobIds:!(myservicename-mytransactiontype-high_mean_response_time)),refreshInterval:(pause:!t,value:0),time:(from:now/w,to:now-4h))"`
);
});
it('should produce the correct URL with jobId, serviceName, and transactionType', async () => {
Expand All @@ -41,7 +41,7 @@ describe('MLJobLink', () => {
);

expect(href).toMatchInlineSnapshot(
`"/basepath/app/ml#/timeseriesexplorer?_g=(ml:(jobIds:!(myservicename-mytransactiontype-high_mean_response_time)),refreshInterval:(pause:true,value:'0'),time:(from:now%2Fw,to:now-4h))&_a=(mlTimeSeriesExplorer:(entities:(service.name:opbeans-test,transaction.type:request)))"`
`"/basepath/app/ml#/timeseriesexplorer?_g=(ml:(jobIds:!(myservicename-mytransactiontype-high_mean_response_time)),refreshInterval:(pause:!t,value:0),time:(from:now/w,to:now-4h))&_a=(mlTimeSeriesExplorer:(entities:(service.name:opbeans-test,transaction.type:request),zoom:(from:now/w,to:now-4h)))"`
);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,6 @@ test('MLLink produces the correct URL', async () => {
);

expect(href).toMatchInlineSnapshot(
`"/basepath/app/ml#/some/path?_g=(ml:(jobIds:!(something)),refreshInterval:(pause:true,value:'0'),time:(from:now-5h,to:now-2h))"`
`"/basepath/app/ml#/some/path?_g=(ml:(jobIds:!(something)),refreshInterval:(pause:!t,value:0),time:(from:now-5h,to:now-2h))"`
);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/*
* 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 { useTimeSeriesExplorerHref } from './useTimeSeriesExplorerHref';

jest.mock('../../../../hooks/useApmPluginContext', () => ({
useApmPluginContext: () => ({
core: { http: { basePath: { prepend: (url: string) => url } } },
}),
}));

jest.mock('../../../../hooks/useLocation', () => ({
useLocation: () => ({
search:
'?rangeFrom=2020-07-29T17:27:29.000Z&rangeTo=2020-07-29T18:45:00.000Z&refreshInterval=10000&refreshPaused=true',
}),
}));

describe('useTimeSeriesExplorerHref', () => {
it('correctly encodes time range values', async () => {
const href = useTimeSeriesExplorerHref({
jobId: 'apm-production-485b-high_mean_transaction_duration',
serviceName: 'opbeans-java',
transactionType: 'request',
});

expect(href).toMatchInlineSnapshot(
`"/app/ml#/timeseriesexplorer?_g=(ml:(jobIds:!(apm-production-485b-high_mean_transaction_duration)),refreshInterval:(pause:!t,value:10000),time:(from:'2020-07-29T17:27:29.000Z',to:'2020-07-29T18:45:00.000Z'))&_a=(mlTimeSeriesExplorer:(entities:(service.name:opbeans-java,transaction.type:request),zoom:(from:'2020-07-29T17:27:29.000Z',to:'2020-07-29T18:45:00.000Z')))"`
);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,14 @@ export function useTimeSeriesExplorerHref({
}) {
const { core } = useApmPluginContext();
const location = useLocation();
const { time, refreshInterval } = getTimepickerRisonData(location.search);

const search = querystring.stringify(
{
_g: rison.encode({
ml: { jobIds: [jobId] },
...getTimepickerRisonData(location.search),
time,
refreshInterval,
}),
...(serviceName && transactionType
? {
Expand All @@ -37,6 +39,7 @@ export function useTimeSeriesExplorerHref({
'service.name': serviceName,
'transaction.type': transactionType,
},
zoom: time,
},
}),
}
Expand Down
Loading

0 comments on commit ce8c17d

Please sign in to comment.