Skip to content

Commit

Permalink
Fall back to dynamic data view
Browse files Browse the repository at this point in the history
  • Loading branch information
sorenlouv committed Jul 22, 2022
1 parent 344b18e commit 2bcdc41
Show file tree
Hide file tree
Showing 19 changed files with 120 additions and 109 deletions.
4 changes: 0 additions & 4 deletions x-pack/plugins/apm/public/application/application.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,6 @@ import { dataPluginMock } from '@kbn/data-plugin/public/mocks';
import { embeddablePluginMock } from '@kbn/embeddable-plugin/public/mocks';
import { ApmPluginSetupDeps, ApmPluginStartDeps } from '../plugin';

jest.mock('../services/rest/data_view', () => ({
createStaticDataView: () => Promise.resolve(undefined),
}));

describe('renderApp (APM)', () => {
let mockConsole: jest.SpyInstance;
beforeAll(() => {
Expand Down
7 changes: 0 additions & 7 deletions x-pack/plugins/apm/public/application/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import { KibanaThemeProvider } from '@kbn/kibana-react-plugin/public';
import { ConfigSchema } from '..';
import { ApmPluginSetupDeps, ApmPluginStartDeps } from '../plugin';
import { createCallApmApi } from '../services/rest/create_call_apm_api';
import { createStaticDataView } from '../services/rest/data_view';
import { setHelpExtension } from '../set_help_extension';
import { setReadonlyBadge } from '../update_badge';
import { ApmAppRoot } from '../components/routing/app_root';
Expand Down Expand Up @@ -61,12 +60,6 @@ export const renderApp = ({
setReadonlyBadge(coreStart);
createCallApmApi(coreStart);

// Automatically creates static data view and stores as saved object
createStaticDataView().catch((e) => {
// eslint-disable-next-line no-console
console.log('Error creating static data view', e);
});

// add .kbnAppWrappers class to root element
element.classList.add(APP_WRAPPER_CLASS);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,11 @@ const stories: Meta<{}> = {
default:
return {};
}
return {};
},
},
notifications: { toasts: { add: () => {}, addWarning: () => {} } },
uiSettings: { get: () => [] },
dataViews: { get: async () => {} },
} as unknown as CoreStart;

const KibanaReactContext = createKibanaReactContext(coreMock);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import {
TraceSearchQuery,
TraceSearchType,
} from '../../../../../common/trace_explorer';
import { useStaticDataView } from '../../../../hooks/use_static_data_view';
import { useApmDataView } from '../../../../hooks/use_apm_data_view';
import { useApmPluginContext } from '../../../../context/apm_plugin/use_apm_plugin_context';
import { EQLCodeEditorSuggestionType } from '../../../shared/eql_code_editor/constants';
import { LazilyLoadedEQLCodeEditor } from '../../../shared/eql_code_editor/lazily_loaded_code_editor';
Expand Down Expand Up @@ -57,7 +57,7 @@ export function TraceSearchBox({
loading,
}: Props) {
const { unifiedSearch } = useApmPluginContext();
const { value: dataView } = useStaticDataView();
const { dataView } = useApmDataView();

return (
<EuiFlexGroup direction="column">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import type { DataView } from '@kbn/data-views-plugin/public';
import { useApmPluginContext } from '../../../context/apm_plugin/use_apm_plugin_context';
import { useLegacyUrlParams } from '../../../context/url_params_context/use_url_params';
import { useApmParams } from '../../../hooks/use_apm_params';
import { useDynamicDataViewFetcher } from '../../../hooks/use_dynamic_data_view';
import { useApmDataView } from '../../../hooks/use_apm_data_view';
import { fromQuery, toQuery } from '../links/url_helpers';
import { getBoolFilter } from './get_bool_filter';
// @ts-expect-error
Expand Down Expand Up @@ -71,8 +71,7 @@ export function KueryBar(props: {
};

const example = examples[processorEvent || 'defaults'];

const { dataView } = useDynamicDataViewFetcher();
const { dataView } = useApmDataView();

const placeholder =
props.placeholder ??
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* 2.0.
*/

import { getByTestId, fireEvent, getByText } from '@testing-library/react';
import { getByTestId, fireEvent, getByText, act } from '@testing-library/react';
import { createMemoryHistory, MemoryHistory } from 'history';
import React from 'react';
import { Router } from 'react-router-dom';
Expand Down Expand Up @@ -37,6 +37,7 @@ function setup({

const KibanaReactContext = createKibanaReactContext({
usageCollection: { reportUiCounter: () => {} },
dataViews: { get: async () => {} },
} as Partial<CoreStart>);

// mock transaction types
Expand Down Expand Up @@ -91,7 +92,7 @@ describe('when transactionType is selected and multiple transaction types are gi
expect(dropdown).toHaveValue('secondType');
});

it('should update the URL when a transaction type is selected', () => {
it('should update the URL when a transaction type is selected', async () => {
const { container } = setup({
history,
serviceTransactionTypes: ['firstType', 'secondType'],
Expand All @@ -112,7 +113,9 @@ describe('when transactionType is selected and multiple transaction types are gi
expect(getByText(dropdown, 'secondType')).toBeInTheDocument();

// change dropdown value
fireEvent.change(dropdown, { target: { value: 'firstType' } });
await act(async () => {
fireEvent.change(dropdown, { target: { value: 'firstType' } });
});

// assert that value was changed
expect(dropdown).toHaveValue('firstType');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ const mockCore = merge({}, coreStart, {
capabilities: {
apm: {},
ml: {},
savedObjectsManagement: { edit: true },
},
},
uiSettings: {
Expand Down
66 changes: 66 additions & 0 deletions x-pack/plugins/apm/public/hooks/use_apm_data_view.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/*
* 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 { DataView } from '@kbn/data-views-plugin/common';
import { useKibana } from '@kbn/kibana-react-plugin/public';
import { SavedObjectNotFound } from '@kbn/kibana-utils-plugin/common';
import { useEffect, useState } from 'react';
import { APM_STATIC_DATA_VIEW_ID } from '../../common/data_view_constants';
import { useApmPluginContext } from '../context/apm_plugin/use_apm_plugin_context';
import { ApmPluginStartDeps } from '../plugin';
import { callApmApi } from '../services/rest/create_call_apm_api';

async function createStaticApmDataView() {
const res = await callApmApi('POST /internal/apm/data_view/static', {
signal: null,
});
return res.dataView;
}

async function getApmDataViewTitle() {
const res = await callApmApi('GET /internal/apm/data_view/title', {
signal: null,
});
return res.apmDataViewTitle;
}

export function useApmDataView() {
const { services } = useKibana<ApmPluginStartDeps>();
const { core } = useApmPluginContext();
const [dataView, setDataView] = useState<DataView | undefined>();

const canCreateDataView =
core.application.capabilities.savedObjectsManagement.edit;

useEffect(() => {
async function fetchDataView() {
try {
// load static data view
return await services.dataViews.get(APM_STATIC_DATA_VIEW_ID);
} catch (e) {
// re-throw if an unhandled error occurred
const notFound = e instanceof SavedObjectNotFound;
if (!notFound) {
throw e;
}

// create static data view if user has permissions
if (canCreateDataView) {
return createStaticApmDataView();
} else {
// or create dynamic data view if user does not have permissions to create a static
const title = await getApmDataViewTitle();
return services.dataViews.create({ title });
}
}
}

fetchDataView().then((dv) => setDataView(dv));
}, [canCreateDataView, services.dataViews]);

return { dataView };
}
27 changes: 0 additions & 27 deletions x-pack/plugins/apm/public/hooks/use_dynamic_data_view.ts

This file was deleted.

16 changes: 0 additions & 16 deletions x-pack/plugins/apm/public/hooks/use_static_data_view.ts

This file was deleted.

14 changes: 0 additions & 14 deletions x-pack/plugins/apm/public/services/rest/data_view.ts

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/

import { SavedObjectsErrorHelpers } from '@kbn/core/server';
import { DataViewsService } from '@kbn/data-views-plugin/common';
import { DataView, DataViewsService } from '@kbn/data-views-plugin/common';
import {
TRACE_ID,
TRANSACTION_ID,
Expand All @@ -26,18 +26,18 @@ export async function createStaticDataView({
dataViewService: DataViewsService;
config: APMConfig;
setup: Setup;
}): Promise<boolean> {
}): Promise<DataView | undefined> {
return withApmSpan('create_static_data_view', async () => {
// don't auto-create APM data view if it's been disabled via the config
if (!config.autoCreateApmDataView) {
return false;
return;
}

// Discover and other apps will throw errors if an data view exists without having matching indices.
// The following ensures the data view is only created if APM data is found
const hasData = await hasHistoricalAgentData(setup);
if (!hasData) {
return false;
return;
}

const apmDataViewTitle = getApmDataViewTitle(setup.indices);
Expand All @@ -47,16 +47,16 @@ export async function createStaticDataView({
});

if (!shouldCreateOrUpdate) {
return false;
return;
}

try {
await withApmSpan('create_index_pattern_saved_object', async () => {
await dataViewService.createAndSave(
return await withApmSpan('create_data_view', async () => {
const dataView = await dataViewService.createAndSave(
{
allowNoIndex: true,
id: APM_STATIC_DATA_VIEW_ID,
name: 'APM UI',
name: 'APM',
title: apmDataViewTitle,
timeFieldName: '@timestamp',

Expand All @@ -80,14 +80,14 @@ export async function createStaticDataView({
},
true
);
});

return true;
return dataView;
});
} catch (e) {
// if the data view (saved object) already exists a conflict error (code: 409) will be thrown
// that error should be silenced
if (SavedObjectsErrorHelpers.isConflictError(e)) {
return false;
return;
}
throw e;
}
Expand Down
7 changes: 4 additions & 3 deletions x-pack/plugins/apm/server/routes/data_view/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
* 2.0.
*/

import { DataView } from '@kbn/data-views-plugin/common';
import { createStaticDataView } from './create_static_data_view';
import { setupRequest } from '../../lib/helpers/setup_request';
import { createApmServerRoute } from '../apm_routes/create_apm_server_route';
Expand All @@ -14,7 +15,7 @@ import { getApmIndices } from '../settings/apm_indices/get_apm_indices';
const staticDataViewRoute = createApmServerRoute({
endpoint: 'POST /internal/apm/data_view/static',
options: { tags: ['access:apm'] },
handler: async (resources): Promise<{ created: boolean }> => {
handler: async (resources): Promise<{ dataView: DataView | undefined }> => {
const setup = await setupRequest(resources);
const { context, plugins, request, config } = resources;

Expand All @@ -27,13 +28,13 @@ const staticDataViewRoute = createApmServerRoute({
true
);

const didCreateDataView = await createStaticDataView({
const dataView = await createStaticDataView({
dataViewService,
config,
setup,
});

return { created: didCreateDataView };
return { dataView };
},
});

Expand Down
1 change: 0 additions & 1 deletion x-pack/plugins/translations/translations/fr-FR.json
Original file line number Diff line number Diff line change
Expand Up @@ -8565,7 +8565,6 @@
"xpack.apm.tutorial.specProvider.artifacts.dashboards.linkLabel": "Tableau de bord APM",
"xpack.apm.tutorial.specProvider.longDescription": "Le monitoring des performances applicatives (APM) collecte les indicateurs et les erreurs de performance approfondies depuis votre application. Cela vous permet de monitorer les performances de milliers d'applications en temps réel. [Learn more]({learnMoreLink}).",
"xpack.apm.tutorial.specProvider.name": "APM",
"xpack.apm.tutorial.specProvider.savedObjectsInstallMsg": "Une vue de données APM est requise pour certaines fonctionnalités de l'interface utilisateur APM.",
"xpack.apm.tutorial.startServer.textPre": "Le serveur traite et conserve les indicateurs de performances de l'application dans Elasticsearch.",
"xpack.apm.tutorial.startServer.title": "Lancer le serveur APM",
"xpack.apm.tutorial.windowsServerInstructions.textPost": "Remarque : si l'exécution du script est désactivée dans votre système, vous devez définir la politique d'exécution de la session en cours de sorte que l'exécution du script soit autorisée. Par exemple : {command}.",
Expand Down
1 change: 0 additions & 1 deletion x-pack/plugins/translations/translations/ja-JP.json
Original file line number Diff line number Diff line change
Expand Up @@ -8557,7 +8557,6 @@
"xpack.apm.tutorial.specProvider.artifacts.dashboards.linkLabel": "APM ダッシュボード",
"xpack.apm.tutorial.specProvider.longDescription": "アプリケーションパフォーマンスモニタリング(APM)は、アプリケーション内から詳細なパフォーマンスメトリックやエラーを収集します。何千ものアプリケーションのパフォーマンスをリアルタイムで監視できます。[詳細]({learnMoreLink})。",
"xpack.apm.tutorial.specProvider.name": "APM",
"xpack.apm.tutorial.specProvider.savedObjectsInstallMsg": "APM UIの機能にはAPMデータビューが必要なものがあります。",
"xpack.apm.tutorial.startServer.textPre": "サーバーは、Elasticsearch アプリケーションのパフォーマンスメトリックを処理し保存します。",
"xpack.apm.tutorial.startServer.title": "APM Server の起動",
"xpack.apm.tutorial.windowsServerInstructions.textPost": "注:システムでスクリプトの実行が無効な場合、スクリプトを実行するために現在のセッションの実行ポリシーの設定が必要となります。例:{command}。",
Expand Down
1 change: 0 additions & 1 deletion x-pack/plugins/translations/translations/zh-CN.json
Original file line number Diff line number Diff line change
Expand Up @@ -8571,7 +8571,6 @@
"xpack.apm.tutorial.specProvider.artifacts.dashboards.linkLabel": "APM 仪表板",
"xpack.apm.tutorial.specProvider.longDescription": "应用程序性能监测 (APM) 从您的应用程序内收集深入全面的性能指标和错误。其允许您实时监测数以千计的应用程序的性能。[了解详情]({learnMoreLink})。",
"xpack.apm.tutorial.specProvider.name": "APM",
"xpack.apm.tutorial.specProvider.savedObjectsInstallMsg": "APM UI 中的某些功能需要 APM 数据视图。",
"xpack.apm.tutorial.startServer.textPre": "服务器在 Elasticsearch 中处理并存储应用程序性能指标。",
"xpack.apm.tutorial.startServer.title": "启动 APM Server",
"xpack.apm.tutorial.windowsServerInstructions.textPost": "注意:如果您的系统禁用了脚本执行,则需要为当前会话设置执行策略,以允许脚本运行。示例:{command}。",
Expand Down
Loading

0 comments on commit 2bcdc41

Please sign in to comment.