Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[APM] Added component for rendering dashboard-based service runtime metrics #157724

Merged
merged 5 commits into from
May 23, 2023
Merged
Show file tree
Hide file tree
Changes from 4 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
2 changes: 2 additions & 0 deletions x-pack/plugins/apm/kibana.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
"configPath": ["xpack", "apm"],
"requiredPlugins": [
"data",
"dashboard",
"controls",
"embeddable",
"features",
"infra",
Expand Down
17 changes: 17 additions & 0 deletions x-pack/plugins/apm/public/components/app/metrics/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ import { useApmServiceContext } from '../../../context/apm_service/use_apm_servi
import { ServerlessMetrics } from './serverless_metrics';
import { ServiceMetrics } from './service_metrics';
import { JvmMetricsOverview } from './jvm_metrics_overview';
import { JsonMetricsDashboard } from './static_dashboard';
import { hasDashboardFile } from './static_dashboard/helper';

export function Metrics() {
const { agentName, runtimeName, serverlessType } = useApmServiceContext();
Expand All @@ -31,5 +33,20 @@ export function Metrics() {
return <ServerlessMetrics />;
}

const dashboardFile = hasDashboardFile({
agentName,
runtimeName,
serverlessType,
});
if (dashboardFile) {
return (
<JsonMetricsDashboard
agentName={agentName}
runtimeName={runtimeName}
serverlessType={serverlessType}
/>
);
}

return <ServiceMetrics />;
}

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/*
* 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 type { DashboardPanelMap } from '@kbn/dashboard-plugin/common';
import { APM_STATIC_DATA_VIEW_ID } from '../../../../../common/data_view_constants';

import nodejs from './dashboards/nodejs.json';
Copy link
Member

@sorenlouv sorenlouv May 22, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: We might want to import these dynamically to avoid increasing the bundle size. Right now the APM app increases with 27kb which is not terrible but if 20 dashboards are loaded up front it might be noticeable.

The syntax is something like this:

await import(path)

And you'd have to defer loading it, until you actually need it (in getDashboardFile I assume)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@sqren Pushed a commit with dynamic importing of the dashboard files.


const AGENT_NAME_DASHBOARD_FILE_MAPPING: Record<string, any> = {
nodejs,
};

export interface MetricsDashboardProps {
agentName?: string;
runtimeName?: string;
serverlessType?: string;
}

export function hasDashboardFile(props: MetricsDashboardProps) {
return !!getDashboardFile(props);
}

function getDashboardFile({ agentName }: MetricsDashboardProps) {
const dashboardFile =
agentName && AGENT_NAME_DASHBOARD_FILE_MAPPING[agentName];
return dashboardFile;
}

export function getDashboardPanelMap(
props: MetricsDashboardProps
): DashboardPanelMap | undefined {
const panelsRawObj = getDashboardFile(props);

if (!panelsRawObj) {
return undefined;
}

const panelsStr: string = (
panelsRawObj.attributes.panelsJSON as string
).replaceAll('APM_STATIC_DATA_VIEW_ID', APM_STATIC_DATA_VIEW_ID);

const panelsRawObjects = JSON.parse(panelsStr) as any[];

return panelsRawObjects.reduce(
(acc, panel) => ({
...acc,
[panel.gridData.i]: {
type: panel.type,
gridData: panel.gridData,
explicitInput: {
id: panel.panelIndex,
...panel.embeddableConfig,
title: panel.title,
},
},
}),
{}
) as DashboardPanelMap;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
/*
* 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 React, { useState, useEffect } from 'react';

import { ViewMode } from '@kbn/embeddable-plugin/public';
import {
AwaitingDashboardAPI,
DashboardRenderer,
} from '@kbn/dashboard-plugin/public';
import { DataView } from '@kbn/data-views-plugin/common';
import { buildExistsFilter, buildPhraseFilter, Filter } from '@kbn/es-query';
import { i18n } from '@kbn/i18n';
import { controlGroupInputBuilder } from '@kbn/controls-plugin/public';
import { getDefaultControlGroupInput } from '@kbn/controls-plugin/common';
import { APM_STATIC_DATA_VIEW_ID } from '../../../../../common/data_view_constants';
import {
ENVIRONMENT_ALL,
ENVIRONMENT_NOT_DEFINED,
} from '../../../../../common/environment_filter_values';
import { useApmPluginContext } from '../../../../context/apm_plugin/use_apm_plugin_context';
import { useApmDataView } from '../../../../hooks/use_apm_data_view';
import { useApmServiceContext } from '../../../../context/apm_service/use_apm_service_context';
import { useApmParams } from '../../../../hooks/use_apm_params';

import { getDashboardPanelMap, MetricsDashboardProps } from './helper';

export function JsonMetricsDashboard(dashboardProps: MetricsDashboardProps) {
const [dashboard, setDashboard] = useState<AwaitingDashboardAPI>();

const {
query: { environment, kuery, rangeFrom, rangeTo },
} = useApmParams('/services/{serviceName}/metrics');

const {
core: { notifications },
} = useApmPluginContext();

const { dataView } = useApmDataView();

const { serviceName } = useApmServiceContext();

useEffect(() => {
if (!dashboard) return;
dashboard.updateInput({
timeRange: { from: rangeFrom, to: rangeTo },
query: { query: kuery, language: 'kuery' },
});
}, [kuery, dashboard, rangeFrom, rangeTo]);

useEffect(() => {
if (!dashboard || !dataView) return;

dashboard.updateInput({
filters: dataView ? getFilters(serviceName, environment, dataView) : [],
});
}, [dataView, serviceName, environment, dashboard]);

try {
const panels = getDashboardPanelMap(dashboardProps);

if (!panels) {
throw new Error('Failed parsing dashboard panels.');
}

return (
<DashboardRenderer
getCreationOptions={async () => {
const builder = controlGroupInputBuilder;
const controlGroupInput = getDefaultControlGroupInput();

await builder.addDataControlFromField(controlGroupInput, {
dataViewId: APM_STATIC_DATA_VIEW_ID,
title: 'Node name',
fieldName: 'service.node.name',
width: 'medium',
grow: true,
});

return {
useControlGroupIntegration: true,
initialInput: {
viewMode: ViewMode.VIEW,
panels,
controlGroupInput,
},
};
}}
ref={setDashboard}
/>
);
} catch (error) {
notifications.toasts.addDanger(
getLoadFailureToastLabels(dashboardProps, error)
);
return <></>;
}
}

function getFilters(
serviceName: string,
environment: string,
dataView: DataView
): Filter[] {
const filters: Filter[] = [];

const serviceNameField = dataView.getFieldByName('service.name');
if (serviceNameField) {
const serviceNameFilter = buildPhraseFilter(
serviceNameField,
serviceName,
dataView
);
filters.push(serviceNameFilter);
}

const environmentField = dataView.getFieldByName('service.environment');
if (
environmentField &&
environment &&
environment !== ENVIRONMENT_ALL.value
) {
if (environment === ENVIRONMENT_NOT_DEFINED.value) {
const envExistsFilter = buildExistsFilter(environmentField, dataView);
envExistsFilter.meta.negate = true;
filters.push(envExistsFilter);
} else {
const environmentFilter = buildPhraseFilter(
environmentField,
serviceName,
dataView
);
filters.push(environmentFilter);
}
}

return filters;
}

function getLoadFailureToastLabels(props: MetricsDashboardProps, error: Error) {
return {
title: i18n.translate(
'xpack.apm.runtimeMetricsJsonDashboards.loadFailure.toast.title',
{
defaultMessage:
'Error while loading dashboard for agent "{agentName}" on runtime "{runtimeName}".',
values: {
agentName: props.agentName ?? 'unknown',
runtimeName: props.runtimeName ?? 'unknown',
},
}
),
text: error.message,
};
}
2 changes: 2 additions & 0 deletions x-pack/plugins/apm/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,8 @@
"@kbn/shared-ux-prompt-not-found",
"@kbn/ui-actions-plugin",
"@kbn/observability-alert-details",
"@kbn/dashboard-plugin",
"@kbn/controls-plugin",
],
"exclude": [
"target/**/*",
Expand Down