Skip to content

Commit

Permalink
Use new event log utility functions
Browse files Browse the repository at this point in the history
  • Loading branch information
mikecote committed Apr 29, 2022
1 parent ea053d6 commit 082120b
Show file tree
Hide file tree
Showing 12 changed files with 36 additions and 46 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import { random, mean } from 'lodash';
import { SanitizedRule, AlertSummary } from '../types';
import { IValidatedEvent } from '@kbn/event-log-plugin/server';
import { IValidatedEvent, millisToNanos, nanosToMillis } from '@kbn/event-log-plugin/server';
import { EVENT_LOG_ACTIONS, EVENT_LOG_PROVIDER, LEGACY_EVENT_LOG_ACTIONS } from '../plugin';
import { alertSummaryFromEventLog } from './alert_summary_from_event_log';

Expand Down Expand Up @@ -643,7 +643,7 @@ export class EventsFactory {
event: {
provider: EVENT_LOG_PROVIDER,
action: EVENT_LOG_ACTIONS.execute,
duration: `${random(2000, 180000)}000000`,
duration: millisToNanos(random(2000, 180000)),
},
};

Expand Down Expand Up @@ -710,7 +710,7 @@ export class EventsFactory {
return this.events
.filter((ev) => ev?.event?.action === 'execute' && ev?.event?.duration !== undefined)
.reduce((res: Record<string, number>, ev) => {
res[ev?.['@timestamp']!] = Number(BigInt(ev?.event?.duration!) / BigInt(1000 * 1000));
res[ev?.['@timestamp']!] = nanosToMillis(ev?.event?.duration!);
return res;
}, {});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,10 @@
*/

import { mean } from 'lodash';
import { IEvent } from '@kbn/event-log-plugin/server';
import { IEvent, nanosToMillis } from '@kbn/event-log-plugin/server';
import { SanitizedRule, AlertSummary, AlertStatus } from '../types';
import { EVENT_LOG_ACTIONS, EVENT_LOG_PROVIDER, LEGACY_EVENT_LOG_ACTIONS } from '../plugin';

const Millis2Nanos = BigInt(1000 * 1000);

export interface AlertSummaryFromEventLogParams {
rule: SanitizedRule<{ bar: boolean }>;
events: IEvent[];
Expand Down Expand Up @@ -111,7 +109,7 @@ export function alertSummaryFromEventLog(params: AlertSummaryFromEventLogParams)
}

if (event?.event?.duration) {
const eventDirationMillis = Number(BigInt(event.event.duration) / Millis2Nanos);
const eventDirationMillis = nanosToMillis(event.event.duration);
eventDurations.push(eventDirationMillis);
eventDurationsWithTimestamp[event['@timestamp']!] = eventDirationMillis;
}
Expand Down
17 changes: 9 additions & 8 deletions x-pack/plugins/alerting/server/task_runner/task_runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,12 @@ import uuid from 'uuid';
import { addSpaceIdToPath } from '@kbn/spaces-plugin/server';
import { KibanaRequest, Logger } from '@kbn/core/server';
import { ConcreteTaskInstance, throwUnrecoverableError } from '@kbn/task-manager-plugin/server';
import { IEvent, SAVED_OBJECT_REL_PRIMARY } from '@kbn/event-log-plugin/server';
import {
IEvent,
SAVED_OBJECT_REL_PRIMARY,
millisToNanos,
nanosToMillis,
} from '@kbn/event-log-plugin/server';
import { TaskRunnerContext } from './task_runner_factory';
import { createExecutionHandler, ExecutionHandler } from './create_execution_handler';
import { Alert, createAlertFactory } from '../alert';
Expand Down Expand Up @@ -803,9 +808,7 @@ export class TaskRunner<

// Copy duration into execution status if available
if (null != event.event?.duration) {
executionStatus.lastDuration = Math.round(
Number(BigInt(event.event?.duration) / BigInt(Millis2Nanos))
);
executionStatus.lastDuration = nanosToMillis(event.event?.duration);
monitoringHistory.duration = executionStatus.lastDuration;
}

Expand Down Expand Up @@ -1066,8 +1069,7 @@ function trackAlertDurations<
: currentAlerts[id].getState();
const durationInMs =
new Date(currentTime).valueOf() - new Date(state.start as string).valueOf();
const durationInNanoStr = durationInMs !== 0 ? `${durationInMs}000000` : '0';
const duration = state.start ? durationInNanoStr : undefined;
const duration = state.start ? millisToNanos(durationInMs) : undefined;
currentAlerts[id].replaceState({
...state,
...(state.start ? { start: state.start } : {}),
Expand All @@ -1080,8 +1082,7 @@ function trackAlertDurations<
const state = recoveredAlerts[id].getState();
const durationInMs =
new Date(currentTime).valueOf() - new Date(state.start as string).valueOf();
const durationInNanoStr = durationInMs !== 0 ? `${durationInMs}000000` : '0';
const duration = state.start ? durationInNanoStr : undefined;
const duration = state.start ? millisToNanos(durationInMs) : undefined;
recoveredAlerts[id].replaceState({
...state,
...(duration ? { duration } : {}),
Expand Down
6 changes: 6 additions & 0 deletions x-pack/plugins/event_log/common/lib/nanos_to_millis.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,10 @@ describe('nanosToMillis', () => {
test('should return 9007199254740991 (Number.MAX_SAFE_INTEGER) when passing in "9007199254740991000000" nanos', () => {
expect(nanosToMillis('9007199254740991000000')).toEqual(9007199254740991);
});

test('should work when numbers are passed in', () => {
expect(nanosToMillis(0)).toEqual(0);
expect(nanosToMillis(1)).toEqual(0);
expect(nanosToMillis(1000001)).toEqual(1);
});
});
2 changes: 1 addition & 1 deletion x-pack/plugins/event_log/common/lib/nanos_to_millis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@

const ONE_MILLION = BigInt(1000 * 1000);

export function nanosToMillis(nanos: string): number {
export function nanosToMillis(nanos: string | number): number {
return Number(BigInt(nanos) / ONE_MILLION);
}
5 changes: 3 additions & 2 deletions x-pack/plugins/event_log/server/event_logger.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
* 2.0.
*/

import { nanosToMillis } from '../common';
import { IEvent, IEventLogger, IEventLogService } from '.';
import { ECS_VERSION } from './types';
import { EventLogService } from './event_log_service';
Expand Down Expand Up @@ -137,9 +138,9 @@ describe('EventLogger', () => {

expect(timeStopValue).toBeGreaterThanOrEqual(timeStartValue);

const duration = BigInt(event.event!.duration!);
const duration = Number(event.event!.duration!);
expect(duration).toBeGreaterThan(0.95 * delayMS * 1000 * 1000);
expect(Number(duration / BigInt(1000 * 1000))).toBeCloseTo(timeStopValue - timeStartValue);
expect(nanosToMillis(duration)).toBeCloseTo(timeStopValue - timeStartValue);
});

test('timing method endTiming() method works when startTiming() is not called', async () => {
Expand Down
2 changes: 2 additions & 0 deletions x-pack/plugins/event_log/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import { PluginInitializerContext, PluginConfigDescriptor } from '@kbn/core/serv
import { ConfigSchema, IEventLogConfig } from './types';
import { Plugin } from './plugin';

export { millisToNanos, nanosToMillis } from '../common';

export type {
IEventLogService,
IEventLogger,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/

import expect from '@kbn/expect';
import { IValidatedEvent } from '@kbn/event-log-plugin/server';
import { IValidatedEvent, nanosToMillis } from '@kbn/event-log-plugin/server';
import { UserAtSpaceScenarios } from '../../scenarios';
import {
ESTestIndexTool,
Expand All @@ -17,8 +17,6 @@ import {
} from '../../../common/lib';
import { FtrProviderContext } from '../../../common/ftr_provider_context';

const NANOS_IN_MILLIS = BigInt(1000 * 1000);

// eslint-disable-next-line import/no-default-export
export default function ({ getService }: FtrProviderContext) {
const supertest = getService('supertest');
Expand Down Expand Up @@ -543,10 +541,7 @@ export default function ({ getService }: FtrProviderContext) {
expect(startExecuteEventStart).to.equal(executeEventStart);
expect(executeEventEnd).to.be.ok();

const durationDiff = Math.abs(
Math.round(Number(BigInt(duration!) / NANOS_IN_MILLIS)) -
(executeEventEnd - executeEventStart)
);
const durationDiff = Math.abs(nanosToMillis(duration!) - (executeEventEnd - executeEventStart));

// account for rounding errors
expect(durationDiff < 1).to.equal(true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import expect from '@kbn/expect';
import { omit } from 'lodash';
import type * as estypes from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { IValidatedEvent } from '@kbn/event-log-plugin/server';
import { IValidatedEvent, nanosToMillis } from '@kbn/event-log-plugin/server';
import { TaskRunning, TaskRunningStage } from '@kbn/task-manager-plugin/server/task_running';
import { ConcreteTaskInstance } from '@kbn/task-manager-plugin/server';
import { UserAtSpaceScenarios, Superuser } from '../../scenarios';
Expand All @@ -25,8 +25,6 @@ import {
getEventLog,
} from '../../../common/lib';

const NANOS_IN_MILLIS = BigInt(1000 * 1000);

// eslint-disable-next-line import/no-default-export
export default function alertTests({ getService }: FtrProviderContext) {
const supertest = getService('supertest');
Expand Down Expand Up @@ -1307,9 +1305,7 @@ instanceStateValue: true
expect(eventStart).to.be.ok();
expect(eventEnd).to.be.ok();

const durationDiff = Math.abs(
Math.round(Number(BigInt(duration!) / NANOS_IN_MILLIS)) - (eventEnd - eventStart)
);
const durationDiff = Math.abs(nanosToMillis(duration!) - (eventEnd - eventStart));

// account for rounding errors
expect(durationDiff < 1).to.equal(true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/
import type { Client } from '@elastic/elasticsearch';
import expect from '@kbn/expect';
import { IValidatedEvent } from '@kbn/event-log-plugin/server';
import { IValidatedEvent, nanosToMillis } from '@kbn/event-log-plugin/server';
import { Spaces } from '../../scenarios';
import {
ESTestIndexTool,
Expand All @@ -17,8 +17,6 @@ import {
} from '../../../common/lib';
import { FtrProviderContext } from '../../../common/ftr_provider_context';

const NANOS_IN_MILLIS = BigInt(1000 * 1000);

// eslint-disable-next-line import/no-default-export
export default function ({ getService }: FtrProviderContext) {
const supertest = getService('supertest');
Expand Down Expand Up @@ -377,10 +375,7 @@ export default function ({ getService }: FtrProviderContext) {
expect(startExecuteEventStart).to.equal(executeEventStart);
expect(executeEventEnd).to.be.ok();

const durationDiff = Math.abs(
Math.round(Number(BigInt(duration!) / NANOS_IN_MILLIS)) -
(executeEventEnd - executeEventStart)
);
const durationDiff = Math.abs(nanosToMillis(duration!) - (executeEventEnd - executeEventStart));

// account for rounding errors
expect(durationDiff < 1).to.equal(true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import expect from '@kbn/expect';
import uuid from 'uuid';
import { IValidatedEvent } from '@kbn/event-log-plugin/server';
import { IValidatedEvent, nanosToMillis } from '@kbn/event-log-plugin/server';
import { Spaces } from '../../scenarios';
import {
getUrlPrefix,
Expand All @@ -18,8 +18,6 @@ import {
} from '../../../common/lib';
import { FtrProviderContext } from '../../../common/ftr_provider_context';

const NANOS_IN_MILLIS = BigInt(1000 * 1000);

// eslint-disable-next-line import/no-default-export
export default function eventLogTests({ getService }: FtrProviderContext) {
const supertest = getService('supertest');
Expand Down Expand Up @@ -869,9 +867,7 @@ export function validateEvent(event: IValidatedEvent, params: ValidateEventLogPa
if (shouldHaveEventEnd !== false) {
expect(eventEnd).to.be.ok();

const durationDiff = Math.abs(
Math.round(Number(BigInt(duration!) / NANOS_IN_MILLIS)) - (eventEnd - eventStart)
);
const durationDiff = Math.abs(nanosToMillis(duration!) - (eventEnd - eventStart));

// account for rounding errors
expect(durationDiff < 1).to.equal(true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/

import expect from '@kbn/expect';
import { IValidatedEvent } from '@kbn/event-log-plugin/server';
import { IValidatedEvent, nanosToMillis } from '@kbn/event-log-plugin/server';
import { Spaces } from '../../scenarios';
import { getUrlPrefix, getTestRuleData, ObjectRemover, getEventLog } from '../../../common/lib';
import { FtrProviderContext } from '../../../common/ftr_provider_context';
Expand Down Expand Up @@ -126,7 +126,7 @@ export default function eventLogAlertTests({ getService }: FtrProviderContext) {
expect(
new Date(instanceEvents[i]?.event?.end!).valueOf() -
new Date(instanceEvents[i]?.event?.start!).valueOf()
).to.equal(Number(BigInt(instanceEvents[i]?.event?.duration!) / BigInt(1000000)));
).to.equal(nanosToMillis(instanceEvents[i]?.event?.duration!));
break;
}
}
Expand Down

0 comments on commit 082120b

Please sign in to comment.