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

feat(Timeseries): Add total resource consumption in legend #108

Merged
merged 3 commits into from
Aug 2, 2024
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 @@ -4,15 +4,18 @@ import { map, Observable } from 'rxjs';

import { LabelsDataSource } from '../../../infrastructure/labels/LabelsDataSource';

// General note: because (e.g.) SceneLabelValuesTimeseries sets the data provider in its constructor, data can come as undefined, hence all the optional chaining operators
// in the transformers below

export const addRefId = () => (source: Observable<DataFrame[]>) =>
source.pipe(map((data: DataFrame[]) => data.map((d, i) => merge(d, { refId: `${d.refId}-${i}` }))));
source.pipe(map((data: DataFrame[]) => data?.map((d, i) => merge(d, { refId: `${d.refId}-${i}` }))));

export const addStats = () => (source: Observable<DataFrame[]>) =>
source.pipe(
map((data: DataFrame[]) => {
const totalSeriesCount = data.length;
const totalSeriesCount = data?.length;

return data.map((d) => {
return data?.map((d) => {
const allValuesSum = d.fields
?.find((field) => field.type === 'number')
?.values.reduce((acc: number, value: number) => acc + value, 0);
Expand All @@ -39,7 +42,7 @@ export const addStats = () => (source: Observable<DataFrame[]>) =>
export const sortSeries = () => (source: Observable<DataFrame[]>) =>
source.pipe(
map((data: DataFrame[]) =>
data.sort((d1, d2) => {
data?.sort((d1, d2) => {
const d1Sum = d1.meta?.stats?.find(({ displayName }) => displayName === 'allValuesSum')?.value || 0;
const d2Sum = d2.meta?.stats?.find(({ displayName }) => displayName === 'allValuesSum')?.value || 0;
return d2Sum - d1Sum;
Expand All @@ -48,4 +51,4 @@ export const sortSeries = () => (source: Observable<DataFrame[]>) =>
);

export const limitNumberOfSeries = () => (source: Observable<DataFrame[]>) =>
source.pipe(map((data: DataFrame[]) => data.slice(0, LabelsDataSource.MAX_TIMESERIES_LABEL_VALUES)));
source.pipe(map((data: DataFrame[]) => data?.slice(0, LabelsDataSource.MAX_TIMESERIES_LABEL_VALUES)));
15 changes: 12 additions & 3 deletions src/pages/ProfilesExplorerView/components/SceneLabelValueStat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
VizPanel,
VizPanelState,
} from '@grafana/scenes';
import { BigValueGraphMode, BigValueTextMode } from '@grafana/ui';
import React from 'react';

import { getColorByIndex } from '../helpers/getColorByIndex';
Expand All @@ -17,16 +18,24 @@ interface SceneLabelValueStatState extends SceneObjectState {
}

export class SceneLabelValueStat extends SceneObjectBase<SceneLabelValueStatState> {
constructor({ item, headerActions }: { item: GridItemData; headerActions: () => VizPanelState['headerActions'] }) {
constructor({
item,
headerActions,
}: {
item: GridItemData;
headerActions: (item: GridItemData) => VizPanelState['headerActions'];
}) {
super({
key: 'stat-label-value',
body: PanelBuilders.stat()
.setTitle(item.label)
.setDescription('This panel displays aggregate values over the current time period')
.setData(buildTimeSeriesQueryRunner(item.queryRunnerParams))
.setHeaderActions(headerActions())
.setColor({ mode: 'fixed', fixedColor: getColorByIndex(item.index) })
.setHeaderActions(headerActions(item))
.setOption('reduceOptions', { values: false, calcs: ['sum'] })
.setColor({ mode: 'fixed', fixedColor: getColorByIndex(item.index) })
.setOption('graphMode', BigValueGraphMode.None)
.setOption('textMode', BigValueTextMode.Value)
.build(),
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,13 @@ interface SceneLabelValuesBarGaugeState extends SceneObjectState {
}

export class SceneLabelValuesBarGauge extends SceneObjectBase<SceneLabelValuesBarGaugeState> {
constructor({ item, headerActions }: { item: GridItemData; headerActions: () => VizPanelState['headerActions'] }) {
constructor({
item,
headerActions,
}: {
item: GridItemData;
headerActions: (item: GridItemData) => VizPanelState['headerActions'];
}) {
super({
key: 'bar-gauge-label-values',
body: PanelBuilders.bargauge()
Expand All @@ -32,7 +38,7 @@ export class SceneLabelValuesBarGauge extends SceneObjectBase<SceneLabelValuesBa
transformations: [addRefId, addStats, sortSeries],
})
)
.setHeaderActions(headerActions())
.setHeaderActions(headerActions(item))
.build(),
});

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { DataFrame, FieldMatcherID, LoadingState } from '@grafana/data';
import { DataFrame, FieldMatcherID, getValueFormat, LoadingState } from '@grafana/data';
import {
PanelBuilders,
SceneComponentProps,
Expand Down Expand Up @@ -33,7 +33,7 @@ export class SceneLabelValuesTimeseries extends SceneObjectBase<SceneLabelValues
displayAllValues,
}: {
item: GridItemData;
headerActions: () => VizPanelState['headerActions'];
headerActions: (item: GridItemData) => VizPanelState['headerActions'];
displayAllValues?: boolean;
}) {
super({
Expand All @@ -48,7 +48,7 @@ export class SceneLabelValuesTimeseries extends SceneObjectBase<SceneLabelValues
: [addRefId, addStats, sortSeries, limitNumberOfSeries],
})
)
.setHeaderActions(headerActions())
.setHeaderActions(headerActions(item))
.build(),
});

Expand Down Expand Up @@ -76,17 +76,23 @@ export class SceneLabelValuesTimeseries extends SceneObjectBase<SceneLabelValues
}

getConfig(item: GridItemData, series: DataFrame[]) {
const totalSeriesCount =
series[0].meta?.stats?.find(({ displayName }) => displayName === 'totalSeriesCount')?.value || 0;
let { title } = this.state.body.state;
let description;

const hasTooManySeries = totalSeriesCount > LabelsDataSource.MAX_TIMESERIES_LABEL_VALUES;
if (item.queryRunnerParams.groupBy?.label) {
title = series.length > 1 ? `${item.label} (${series.length})` : item.label;

const description = hasTooManySeries
? `The number of series on this panel has been reduced from ${totalSeriesCount} to ${LabelsDataSource.MAX_TIMESERIES_LABEL_VALUES} to preserve readability. To view all the data, click on the expand icon on this panel.`
: undefined;
const totalSeriesCount =
series[0].meta?.stats?.find(({ displayName }) => displayName === 'totalSeriesCount')?.value || 0;
const hasTooManySeries = totalSeriesCount > LabelsDataSource.MAX_TIMESERIES_LABEL_VALUES;

description = hasTooManySeries
? `The number of series on this panel has been reduced from ${totalSeriesCount} to ${LabelsDataSource.MAX_TIMESERIES_LABEL_VALUES} to preserve readability. To view all the data, click on the expand icon on this panel.`
: undefined;
}

return {
title: series.length > 1 ? `${item.label} (${series.length})` : item.label,
title,
description,
fieldConfig: {
defaults: {
Expand Down Expand Up @@ -118,19 +124,35 @@ export class SceneLabelValuesTimeseries extends SceneObjectBase<SceneLabelValues
getOverrides(item: GridItemData, series: DataFrame[]) {
const groupByLabel = item.queryRunnerParams.groupBy?.label;

return series.map((serie, i) => ({
matcher: { id: FieldMatcherID.byFrameRefID, options: serie.refId },
properties: [
{
id: 'displayName',
value: groupByLabel ? serie.fields[1].labels?.[groupByLabel] : serie.fields[1].name,
},
{
id: 'color',
value: { mode: 'fixed', fixedColor: getColorByIndex(item.index + i) },
},
],
}));
return series.map((serie, i) => {
let displayName = groupByLabel ? serie.fields[1].labels?.[groupByLabel] : serie.fields[1].name;

if (series.length === 1) {
const allValuesSum = serie.meta?.stats?.find(({ displayName }) => displayName === 'allValuesSum')?.value || 0;
const { unit } = serie.fields[1].config;
const formattedValue = getValueFormat(unit)(allValuesSum);

displayName = `${displayName} · total = ${formattedValue.text}${formattedValue.suffix}`;
}

return {
matcher: { id: FieldMatcherID.byFrameRefID, options: serie.refId },
properties: [
{
id: 'displayName',
value: displayName,
},
{
id: 'color',
value: { mode: 'fixed', fixedColor: getColorByIndex(item.index + i) },
},
],
};
});
}

updateTitle(newTitle: string) {
this.state.body.setState({ title: newTitle });
}

static Component({ model }: SceneComponentProps<SceneLabelValuesTimeseries>) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,69 +1,55 @@
import {
PanelBuilders,
SceneComponentProps,
SceneObjectBase,
SceneObjectState,
VariableDependencyConfig,
VizPanel,
VizPanelState,
} from '@grafana/scenes';
import { getProfileMetric, ProfileMetricId } from '@shared/infrastructure/profile-metrics/getProfileMetric';
import React from 'react';

import { getColorByIndex } from '../helpers/getColorByIndex';
import { getSceneVariableValue } from '../helpers/getSceneVariableValue';
import { getProfileMetricLabel } from '../infrastructure/series/helpers/getProfileMetricLabel';
import { buildTimeSeriesQueryRunner } from '../infrastructure/timeseries/buildTimeSeriesQueryRunner';
import { PanelType } from './SceneByVariableRepeaterGrid/components/ScenePanelTypeSwitcher';
import { GridItemData } from './SceneByVariableRepeaterGrid/types/GridItemData';
import { SceneLabelValuesTimeseries } from './SceneLabelValuesTimeseries';

interface SceneMainServiceTimeseriesState extends SceneObjectState {
headerActions: (item: GridItemData) => VizPanelState['headerActions'];
body?: VizPanel;
body?: SceneLabelValuesTimeseries;
}

export class SceneMainServiceTimeseries extends SceneObjectBase<SceneMainServiceTimeseriesState> {
static MIN_HEIGHT = 200;

protected _variableDependency = new VariableDependencyConfig(this, {
variableNames: ['dataSource', 'serviceName', 'profileMetricId'],
variableNames: ['profileMetricId'],
onVariableUpdateCompleted: () => {
this.state.body?.setState({
title: this.buildTitle(),
});
this.state.body?.updateTitle(this.buildTitle());
},
});

constructor({ headerActions }: { headerActions: SceneMainServiceTimeseriesState['headerActions'] }) {
super({ headerActions });
constructor({ headerActions }: { headerActions: (item: GridItemData) => VizPanelState['headerActions'] }) {
super({
body: undefined,
});

this.addActivationHandler(this.onActivate.bind(this));
this.addActivationHandler(this.onActivate.bind(this, headerActions));
}

onActivate() {
const item = {
index: 0,
value: '',
label: '',
panelType: PanelType.TIMESERIES,
// let actions interpolate
queryRunnerParams: {},
};

const body = PanelBuilders.timeseries()
.setTitle(this.buildTitle())
.setData(buildTimeSeriesQueryRunner({}))
.setMin(0)
.setColor({ mode: 'fixed', fixedColor: getColorByIndex(0) })
.setCustomFieldConfig('fillOpacity', 9)
.setHeaderActions(this.state.headerActions(item))
.build();

body.setState({
key: 'main-service-timeseries',
onActivate(headerActions: (item: GridItemData) => VizPanelState['headerActions']) {
this.setState({
body: new SceneLabelValuesTimeseries({
item: {
index: 0,
value: '',
label: this.buildTitle(),
panelType: PanelType.TIMESERIES,
// let actions interpolate the missing values
queryRunnerParams: {},
},
headerActions,
}),
});

this.setState({ body });
}

buildTitle() {
Expand Down
Loading