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

Pyroscope: Add query range to ProfileTypes API call #79574

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
18 changes: 15 additions & 3 deletions pkg/tsdb/grafana-pyroscope-datasource/instance.go
Expand Up @@ -30,7 +30,7 @@ var (
)

type ProfilingClient interface {
ProfileTypes(context.Context) ([]*ProfileType, error)
ProfileTypes(ctx context.Context, start int64, end int64) ([]*ProfileType, error)
LabelNames(ctx context.Context, labelSelector string, start int64, end int64) ([]string, error)
LabelValues(ctx context.Context, label string, labelSelector string, start int64, end int64) ([]string, error)
GetSeries(ctx context.Context, profileTypeID string, labelSelector string, start int64, end int64, groupBy []string, step float64) (*SeriesResponse, error)
Expand Down Expand Up @@ -89,7 +89,17 @@ func (d *PyroscopeDatasource) CallResource(ctx context.Context, req *backend.Cal

func (d *PyroscopeDatasource) profileTypes(ctx context.Context, req *backend.CallResourceRequest, sender backend.CallResourceResponseSender) error {
ctxLogger := logger.FromContext(ctx)
types, err := d.client.ProfileTypes(ctx)

u, err := url.Parse(req.URL)
if err != nil {
ctxLogger.Error("Failed to parse URL", "error", err, "function", logEntrypoint())
return err
}
query := u.Query()
start, _ := strconv.ParseInt(query.Get("start"), 10, 64)
end, _ := strconv.ParseInt(query.Get("end"), 10, 64)

types, err := d.client.ProfileTypes(ctx, start, end)
if err != nil {
ctxLogger.Error("Received error from client", "error", err, "function", logEntrypoint())
return err
Expand Down Expand Up @@ -231,7 +241,9 @@ func (d *PyroscopeDatasource) CheckHealth(ctx context.Context, _ *backend.CheckH
status := backend.HealthStatusOk
message := "Data source is working"

if _, err := d.client.ProfileTypes(ctx); err != nil {
start := time.Now().Add(-5 * time.Minute)
end := time.Now()
if _, err := d.client.ProfileTypes(ctx, start.UnixMilli(), end.UnixMilli()); err != nil {
status = backend.HealthStatusError
message = err.Error()
}
Expand Down
7 changes: 5 additions & 2 deletions pkg/tsdb/grafana-pyroscope-datasource/pyroscopeClient.go
Expand Up @@ -70,10 +70,13 @@ func NewPyroscopeClient(httpClient *http.Client, url string) *PyroscopeClient {
}
}

func (c *PyroscopeClient) ProfileTypes(ctx context.Context) ([]*ProfileType, error) {
func (c *PyroscopeClient) ProfileTypes(ctx context.Context, start int64, end int64) ([]*ProfileType, error) {
ctx, span := tracing.DefaultTracer().Start(ctx, "datasource.pyroscope.ProfileTypes")
defer span.End()
res, err := c.connectClient.ProfileTypes(ctx, connect.NewRequest(&querierv1.ProfileTypesRequest{}))
res, err := c.connectClient.ProfileTypes(ctx, connect.NewRequest(&querierv1.ProfileTypesRequest{
Start: start,
End: end,
}))
if err != nil {
logger.Error("Received error from client", "error", err, "function", logEntrypoint())
span.RecordError(err)
Expand Down
2 changes: 1 addition & 1 deletion pkg/tsdb/grafana-pyroscope-datasource/query_test.go
Expand Up @@ -275,7 +275,7 @@ type FakeClient struct {
Args []any
}

func (f *FakeClient) ProfileTypes(ctx context.Context) ([]*ProfileType, error) {
func (f *FakeClient) ProfileTypes(ctx context.Context, start int64, end int64) ([]*ProfileType, error) {
return []*ProfileType{
{
ID: "type:1",
Expand Down
Expand Up @@ -55,7 +55,9 @@ export function TraceToProfilesSettings({ options, onOptionsChange }: Props) {
supportedDataSourceTypes.includes(dataSource.type) &&
dataSource.uid === options.jsonData.tracesToProfiles?.datasourceUid
) {
dataSource.getProfileTypes().then((profileTypes) => {
const end = Date.now();
const start = end - 24 * 60 * 60 * 1000; // 1 day ago
dataSource.getProfileTypes(start, end).then((profileTypes) => {
Comment on lines +58 to +60
Copy link
Contributor Author

Choose a reason for hiding this comment

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

@joey-grafana I am not entirely sure if this is a good thing to do and what its impact is

setProfileTypes(profileTypes);
});
} else {
Expand Down
@@ -1,5 +1,6 @@
import React, { useEffect, useMemo, useState } from 'react';

import { TimeRange } from '@grafana/data';
import { Cascader, CascaderOption } from '@grafana/ui';

import { PyroscopeDataSource } from '../datasource';
Expand Down Expand Up @@ -70,16 +71,22 @@ function useCascaderOptions(profileTypes?: ProfileTypeMessage[]): CascaderOption
* This is exported and not used directly in the ProfileTypesCascader component because in some case we need to know
* the profileTypes before rendering the cascader.
* @param datasource
* @param range
*/
export function useProfileTypes(datasource: PyroscopeDataSource) {
export function useProfileTypes(datasource: PyroscopeDataSource, range?: TimeRange) {
const [profileTypes, setProfileTypes] = useState<ProfileTypeMessage[]>();

const impreciseRange = {
to: Math.ceil((range?.to.valueOf() || 0) / 60000) * 60000,
from: Math.floor((range?.from.valueOf() || 0) / 60000) * 60000,
};

useEffect(() => {
(async () => {
const profileTypes = await datasource.getProfileTypes();
const profileTypes = await datasource.getProfileTypes(impreciseRange.from.valueOf(), impreciseRange.to.valueOf());
setProfileTypes(profileTypes);
})();
}, [datasource]);
}, [datasource, impreciseRange.from, impreciseRange.to]);

return profileTypes;
}
Expand Up @@ -27,7 +27,7 @@ export function QueryEditor(props: Props) {
onRunQuery();
}

const profileTypes = useProfileTypes(datasource);
const profileTypes = useProfileTypes(datasource, range);
const { labels, getLabelValues, onLabelSelectorChange } = useLabels(range, datasource, query, onChange);
useNormalizeQuery(query, profileTypes, onChange, app);

Expand Down
@@ -1,6 +1,6 @@
import React, { useEffect, useState } from 'react';

import { QueryEditorProps, SelectableValue } from '@grafana/data';
import { QueryEditorProps, SelectableValue, TimeRange } from '@grafana/data';
import { InlineField, InlineFieldRow, LoadingPlaceholder, Select } from '@grafana/ui';

import { ProfileTypesCascader, useProfileTypes } from './QueryEditor/ProfileTypesCascader';
Expand Down Expand Up @@ -58,6 +58,7 @@ export function VariableQueryEditor(props: QueryEditorProps<PyroscopeDataSource,
{(props.query.type === 'labelValue' || props.query.type === 'label') && (
<ProfileTypeRow
datasource={props.datasource}
range={props.range}
initialValue={props.query.profileTypeId}
onChange={(val) => {
// To make TS happy
Expand Down Expand Up @@ -131,8 +132,9 @@ function ProfileTypeRow(props: {
datasource: PyroscopeDataSource;
onChange: (val: string) => void;
initialValue?: string;
range?: TimeRange;
}) {
const profileTypes = useProfileTypes(props.datasource);
const profileTypes = useProfileTypes(props.datasource, props.range);
return (
<InlineFieldRow>
<InlineField
Expand Down
Expand Up @@ -9,7 +9,7 @@ import { PyroscopeDataSource } from './datasource';
import { ProfileTypeMessage, VariableQuery } from './types';

export interface DataAPI {
getProfileTypes(): Promise<ProfileTypeMessage[]>;
getProfileTypes(start: number, end: number): Promise<ProfileTypeMessage[]>;
getLabelNames(query: string, start: number, end: number): Promise<string[]>;
getLabelValues(query: string, label: string, start: number, end: number): Promise<string[]>;
}
Expand All @@ -26,7 +26,9 @@ export class VariableSupport extends CustomVariableSupport<PyroscopeDataSource>

query(request: DataQueryRequest<VariableQuery>): Observable<DataQueryResponse> {
if (request.targets[0].type === 'profileType') {
return from(this.dataAPI.getProfileTypes()).pipe(
return from(
this.dataAPI.getProfileTypes(this.timeSrv.timeRange().from.valueOf(), this.timeSrv.timeRange().to.valueOf())
).pipe(
map((values) => {
return { data: values.map<MetricFindValue>((v) => ({ text: v.label, value: v.id })) };
})
Expand Down
Expand Up @@ -48,8 +48,11 @@ export class PyroscopeDataSource extends DataSourceWithBackend<Query, PyroscopeD
});
}

async getProfileTypes(): Promise<ProfileTypeMessage[]> {
return await this.getResource('profileTypes');
async getProfileTypes(start: number, end: number): Promise<ProfileTypeMessage[]> {
return await this.getResource('profileTypes', {
start,
end,
});
}

async getLabelNames(query: string, start: number, end: number): Promise<string[]> {
Expand Down