Skip to content

Commit

Permalink
Avoid using the rule data client for field list
Browse files Browse the repository at this point in the history
  • Loading branch information
weltenwort committed Aug 20, 2021
1 parent dcb6c9d commit 3b18c32
Show file tree
Hide file tree
Showing 10 changed files with 72 additions and 62 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,20 @@
* 2.0.
*/

import { IndexPatternBase } from '@kbn/es-query';
import { i18n } from '@kbn/i18n';
import React, { useMemo, useState } from 'react';
import { IIndexPattern, SearchBar, TimeHistory } from '../../../../../../src/plugins/data/public';
import { SearchBar, TimeHistory } from '../../../../../../src/plugins/data/public';
import { Storage } from '../../../../../../src/plugins/kibana_utils/public';

export function AlertsSearchBar({
dynamicIndexPattern,
dynamicIndexPatterns,
rangeFrom,
rangeTo,
onQueryChange,
query,
}: {
dynamicIndexPattern: IIndexPattern[];
dynamicIndexPatterns: IndexPatternBase[];
rangeFrom?: string;
rangeTo?: string;
query?: string;
Expand All @@ -31,9 +32,19 @@ export function AlertsSearchBar({
}, []);
const [queryLanguage, setQueryLanguage] = useState<'lucene' | 'kuery'>('kuery');

const compatibleIndexPatterns = useMemo(
() =>
dynamicIndexPatterns.map((dynamicIndexPattern) => ({
title: dynamicIndexPattern.title ?? '',
id: dynamicIndexPattern.id ?? '',
fields: dynamicIndexPattern.fields,
})),
[dynamicIndexPatterns]
);

return (
<SearchBar
indexPatterns={dynamicIndexPattern}
indexPatterns={compatibleIndexPatterns}
placeholder={i18n.translate('xpack.observability.alerts.searchBarPlaceholder', {
defaultMessage: 'kibana.alert.evaluation.threshold > 75',
})}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ const ALERT_STATUS: typeof ALERT_STATUS_TYPED = ALERT_STATUS_NON_TYPED;
const ALERT_REASON: typeof ALERT_REASON_TYPED = ALERT_REASON_NON_TYPED;

interface AlertsTableTGridProps {
indexName: string;
indexNames: string[];
rangeFrom: string;
rangeTo: string;
kuery: string;
Expand Down Expand Up @@ -276,7 +276,7 @@ function ObservabilityActions({
}

export function AlertsTableTGrid(props: AlertsTableTGridProps) {
const { indexName, rangeFrom, rangeTo, kuery, status, setRefetch, addToQuery } = props;
const { indexNames, rangeFrom, rangeTo, kuery, status, setRefetch, addToQuery } = props;
const { timelines } = useKibana<{ timelines: TimelinesUIStart }>().services;

const [flyoutAlert, setFlyoutAlert] = useState<TopAlert | undefined>(undefined);
Expand Down Expand Up @@ -322,7 +322,7 @@ export function AlertsTableTGrid(props: AlertsTableTGridProps) {
defaultCellActions: getDefaultCellActions({ addToQuery }),
end: rangeTo,
filters: [],
indexNames: indexName.split(','),
indexNames,
itemsPerPage: 10,
itemsPerPageOptions: [10, 25, 50],
loadingText: i18n.translate('xpack.observability.alertsTable.loadingTextLabel', {
Expand Down Expand Up @@ -357,7 +357,7 @@ export function AlertsTableTGrid(props: AlertsTableTGridProps) {
};
}, [
casePermissions,
indexName,
indexNames,
kuery,
leadingControlColumns,
rangeFrom,
Expand Down
36 changes: 27 additions & 9 deletions x-pack/plugins/observability/public/pages/alerts/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@

import { EuiButtonEmpty, EuiCallOut, EuiFlexGroup, EuiFlexItem, EuiLink } from '@elastic/eui';
import { i18n } from '@kbn/i18n';
import React, { useCallback, useMemo, useRef } from 'react';
import React, { useCallback, useRef } from 'react';
import { useHistory } from 'react-router-dom';
import useAsync from 'react-use/lib/useAsync';
import { IndexPatternBase } from '@kbn/es-query';
import { ParsedTechnicalFields } from '../../../../rule_registry/common/parse_technical_fields';
import type { AlertStatus } from '../../../common/typings';
import { ExperimentalBadge } from '../../components/shared/experimental_badge';
Expand All @@ -35,7 +37,7 @@ interface AlertsPageProps {
}

export function AlertsPage({ routeParams }: AlertsPageProps) {
const { core, ObservabilityPageTemplate } = usePluginContext();
const { core, plugins, ObservabilityPageTemplate } = usePluginContext();
const { prepend } = core.http.basePath;
const history = useHistory();
const refetch = useRef<() => void>();
Expand All @@ -60,12 +62,13 @@ export function AlertsPage({ routeParams }: AlertsPageProps) {
// observability. For now link to the settings page.
const manageRulesHref = prepend('/app/management/insightsAndAlerting/triggersActions/alerts');

const { data: dynamicIndexPatternResp } = useFetcher(({ signal }) => {
const { data: indexNames = NO_INDEX_NAMES } = useFetcher(({ signal }) => {
return callObservabilityApi({
signal,
endpoint: 'GET /api/observability/rules/alerts/dynamic_index_pattern',
params: {
query: {
namespace: 'default',
registrationContexts: [
'observability.apm',
'observability.logs',
Expand All @@ -78,10 +81,22 @@ export function AlertsPage({ routeParams }: AlertsPageProps) {
});
}, []);

const dynamicIndexPattern = useMemo(
() => (dynamicIndexPatternResp ? [dynamicIndexPatternResp] : []),
[dynamicIndexPatternResp]
);
const dynamicIndexPatternsAsyncState = useAsync(async (): Promise<IndexPatternBase[]> => {
if (indexNames.length === 0) {
return [];
}

return [
{
id: 'dynamic-observability-alerts-table-index-pattern',
title: indexNames.join(','),
fields: await plugins.data.indexPatterns.getFieldsForWildcard({
pattern: indexNames.join(','),
allowNoIndex: true,
}),
},
];
}, [indexNames]);

const setStatusFilter = useCallback(
(value: AlertStatus) => {
Expand Down Expand Up @@ -176,7 +191,7 @@ export function AlertsPage({ routeParams }: AlertsPageProps) {
</EuiFlexItem>
<EuiFlexItem>
<AlertsSearchBar
dynamicIndexPattern={dynamicIndexPattern}
dynamicIndexPatterns={dynamicIndexPatternsAsyncState.value ?? NO_INDEX_PATTERNS}
rangeFrom={rangeFrom}
rangeTo={rangeTo}
query={kuery}
Expand All @@ -194,7 +209,7 @@ export function AlertsPage({ routeParams }: AlertsPageProps) {
</EuiFlexItem>
<EuiFlexItem>
<AlertsTableTGrid
indexName={dynamicIndexPattern.length > 0 ? dynamicIndexPattern[0].title : ''}
indexNames={indexNames}
rangeFrom={rangeFrom}
rangeTo={rangeTo}
kuery={kuery}
Expand All @@ -209,3 +224,6 @@ export function AlertsPage({ routeParams }: AlertsPageProps) {
</ObservabilityPageTemplate>
);
}

const NO_INDEX_NAMES: string[] = [];
const NO_INDEX_PATTERNS: IndexPatternBase[] = [];
13 changes: 1 addition & 12 deletions x-pack/plugins/observability/server/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import {
ScopedAnnotationsClientFactory,
AnnotationsAPI,
} from './lib/annotations/bootstrap_annotations';
import { Dataset, RuleRegistryPluginSetupContract } from '../../rule_registry/server';
import { RuleRegistryPluginSetupContract } from '../../rule_registry/server';
import { PluginSetupContract as FeaturesSetup } from '../../features/server';
import { uiSettings } from './ui_settings';
import { registerRoutes } from './routes/register_routes';
Expand Down Expand Up @@ -101,16 +101,6 @@ export class ObservabilityPlugin implements Plugin<ObservabilityPluginSetup> {
const start = () => core.getStartServices().then(([coreStart]) => coreStart);

const { ruleDataService } = plugins.ruleRegistry;
const ruleDataClient = ruleDataService.initializeIndex({
feature: 'observability',
registrationContext: 'observability',
dataset: Dataset.alerts,
componentTemplateRefs: [],
componentTemplates: [],
indexTemplate: {
version: 0,
},
});

registerRoutes({
core: {
Expand All @@ -119,7 +109,6 @@ export class ObservabilityPlugin implements Plugin<ObservabilityPluginSetup> {
},
logger: this.initContext.logger.get(),
repository: getGlobalObservabilityServerRouteRepository(),
ruleDataClient,
ruleDataService,
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,14 @@ import {
import { CoreSetup, CoreStart, Logger, RouteRegistrar } from 'kibana/server';
import Boom from '@hapi/boom';
import { RequestAbortedError } from '@elastic/elasticsearch/lib/errors';
import { IRuleDataClient, RuleDataPluginService } from '../../../rule_registry/server';
import { RuleDataPluginService } from '../../../rule_registry/server';
import { ObservabilityRequestHandlerContext } from '../types';
import { AbstractObservabilityServerRouteRepository } from './types';

export function registerRoutes({
repository,
core,
logger,
ruleDataClient,
ruleDataService,
}: {
core: {
Expand All @@ -30,7 +29,6 @@ export function registerRoutes({
};
repository: AbstractObservabilityServerRouteRepository;
logger: Logger;
ruleDataClient: IRuleDataClient;
ruleDataService: RuleDataPluginService;
}) {
const routes = repository.getRoutes();
Expand Down Expand Up @@ -64,7 +62,6 @@ export function registerRoutes({
core,
logger,
params: decodedParams,
ruleDataClient,
ruleDataService,
})) as any;

Expand Down
25 changes: 13 additions & 12 deletions x-pack/plugins/observability/server/routes/rules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,23 +17,24 @@ const alertsDynamicIndexPatternRoute = createObservabilityServerRoute({
params: t.type({
query: t.type({
registrationContexts: t.array(t.string),
namespace: t.string,
}),
}),
handler: async ({ context, ruleDataService, ruleDataClient, params }) => {
const { registrationContexts } = params.query;
const spaceId = context.alerting.getRulesClient().getSpaceId();
const indexNames = registrationContexts.map((registrationContext) => {
const rcIndexName = ruleDataService.getBaseNameByRegistrationContext(registrationContext);
if (rcIndexName) {
return `${rcIndexName}-${spaceId}`;
handler: async ({ ruleDataService, params }) => {
const { namespace, registrationContexts } = params.query;
const indexNames = registrationContexts.flatMap((registrationContext) => {
const indexName = ruleDataService
.getRegisteredIndexInfo(registrationContext)
?.getPrimaryAlias(namespace);

if (indexName != null) {
return [indexName];
} else {
return [];
}
return undefined;
});
const reader = ruleDataClient.getReader({
indexNames: indexNames.filter<string>((item: string | undefined): item is string => !!item),
});

return reader.getDynamicIndexPattern();
return indexNames;
},
});

Expand Down
3 changes: 1 addition & 2 deletions x-pack/plugins/observability/server/routes/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import type {
ServerRouteRepository,
} from '@kbn/server-route-repository';
import { CoreSetup, CoreStart, KibanaRequest, Logger } from 'kibana/server';
import { IRuleDataClient, RuleDataPluginService } from '../../../rule_registry/server';
import { RuleDataPluginService } from '../../../rule_registry/server';

import { ObservabilityServerRouteRepository } from './get_global_observability_server_route_repository';
import { ObservabilityRequestHandlerContext } from '../types';
Expand All @@ -24,7 +24,6 @@ export interface ObservabilityRouteHandlerResources {
start: () => Promise<CoreStart>;
setup: CoreSetup;
};
ruleDataClient: IRuleDataClient;
ruleDataService: RuleDataPluginService;
request: KibanaRequest;
context: ObservabilityRequestHandlerContext;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,9 @@ export class RuleDataClient implements IRuleDataClient {
return this.options.isWriteEnabled;
}

public getReader(options: { namespace?: string; indexNames?: string[] } = {}): IRuleDataReader {
public getReader(options: { namespace?: string } = {}): IRuleDataReader {
const { indexInfo } = this.options;
const { namespace, indexNames } = options;
let indexPattern = indexInfo.getPatternForReading(namespace);
if (indexNames && indexNames.length > 0) {
indexPattern = indexNames.join(',');
}
const indexPattern = indexInfo.getPatternForReading(options.namespace);

const waitUntilReady = async () => {
const result = await this.options.waitUntilReadyForReading;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ type Schema = PublicMethodsOf<RuleDataPluginService>;

const createRuleDataPluginService = () => {
const mocked: jest.Mocked<Schema> = {
getBaseNameByRegistrationContext: jest.fn(),
getRegisteredIndexInfo: jest.fn(),
getResourcePrefix: jest.fn(),
getResourceName: jest.fn(),
isWriteEnabled: jest.fn(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export class RuleDataPluginService {
private readonly resourceInstaller: ResourceInstaller;
private installCommonResources: Promise<Either<Error, 'ok'>>;
private isInitialized: boolean;
private registrationContextWithBaseName: Map<string, string>;
private registeredIndices: Map<string, IndexInfo> = new Map();

constructor(private readonly options: ConstructorOptions) {
this.resourceInstaller = new ResourceInstaller({
Expand All @@ -41,7 +41,6 @@ export class RuleDataPluginService {

this.installCommonResources = Promise.resolve(right('ok'));
this.isInitialized = false;
this.registrationContextWithBaseName = new Map();
}

/**
Expand Down Expand Up @@ -107,7 +106,7 @@ export class RuleDataPluginService {
indexOptions,
});

this.registrationContextWithBaseName.set(indexOptions.registrationContext, indexInfo.baseName);
this.registeredIndices.set(indexOptions.registrationContext, indexInfo);

const waitUntilClusterClientAvailable = async (): Promise<WaitResult> => {
try {
Expand Down Expand Up @@ -154,11 +153,11 @@ export class RuleDataPluginService {
}

/**
* Initializes alerts-as-data index and starts index bootstrapping right away.
* @param indexOptions Index parameters: names and resources.
* @returns Client for reading and writing data to this index.
* Looks up the index information associated with the given `registrationContext`.
* @param registrationContext
* @returns the IndexInfo or undefined
*/
public getBaseNameByRegistrationContext(registrationContext: string): string | undefined {
return this.registrationContextWithBaseName.get(registrationContext);
public getRegisteredIndexInfo(registrationContext: string): IndexInfo | undefined {
return this.registeredIndices.get(registrationContext);
}
}

0 comments on commit 3b18c32

Please sign in to comment.