Skip to content

Commit

Permalink
Merge branch 'master' into feature/lensOriginatingAppBreadcrumb
Browse files Browse the repository at this point in the history
  • Loading branch information
elasticmachine authored Aug 20, 2020
2 parents c3a5273 + 5308cc7 commit 2209bf0
Show file tree
Hide file tree
Showing 29 changed files with 882 additions and 71 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
*/

import { i18n } from '@kbn/i18n';
import { SnapshotCustomMetricInput } from '../../../../../../../common/http_api/snapshot_api';
import { SnapshotCustomMetricInput } from '../http_api/snapshot_api';

export const getCustomMetricLabel = (metric: SnapshotCustomMetricInput) => {
const METRIC_LABELS = {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/*
* 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 { decimalToPct, pctToDecimal } from './corrected_percent_convert';

describe('decimalToPct', () => {
test('should retain correct floating point precision up to 10 decimal places', () => {
// Most of these cases would still work fine just doing x * 100 instead of passing it through
// decimalToPct, but the function still needs to work regardless
expect(decimalToPct(0)).toBe(0);
expect(decimalToPct(0.1)).toBe(10);
expect(decimalToPct(0.01)).toBe(1);
expect(decimalToPct(0.014)).toBe(1.4);
expect(decimalToPct(0.0141)).toBe(1.41);
expect(decimalToPct(0.01414)).toBe(1.414);
// This case is known to fail without decimalToPct; vanilla JS 0.014141 * 100 === 1.4141000000000001
expect(decimalToPct(0.014141)).toBe(1.4141);
expect(decimalToPct(0.0141414)).toBe(1.41414);
expect(decimalToPct(0.01414141)).toBe(1.414141);
expect(decimalToPct(0.014141414)).toBe(1.4141414);
});
test('should also work with values greater than 1', () => {
expect(decimalToPct(2)).toBe(200);
expect(decimalToPct(2.1)).toBe(210);
expect(decimalToPct(2.14)).toBe(214);
expect(decimalToPct(2.14141414)).toBe(214.141414);
});
});

describe('pctToDecimal', () => {
test('should retain correct floating point precision up to 10 decimal places', () => {
expect(pctToDecimal(0)).toBe(0);
expect(pctToDecimal(10)).toBe(0.1);
expect(pctToDecimal(1)).toBe(0.01);
expect(pctToDecimal(1.4)).toBe(0.014);
expect(pctToDecimal(1.41)).toBe(0.0141);
expect(pctToDecimal(1.414)).toBe(0.01414);
expect(pctToDecimal(1.4141)).toBe(0.014141);
expect(pctToDecimal(1.41414)).toBe(0.0141414);
expect(pctToDecimal(1.414141)).toBe(0.01414141);
expect(pctToDecimal(1.4141414)).toBe(0.014141414);
});
test('should also work with values greater than 100%', () => {
expect(pctToDecimal(200)).toBe(2);
expect(pctToDecimal(210)).toBe(2.1);
expect(pctToDecimal(214)).toBe(2.14);
expect(pctToDecimal(214.141414)).toBe(2.14141414);
});
});
16 changes: 16 additions & 0 deletions x-pack/plugins/infra/common/utils/corrected_percent_convert.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/*
* 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.
*/

const correctedPctConvert = (v: number, decimalToPct: boolean) => {
// Correct floating point precision
const replacementPattern = decimalToPct ? new RegExp(/0?\./) : '.';
const numberOfDigits = String(v).replace(replacementPattern, '').length;
const multipliedValue = decimalToPct ? v * 100 : v / 100;
return parseFloat(multipliedValue.toPrecision(numberOfDigits));
};

export const decimalToPct = (v: number) => correctedPctConvert(v, true);
export const pctToDecimal = (v: number) => correctedPctConvert(v, false);
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { useKibana } from '../../../../../../../src/plugins/kibana_react/public'
import { METRIC_INVENTORY_THRESHOLD_ALERT_TYPE_ID } from '../../../../server/lib/alerting/inventory_metric_threshold/types';
import { InfraWaffleMapOptions } from '../../../lib/lib';
import { InventoryItemType } from '../../../../common/inventory_models/types';
import { useAlertPrefillContext } from '../../../alerting/use_alert_prefill';

interface Props {
visible?: boolean;
Expand All @@ -21,16 +22,24 @@ interface Props {
setVisible: React.Dispatch<React.SetStateAction<boolean>>;
}

export const AlertFlyout = (props: Props) => {
export const AlertFlyout = ({ options, nodeType, filter, visible, setVisible }: Props) => {
const { triggersActionsUI } = useContext(TriggerActionsContext);
const { services } = useKibana();

const { inventoryPrefill } = useAlertPrefillContext();
const { customMetrics } = inventoryPrefill;

return (
<>
{triggersActionsUI && (
<AlertsContextProvider
value={{
metadata: { options: props.options, nodeType: props.nodeType, filter: props.filter },
metadata: {
options,
nodeType,
filter,
customMetrics,
},
toastNotifications: services.notifications?.toasts,
http: services.http,
docLinks: services.docLinks,
Expand All @@ -40,8 +49,8 @@ export const AlertFlyout = (props: Props) => {
}}
>
<AlertAdd
addFlyoutVisible={props.visible!}
setAddFlyoutVisibility={props.setVisible}
addFlyoutVisible={visible!}
setAddFlyoutVisibility={setVisible}
alertTypeId={METRIC_INVENTORY_THRESHOLD_ALERT_TYPE_ID}
canChangeTrigger={false}
consumer={'infrastructure'}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
/*
* 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 { mountWithIntl, nextTick } from 'test_utils/enzyme_helpers';
import { actionTypeRegistryMock } from '../../../../../triggers_actions_ui/public/application/action_type_registry.mock';
import { alertTypeRegistryMock } from '../../../../../triggers_actions_ui/public/application/alert_type_registry.mock';
import { coreMock } from '../../../../../../../src/core/public/mocks';
import { AlertsContextValue } from '../../../../../triggers_actions_ui/public/application/context/alerts_context';
// eslint-disable-next-line @kbn/eslint/no-restricted-paths
import { InventoryMetricConditions } from '../../../../server/lib/alerting/inventory_metric_threshold/types';
import React from 'react';
import { Expressions, AlertContextMeta, ExpressionRow } from './expression';
import { act } from 'react-dom/test-utils';
// eslint-disable-next-line @kbn/eslint/no-restricted-paths
import { Comparator } from '../../../../server/lib/alerting/metric_threshold/types';
import { SnapshotCustomMetricInput } from '../../../../common/http_api/snapshot_api';

jest.mock('../../../containers/source/use_source_via_http', () => ({
useSourceViaHttp: () => ({
source: { id: 'default' },
createDerivedIndexPattern: () => ({ fields: [], title: 'metricbeat-*' }),
}),
}));

const exampleCustomMetric = {
id: 'this-is-an-id',
field: 'some.system.field',
aggregation: 'rate',
type: 'custom',
} as SnapshotCustomMetricInput;

describe('Expression', () => {
async function setup(currentOptions: AlertContextMeta) {
const alertParams = {
criteria: [],
nodeType: undefined,
filterQueryText: '',
};

const mocks = coreMock.createSetup();
const startMocks = coreMock.createStart();
const [
{
application: { capabilities },
},
] = await mocks.getStartServices();

const context: AlertsContextValue<AlertContextMeta> = {
http: mocks.http,
toastNotifications: mocks.notifications.toasts,
actionTypeRegistry: actionTypeRegistryMock.create() as any,
alertTypeRegistry: alertTypeRegistryMock.create() as any,
docLinks: startMocks.docLinks,
capabilities: {
...capabilities,
actions: {
delete: true,
save: true,
show: true,
},
},
metadata: currentOptions,
};

const wrapper = mountWithIntl(
<Expressions
alertsContext={context}
alertInterval="1m"
alertParams={alertParams as any}
errors={[]}
setAlertParams={(key, value) => Reflect.set(alertParams, key, value)}
setAlertProperty={() => {}}
/>
);

const update = async () =>
await act(async () => {
await nextTick();
wrapper.update();
});

await update();

return { wrapper, update, alertParams };
}

it('should prefill the alert using the context metadata', async () => {
const currentOptions = {
filter: 'foo',
nodeType: 'pod',
customMetrics: [],
options: { metric: { type: 'memory' } },
};
const { alertParams } = await setup(currentOptions as AlertContextMeta);
expect(alertParams.nodeType).toBe('pod');
expect(alertParams.filterQueryText).toBe('foo');
expect(alertParams.criteria).toEqual([
{
metric: 'memory',
comparator: Comparator.GT,
threshold: [],
timeSize: 1,
timeUnit: 'm',
},
]);
});
describe('using custom metrics', () => {
it('should prefill the alert using the context metadata', async () => {
const currentOptions = {
filter: '',
nodeType: 'tx',
customMetrics: [exampleCustomMetric],
options: { metric: exampleCustomMetric },
};
const { alertParams, update } = await setup(currentOptions as AlertContextMeta);
await update();
expect(alertParams.nodeType).toBe('tx');
expect(alertParams.filterQueryText).toBe('');
expect(alertParams.criteria).toEqual([
{
metric: 'custom',
comparator: Comparator.GT,
threshold: [],
timeSize: 1,
timeUnit: 'm',
customMetric: exampleCustomMetric,
},
]);
});
});
});

describe('ExpressionRow', () => {
async function setup(expression: InventoryMetricConditions) {
const wrapper = mountWithIntl(
<ExpressionRow
nodeType="host"
canDelete={false}
remove={() => {}}
addExpression={() => {}}
key={1}
expressionId={1}
setAlertParams={() => {}}
errors={{
aggField: [],
timeSizeUnit: [],
timeWindowSize: [],
metric: [],
}}
expression={expression}
alertsContextMetadata={{
customMetrics: [],
}}
/>
);

const update = async () =>
await act(async () => {
await nextTick();
wrapper.update();
});

await update();

return { wrapper, update };
}
const expression = {
metric: 'custom',
comparator: Comparator.GT,
threshold: [],
timeSize: 1,
timeUnit: 'm',
customMetric: exampleCustomMetric,
};

it('loads custom metrics passed in through the expression, even with an empty context', async () => {
const { wrapper } = await setup(expression as InventoryMetricConditions);
const [valueMatch] =
wrapper.html().match('<span class="euiExpression__value">Rate of some.system.field</span>') ??
[];
expect(valueMatch).toBeTruthy();
});
});
Loading

0 comments on commit 2209bf0

Please sign in to comment.