Skip to content

Commit

Permalink
[Uptime] Migrate to new es client (#82003)
Browse files Browse the repository at this point in the history
* migrate to new es client

* fix tests

* fix type

* types

* types

* update

* update

* update

* upadte

* update snaps

Co-authored-by: Kibana Machine <[email protected]>
  • Loading branch information
shahzad31 and kibanamachine authored Nov 6, 2020
1 parent b19a342 commit a6b2a6e
Show file tree
Hide file tree
Showing 47 changed files with 838 additions and 615 deletions.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,9 @@ describe('EmptyState component', () => {

it(`renders error message when an error occurs`, () => {
const errors: IHttpFetchError[] = [
new HttpFetchError('There was an error fetching your data.', 'error', {} as any),
new HttpFetchError('There was an error fetching your data.', 'error', {} as any, {} as any, {
body: { message: 'There was an error fetching your data.' },
}),
];
const component = mountWithRouter(
<EmptyStateComponent statesIndexStatus={null} errors={errors} loading={false}>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ interface EmptyStateErrorProps {

export const EmptyStateError = ({ errors }: EmptyStateErrorProps) => {
const unauthorized = errors.find(
(error: Error) => error.message && error.message.includes('unauthorized')
(error: IHttpFetchError) => error.message && error.message.includes('unauthorized')
);

return (
Expand Down Expand Up @@ -46,7 +46,9 @@ export const EmptyStateError = ({ errors }: EmptyStateErrorProps) => {
body={
<Fragment>
{!unauthorized &&
errors.map((error: Error) => <p key={error.message}>{error.message}</p>)}
errors.map((error: IHttpFetchError) => (
<p key={error.body.message}>{error.body.message || error.message}</p>
))}
</Fragment>
}
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { MonitorListComponent, noItemsMessage } from '../monitor_list';
import { renderWithRouter, shallowWithRouter } from '../../../../lib';
import * as redux from 'react-redux';
import moment from 'moment';
import { IHttpFetchError } from '../../../../../../../../src/core/public';

jest.mock('@elastic/eui/lib/services/accessibility/html_id_generator', () => {
return {
Expand Down Expand Up @@ -187,7 +188,11 @@ describe('MonitorList component', () => {
it('renders error list', () => {
const component = shallowWithRouter(
<MonitorListComponent
monitorList={{ list: getMonitorList(), error: new Error('foo message'), loading: false }}
monitorList={{
list: getMonitorList(),
error: new Error('foo message') as IHttpFetchError,
loading: false,
}}
pageSize={10}
setPageSize={jest.fn()}
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ export const MonitorListComponent: ({
<EuiSpacer size="m" />
<EuiBasicTable
aria-label={labels.getDescriptionLabel(items.length)}
error={error?.message}
error={error?.body?.message || error?.message}
loading={loading}
isExpandable={true}
hasActions={true}
Expand Down
7 changes: 4 additions & 3 deletions x-pack/plugins/uptime/public/state/reducers/monitor_list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@
*/

import { handleActions, Action } from 'redux-actions';
import { IHttpFetchError } from 'src/core/public';
import { getMonitorList, getMonitorListSuccess, getMonitorListFailure } from '../actions';
import { MonitorSummariesResult } from '../../../common/runtime_types';

export interface MonitorList {
error?: Error;
error?: IHttpFetchError;
loading: boolean;
list: MonitorSummariesResult;
}
Expand All @@ -24,7 +25,7 @@ export const initialState: MonitorList = {
loading: false,
};

type Payload = MonitorSummariesResult & Error;
type Payload = MonitorSummariesResult & IHttpFetchError;

export const monitorListReducer = handleActions<MonitorList, Payload>(
{
Expand All @@ -41,7 +42,7 @@ export const monitorListReducer = handleActions<MonitorList, Payload>(
error: undefined,
list: { ...action.payload },
}),
[String(getMonitorListFailure)]: (state: MonitorList, action: Action<Error>) => ({
[String(getMonitorListFailure)]: (state: MonitorList, action: Action<IHttpFetchError>) => ({
...state,
error: action.payload,
loading: false,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,20 @@ import {
IRouter,
SavedObjectsClientContract,
ISavedObjectsRepository,
ILegacyScopedClusterClient,
IScopedClusterClient,
ElasticsearchClient,
} from 'src/core/server';
import { UMKibanaRoute } from '../../../rest_api';
import { PluginSetupContract } from '../../../../../features/server';
import { DynamicSettings } from '../../../../common/runtime_types';
import { MlPluginSetup as MlSetup } from '../../../../../ml/server';

export type ESAPICaller = ILegacyScopedClusterClient['callAsCurrentUser'];

export type UMElasticsearchQueryFn<P, R = any> = (
params: { callES: ESAPICaller; dynamicSettings: DynamicSettings } & P
params: {
callES: ElasticsearchClient;
esClient?: IScopedClusterClient;
dynamicSettings: DynamicSettings;
} & P
) => Promise<R>;

export type UMSavedObjectsQueryFn<T = any, P = undefined> = (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,14 @@
*/

import moment from 'moment';
import { ISavedObjectsRepository, SavedObjectsClientContract } from 'kibana/server';
import {
ISavedObjectsRepository,
ILegacyScopedClusterClient,
SavedObjectsClientContract,
ElasticsearchClient,
} from 'kibana/server';
import { CollectorFetchContext, UsageCollectionSetup } from 'src/plugins/usage_collection/server';
import { PageViewParams, UptimeTelemetry, Usage } from './types';
import { ESAPICaller } from '../framework';
import { savedObjectsAdapter } from '../../saved_objects';

interface UptimeTelemetryCollector {
Expand All @@ -21,6 +25,8 @@ const BUCKET_SIZE = 3600;
const BUCKET_NUMBER = 24;

export class KibanaTelemetryAdapter {
public static callCluster: ILegacyScopedClusterClient['callAsCurrentUser'] | ElasticsearchClient;

public static registerUsageCollector = (
usageCollector: UsageCollectionSetup,
getSavedObjectsClient: () => ISavedObjectsRepository | undefined
Expand Down Expand Up @@ -125,7 +131,7 @@ export class KibanaTelemetryAdapter {
}

public static async countNoOfUniqueMonitorAndLocations(
callCluster: ESAPICaller,
callCluster: ILegacyScopedClusterClient['callAsCurrentUser'] | ElasticsearchClient,
savedObjectsClient: ISavedObjectsRepository | SavedObjectsClientContract
) {
const dynamicSettings = await savedObjectsAdapter.getUptimeDynamicSettings(savedObjectsClient);
Expand Down Expand Up @@ -187,7 +193,11 @@ export class KibanaTelemetryAdapter {
},
};

const result = await callCluster('search', params);
const { body: result } =
typeof callCluster === 'function'
? await callCluster('search', params)
: await callCluster.search(params);

const numberOfUniqueMonitors: number = result?.aggregations?.unique_monitors?.value ?? 0;
const numberOfUniqueLocations: number = result?.aggregations?.unique_locations?.value ?? 0;
const monitorNameStats: any = result?.aggregations?.monitor_name;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ const mockOptions = (
services = alertsMock.createAlertServices(),
state = {}
): any => {
services.scopedClusterClient = jest.fn() as any;

services.savedObjectsClient.get.mockResolvedValue({
id: '',
type: '',
Expand Down Expand Up @@ -282,7 +284,8 @@ describe('status check alert', () => {
expect.assertions(5);
toISOStringSpy.mockImplementation(() => 'foo date string');
const mockGetter: jest.Mock<GetMonitorStatusResult[]> = jest.fn();
mockGetter.mockReturnValue([

mockGetter.mockReturnValueOnce([
{
monitorId: 'first',
location: 'harrisburg',
Expand Down Expand Up @@ -326,6 +329,7 @@ describe('status check alert', () => {
const state = await alert.executor(options);
const [{ value: alertInstanceMock }] = alertServices.alertInstanceFactory.mock.results;
expect(mockGetter).toHaveBeenCalledTimes(1);

expect(mockGetter.mock.calls[0]).toMatchInlineSnapshot(`
Array [
Object {
Expand Down
103 changes: 50 additions & 53 deletions x-pack/plugins/uptime/server/lib/alerts/duration_anomaly.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@ import { ACTION_GROUP_DEFINITIONS } from '../../../common/constants/alerts';
import { commonStateTranslations, durationAnomalyTranslations } from './translations';
import { AnomaliesTableRecord } from '../../../../ml/common/types/anomalies';
import { getSeverityType } from '../../../../ml/common/util/anomaly_utils';
import { savedObjectsAdapter } from '../saved_objects';
import { UptimeCorePlugins } from '../adapters/framework';
import { UptimeAlertTypeFactory } from './types';
import { Ping } from '../../../common/runtime_types/ping';
import { getMLJobId } from '../../../common/lib';
import { getLatestMonitor } from '../requests/get_latest_monitor';
import { uptimeAlertWrapper } from './uptime_alert_wrapper';

const { DURATION_ANOMALY } = ACTION_GROUP_DEFINITIONS;

Expand Down Expand Up @@ -61,61 +61,58 @@ const getAnomalies = async (
);
};

export const durationAnomalyAlertFactory: UptimeAlertTypeFactory = (_server, _libs, plugins) => ({
id: 'xpack.uptime.alerts.durationAnomaly',
name: durationAnomalyTranslations.alertFactoryName,
validate: {
params: schema.object({
monitorId: schema.string(),
severity: schema.number(),
}),
},
defaultActionGroupId: DURATION_ANOMALY.id,
actionGroups: [
{
id: DURATION_ANOMALY.id,
name: DURATION_ANOMALY.name,
export const durationAnomalyAlertFactory: UptimeAlertTypeFactory = (_server, _libs, plugins) =>
uptimeAlertWrapper({
id: 'xpack.uptime.alerts.durationAnomaly',
name: durationAnomalyTranslations.alertFactoryName,
validate: {
params: schema.object({
monitorId: schema.string(),
severity: schema.number(),
}),
},
],
actionVariables: {
context: [],
state: [...durationAnomalyTranslations.actionVariables, ...commonStateTranslations],
},
producer: 'uptime',
async executor(options) {
const {
services: { alertInstanceFactory, callCluster, savedObjectsClient },
state,
params,
} = options;
defaultActionGroupId: DURATION_ANOMALY.id,
actionGroups: [
{
id: DURATION_ANOMALY.id,
name: DURATION_ANOMALY.name,
},
],
actionVariables: {
context: [],
state: [...durationAnomalyTranslations.actionVariables, ...commonStateTranslations],
},
async executor({ options, esClient, savedObjectsClient, dynamicSettings }) {
const {
services: { alertInstanceFactory },
state,
params,
} = options;

const { anomalies } =
(await getAnomalies(plugins, savedObjectsClient, params, state.lastCheckedAt)) ?? {};
const { anomalies } =
(await getAnomalies(plugins, savedObjectsClient, params, state.lastCheckedAt)) ?? {};

const foundAnomalies = anomalies?.length > 0;
const foundAnomalies = anomalies?.length > 0;

if (foundAnomalies) {
const dynamicSettings = await savedObjectsAdapter.getUptimeDynamicSettings(
savedObjectsClient
);
const monitorInfo = await getLatestMonitor({
dynamicSettings,
callES: callCluster,
dateStart: 'now-15m',
dateEnd: 'now',
monitorId: params.monitorId,
});
anomalies.forEach((anomaly, index) => {
const alertInstance = alertInstanceFactory(DURATION_ANOMALY.id + index);
const summary = getAnomalySummary(anomaly, monitorInfo);
alertInstance.replaceState({
...updateState(state, false),
...summary,
if (foundAnomalies) {
const monitorInfo = await getLatestMonitor({
dynamicSettings,
callES: esClient,
dateStart: 'now-15m',
dateEnd: 'now',
monitorId: params.monitorId,
});
anomalies.forEach((anomaly, index) => {
const alertInstance = alertInstanceFactory(DURATION_ANOMALY.id + index);
const summary = getAnomalySummary(anomaly, monitorInfo);
alertInstance.replaceState({
...updateState(state, false),
...summary,
});
alertInstance.scheduleActions(DURATION_ANOMALY.id);
});
alertInstance.scheduleActions(DURATION_ANOMALY.id);
});
}
}

return updateState(state, foundAnomalies);
},
});
return updateState(state, foundAnomalies);
},
});
Loading

0 comments on commit a6b2a6e

Please sign in to comment.