Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import { i18n } from '@kbn/i18n';
import { IBasePath } from '@kbn/core/public';
import moment from 'moment';
import type { InfraLocators } from '@kbn/infra-plugin/public/locators';
import type { InfraLocators } from '@kbn/infra-plugin/common/locators';
import { APIReturnType } from '../../../../../services/rest/create_call_apm_api';
import { getInfraHref } from '../../../../shared/links/infra_link';
import {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { IBasePath } from '@kbn/core/public';
import { isEmpty, pickBy } from 'lodash';
import moment from 'moment';
import url from 'url';
import type { InfraLocators } from '@kbn/infra-plugin/public/locators';
import type { InfraLocators } from '@kbn/infra-plugin/common/locators';
import type { Transaction } from '../../../../typings/es_schemas/ui/transaction';
import { getDiscoverHref } from '../links/discover_links/discover_link';
import { getDiscoverQuery } from '../links/discover_links/discover_transaction_link';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ import { createObservabilityRuleTypeRegistryMock } from '@kbn/observability-plug
import { UI_SETTINGS } from '@kbn/data-plugin/common';
import { MlLocatorDefinition } from '@kbn/ml-plugin/public';
import { enableComparisonByDefault } from '@kbn/observability-plugin/public';
import type { InfraLocators } from '@kbn/infra-plugin/public/locators';
import { sharePluginMock } from '@kbn/share-plugin/public/mocks';
import type { InfraLocators } from '@kbn/infra-plugin/common/locators';
import { ApmPluginContext, ApmPluginContextValue } from './apm_plugin_context';
import { ConfigSchema } from '../..';
import { createCallApmApi } from '../../services/rest/create_call_apm_api';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import { LocatorDefinition, LocatorPublic } from '@kbn/share-plugin/public';
import type { LocatorDefinition, LocatorPublic } from '@kbn/share-plugin/public';
import type { LogsLocatorDependencies, LogsLocatorParams } from './logs_locator';
import { LOGS_LOCATOR_ID } from './logs_locator';

Expand All @@ -19,6 +19,9 @@ export class DiscoverLogsLocatorDefinition implements LocatorDefinition<LogsLoca
public readonly getLocation = async (params: LogsLocatorParams) => {
const { getLocationToDiscover } = await import('./helpers');

return getLocationToDiscover({ core: this.deps.core, ...params });
return getLocationToDiscover({
core: this.deps.core,
...params,
});
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import { LocatorDefinition, LocatorPublic } from '@kbn/share-plugin/public';
import type { LocatorDefinition, LocatorPublic } from '@kbn/share-plugin/public';
import type { NodeLogsLocatorDependencies, NodeLogsLocatorParams } from './node_logs_locator';
import { NODE_LOGS_LOCATOR_ID } from './node_logs_locator';

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,23 @@
* 2.0.
*/

import { interpret } from 'xstate';
import { waitFor } from 'xstate/lib/waitFor';
import { flowRight } from 'lodash';
import type { DiscoverAppLocatorParams } from '@kbn/discover-plugin/common';
import type { DiscoverStart } from '@kbn/discover-plugin/public';
import { findInventoryFields } from '../../common/inventory_models';
import { MESSAGE_FIELD, TIMESTAMP_FIELD } from '../../common/constants';
import { findInventoryFields } from '../inventory_models';
import { MESSAGE_FIELD, TIMESTAMP_FIELD } from '../constants';
import type { TimeRange } from '../time';
import type { LogsLocatorParams } from './logs_locator';
import type { InfraClientCoreSetup } from '../../public/types';
import {
createLogViewStateMachine,
DEFAULT_LOG_VIEW,
replaceLogViewInQueryString,
} from '../observability_logs/log_view_state';
import { replaceLogFilterInQueryString } from '../observability_logs/log_stream_query_state';
import { replaceLogPositionInQueryString } from '../observability_logs/log_stream_position_state/src/url_state_storage_service';
import type { TimeRange } from '../../common/time';
import type { LogsLocatorParams } from './logs_locator';
import type { InfraClientCoreSetup } from '../types';
import type {
LogViewColumnConfiguration,
LogViewReference,
replaceLogFilterInQueryString,
replaceLogPositionInQueryString,
replaceLogViewInQueryString,
ResolvedLogView,
} from '../../common/log_views';
} from '../log_views';
import type { NodeLogsLocatorParams } from './node_logs_locator';

interface LocationToDiscoverParams {
Expand Down Expand Up @@ -62,16 +57,12 @@ export const getLocationToDiscover = async ({
core,
timeRange,
filter,
logView,
logView = DEFAULT_LOG_VIEW,
}: LocationToDiscoverParams) => {
const [, plugins, pluginStart] = await core.getStartServices();
const { discover } = plugins;
const { logViews } = pluginStart;

const machine = createLogViewStateMachine({
initialContext: { logViewReference: logView || DEFAULT_LOG_VIEW },
logViews: logViews.client,
});
const resolvedLogView = await logViews.client.getResolvedLogView(logView);

const discoverParams: DiscoverAppLocatorParams = {
...(timeRange ? { from: timeRange.startTime, to: timeRange.endTime } : {}),
Expand All @@ -85,32 +76,12 @@ export const getLocationToDiscover = async ({
: {}),
};

let discoverLocation;

const service = interpret(machine).start();
const doneState = await waitFor(
service,
(state) =>
state.matches('checkingStatus') ||
state.matches('resolvedPersistedLogView') ||
state.matches('resolvedInlineLogView') ||
state.matches('loadingFailed') ||
state.matches('resolutionFailed') ||
state.matches('checkingStatusFailed')
const discoverLocation = await constructDiscoverLocation(
discover,
discoverParams,
resolvedLogView
);

service.stop();

if ('resolvedLogView' in doneState.context) {
discoverLocation = await constructDiscoverLocation(
discover,
discoverParams,
doneState.context.resolvedLogView
);
} else {
discoverLocation = await constructDiscoverLocation(discover, discoverParams);
}

if (!discoverLocation) {
throw new Error('Discover location not found');
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,9 @@ import { NodeLogsLocatorDefinition } from './node_logs_locator';
import type { LogsLocatorParams } from './logs_locator';
import type { NodeLogsLocatorParams } from './node_logs_locator';
import { coreMock } from '@kbn/core/public/mocks';
import { findInventoryFields } from '../../common/inventory_models';
import { findInventoryFields } from '../inventory_models';
import moment from 'moment';
import { DEFAULT_LOG_VIEW } from '../observability_logs/log_view_state';
import type { LogViewReference } from '../../common/log_views';
import { DEFAULT_LOG_VIEW, LogViewReference } from '../log_views';

const setupLogsLocator = async () => {
const deps: LogsLocatorDependencies = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@
* 2.0.
*/

import { LocatorDefinition, LocatorPublic } from '@kbn/share-plugin/public';
import type { SerializableRecord } from '@kbn/utility-types';
import type { LogViewReference } from '../../common/log_views';
import type { TimeRange } from '../../common/time';
import type { InfraClientCoreSetup } from '../types';
import type { LocatorDefinition, LocatorPublic } from '@kbn/share-plugin/public';
import { SerializableRecord } from '@kbn/utility-types';
import type { LogViewReference } from '../log_views';
import type { TimeRange } from '../time';
import type { InfraClientCoreSetup } from '../../public/types';

export const LOGS_LOCATOR_ID = 'LOGS_LOCATOR';

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
* 2.0.
*/

import { LocatorDefinition, LocatorPublic } from '@kbn/share-plugin/public';
import type { InventoryItemType } from '../../common/inventory_models/types';
import type { LocatorDefinition, LocatorPublic } from '@kbn/share-plugin/public';
import type { InventoryItemType } from '../inventory_models/types';
import type { LogsLocatorDependencies, LogsLocatorParams } from './logs_locator';

export const NODE_LOGS_LOCATOR_ID = 'NODE_LOGS_LOCATOR';
Expand Down
9 changes: 9 additions & 0 deletions x-pack/plugins/infra/common/log_views/defaults.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ import { defaultSourceConfiguration } from '../source_configuration/defaults';
import { LogViewAttributes, LogViewsStaticConfig } from './types';

export const defaultLogViewId = 'default';
export const defaultFilterStateKey = 'logFilter';
export const defaultPositionStateKey = 'logPosition'; // NOTE: Provides backwards compatibility for start / end / streamLive previously stored under the logPosition key.

export const DEFAULT_REFRESH_INTERVAL = { pause: true, value: 5000 };

export const defaultLogViewAttributes: LogViewAttributes = {
name: 'Log View',
Expand Down Expand Up @@ -40,3 +44,8 @@ export const defaultLogViewAttributes: LogViewAttributes = {
export const defaultLogViewsStaticConfig: LogViewsStaticConfig = {
messageFields: defaultSourceConfiguration.fields.message,
};

export const DEFAULT_LOG_VIEW = {
type: 'log-view-reference' as const,
logViewId: defaultLogViewId,
};
1 change: 1 addition & 0 deletions x-pack/plugins/infra/common/log_views/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@ export * from './defaults';
export * from './errors';
export * from './resolved_log_view';
export * from './types';
export * from './url_state_storage_service';
89 changes: 89 additions & 0 deletions x-pack/plugins/infra/common/log_views/url_state_storage_service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { url } from '@kbn/kibana-utils-plugin/common';
import { encode } from '@kbn/rison';
import type { Query } from '@kbn/es-query';
import { parse, stringify } from 'query-string';
import moment, { DurationInputObject } from 'moment';
import type { FilterStateInUrl } from '../../public/observability_logs/log_stream_query_state';
import type { PositionStateInUrl } from '../../public/observability_logs/log_stream_position_state/src/url_state_storage_service';
import {
defaultFilterStateKey,
defaultPositionStateKey,
DEFAULT_REFRESH_INTERVAL,
LogViewReference,
} from '.';
import type { TimeRange } from '../time';

export const defaultLogViewKey = 'logView';

const encodeRisonUrlState = (state: any) => encode(state);

// Used by linkTo components
export const replaceLogPositionInQueryString = (time?: number) =>
Number.isNaN(time) || time == null
? (value: string) => value
: replaceStateKeyInQueryString<PositionStateInUrl>(defaultPositionStateKey, {
position: {
time,
tiebreaker: 0,
},
});

// NOTE: Used by link-to components
export const replaceLogViewInQueryString = (logViewReference: LogViewReference) =>
replaceStateKeyInQueryString(defaultLogViewKey, logViewReference);

export const replaceStateKeyInQueryString =
<UrlState extends any>(stateKey: string, urlState: UrlState | undefined) =>
(queryString: string) => {
const previousQueryValues = parse(queryString, { sort: false });
const newValue =
typeof urlState === 'undefined'
? previousQueryValues
: {
...previousQueryValues,
[stateKey]: encodeRisonUrlState(urlState),
};
return stringify(url.encodeQuery(newValue), { sort: false, encode: false });
};

export const replaceLogFilterInQueryString = (query: Query, time?: number, timeRange?: TimeRange) =>
replaceStateKeyInQueryString<FilterStateInUrl>(defaultFilterStateKey, {
query,
...getTimeRange(time, timeRange),
refreshInterval: DEFAULT_REFRESH_INTERVAL,
});

const getTimeRange = (time?: number, timeRange?: TimeRange) => {
if (timeRange) {
return {
timeRange: {
from: new Date(timeRange.startTime).toISOString(),
to: new Date(timeRange.endTime).toISOString(),
},
};
} else if (time) {
return {
timeRange: {
from: getTimeRangeStartFromTime(time),
to: getTimeRangeEndFromTime(time),
},
};
} else {
return {};
}
};

const defaultTimeRangeFromPositionOffset: DurationInputObject = { hours: 1 };

export const getTimeRangeStartFromTime = (time: number): string =>
moment(time).subtract(defaultTimeRangeFromPositionOffset).toISOString();

export const getTimeRangeEndFromTime = (time: number): string =>
moment(time).add(defaultTimeRangeFromPositionOffset).toISOString();
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,21 @@

import { i18n } from '@kbn/i18n';
import { ObservabilityRuleTypeModel } from '@kbn/observability-plugin/public';
import type { LocatorPublic } from '@kbn/share-plugin/public';
import { lazy } from 'react';
import type { LogsLocatorParams } from '../../../common/locators';
import {
LOG_DOCUMENT_COUNT_RULE_TYPE_ID,
PartialRuleParams,
} from '../../../common/alerting/logs/log_threshold';
import { createLazyComponentWithKibanaContext } from '../../hooks/use_kibana';
import { InfraClientCoreSetup } from '../../types';
import { formatRuleData } from './rule_data_formatters';
import { createRuleFormatter } from './rule_data_formatters';
import { validateExpression } from './validation';

export function createLogThresholdRuleType(
core: InfraClientCoreSetup
core: InfraClientCoreSetup,
logsLocator: LocatorPublic<LogsLocatorParams>
): ObservabilityRuleTypeModel<PartialRuleParams> {
const ruleParamsExpression = createLazyComponentWithKibanaContext(
core,
Expand All @@ -44,6 +47,6 @@ export function createLogThresholdRuleType(
}
),
requiresAppContext: false,
format: formatRuleData,
format: createRuleFormatter(logsLocator),
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,32 @@
*/

import { ALERT_REASON, ALERT_START } from '@kbn/rule-data-utils';
import { ObservabilityRuleTypeFormatter } from '@kbn/observability-plugin/public';
import { getLogsAppAlertUrl } from '../../../common/formatters/alert_link';
import type { ObservabilityRuleTypeFormatter } from '@kbn/observability-plugin/public';
import type { LocatorPublic } from '@kbn/share-plugin/public';
import type { LogsLocatorParams } from '../../../common/locators';

export const formatRuleData: ObservabilityRuleTypeFormatter = ({ fields }) => {
const reason = fields[ALERT_REASON] ?? '';
const alertStartDate = fields[ALERT_START];
const timestamp = alertStartDate != null ? new Date(alertStartDate).valueOf() : null;
export const createRuleFormatter: (
logsLocator: LocatorPublic<LogsLocatorParams>
) => ObservabilityRuleTypeFormatter =
(logsLocator) =>
({ fields }) => {
const reason = fields[ALERT_REASON] ?? '';
const alertStartDate = fields[ALERT_START];
const time = alertStartDate != null ? new Date(alertStartDate).valueOf() : undefined;
const url = logsLocator.getRedirectUrl({ time });

return {
reason,
link: getLogsAppAlertUrl(timestamp), // TODO: refactor to URL generators
// the alerts UI already prepends the url to the baseUrl so we need to remove it here
const link = removeBaseUrl(url);

return {
reason,
link,
};
};

const removeBaseUrl = (url: string): string => {
const substring = '/app/';
const substringIndex = url.indexOf(substring);

return url.substring(substringIndex);
};
3 changes: 1 addition & 2 deletions x-pack/plugins/infra/public/hooks/use_log_view.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { useInterpret, useSelector } from '@xstate/react';
import createContainer from 'constate';
import { useCallback, useState } from 'react';
import { waitFor } from 'xstate/lib/waitFor';
import { LogViewAttributes, LogViewReference } from '../../common/log_views';
import { DEFAULT_LOG_VIEW, LogViewAttributes, LogViewReference } from '../../common/log_views';
import {
InitializeFromUrl,
UpdateContextInUrl,
Expand All @@ -18,7 +18,6 @@ import {
import {
createLogViewNotificationChannel,
createLogViewStateMachine,
DEFAULT_LOG_VIEW,
} from '../observability_logs/log_view_state';
import type { ILogViewsClient } from '../services/log_views';
import { isDevMode } from '../utils/dev_mode';
Expand Down
Loading