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/uptime query v3 #1054

Open
wants to merge 14 commits into
base: main
Choose a base branch
from
Open
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
Binary file added docs/uptime/images/20p_accuracy.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/uptime/images/control_1p_overlap.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/uptime/images/control_1p_overlap_4c.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/uptime/images/control_1p_random.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/uptime/images/control_20p_random.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/uptime/images/control_2p_no_overlap.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/uptime/images/control_2p_overlap.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/uptime/images/control_2p_random.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/uptime/images/control_2p_shared_random.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/uptime/images/in_phase_probes.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/uptime/images/logs_vs_visualization.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/uptime/images/out_of_phase_probes.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/uptime/images/sm-architecture.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/uptime/images/v1_v3_comparison.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/uptime/images/without_aggregation.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
289 changes: 289 additions & 0 deletions docs/uptime/uptime.md

Large diffs are not rendered by default.

5 changes: 2 additions & 3 deletions src/components/Gauges/SuccessRateGaugeCheckUptime.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@ type SuccessRateGaugeCheckUptimeProps = {

export const SuccessRateGaugeCheckUptime = ({ check, height, width, onClick }: SuccessRateGaugeCheckUptimeProps) => {
const metricsDS = useMetricsDS();
const { data, isLoading, isFetching } = useCheckUptimeSuccessRate(check);
const value = data ? data[0]?.value?.[1] : null;
const { data = null, isLoading, isFetching } = useCheckUptimeSuccessRate(check);

if (!metricsDS) {
return null;
Expand All @@ -30,7 +29,7 @@ export const SuccessRateGaugeCheckUptime = ({ check, height, width, onClick }: S
width={width}
onClick={onClick}
type={'uptime'}
value={value}
value={data}
unit="%"
/>
);
Expand Down
5 changes: 3 additions & 2 deletions src/data/useLatency.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { type QueryKey, useQuery } from '@tanstack/react-query';

import { Check, CheckType } from 'types';
import { getCheckType, queryMetric } from 'utils';
import { getCheckType } from 'utils';
import { MetricLatency } from 'datasource/responses.types';
import { getStartEnd, queryInstantMetric } from 'data/utils';
import { useMetricsDS } from 'hooks/useMetricsDS';
import { STANDARD_REFRESH_INTERVAL } from 'components/constants';

Expand All @@ -22,7 +23,7 @@ export function useLatency({ job, target, settings }: Check) {
return Promise.reject(`You need to have a metrics datasource available.`);
}

return queryMetric<MetricLatency>(url, getQuery(job, target, type));
return queryInstantMetric<MetricLatency>({ url, query: getQuery(job, target, type), ...getStartEnd() });
},
refetchInterval: (query) => STANDARD_REFRESH_INTERVAL,
select: (data) => {
Expand Down
56 changes: 24 additions & 32 deletions src/data/useSuccessRates.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import { type QueryKey, useQuery } from '@tanstack/react-query';
import { getUptimeQuery } from 'queries/uptime';

import { Check } from 'types';
import { queryMetric } from 'utils';
import { MetricCheckSuccess, MetricProbeSuccessRate } from 'datasource/responses.types';
import { useMetricsDS } from 'hooks/useMetricsDS';
import { STANDARD_REFRESH_INTERVAL } from 'components/constants';
import { getMinStepFromFrequency } from 'scenes/utils';

import { findCheckinMetrics } from './utils';
import { findCheckinMetrics, getStartEnd, queryInstantMetric, queryRangeMetric } from './utils';

const queryKeys: Record<'checkReachability' | 'checkUptime' | 'probeReachability', QueryKey> = {
checkReachability: ['check_reachability'],
Expand All @@ -16,7 +15,6 @@ const queryKeys: Record<'checkReachability' | 'checkUptime' | 'probeReachability
};

export function useChecksReachabilitySuccessRate() {
const { options } = useQueryMetric();
const metricsDS = useMetricsDS();
const url = metricsDS?.url || ``;
const query =
Expand All @@ -32,7 +30,7 @@ export function useChecksReachabilitySuccessRate() {
return Promise.reject(`You need to have a metrics datasource available.`);
}

return queryMetric<MetricCheckSuccess>(url, query, options);
return queryInstantMetric<MetricCheckSuccess>({ url, query, ...getStartEnd() });
},
refetchInterval: (query) => STANDARD_REFRESH_INTERVAL,
enabled: Boolean(metricsDS),
Expand All @@ -50,36 +48,44 @@ export function useCheckReachabilitySuccessRate(check: Check) {
}

export function useCheckUptimeSuccessRate(check: Check) {
const { options } = useQueryMetric(getMinStepFromFrequency(check.frequency));
const metricsDS = useMetricsDS();
const url = metricsDS?.url || ``;

const query = `
ceil(
sum by (instance, job) (increase(probe_all_success_sum{instance="${check.target}", job="${check.job}"}[3h]))
/
(sum by (instance, job) (increase(probe_all_success_count{instance="${check.target}", job="${check.job}"}[3h])) + 1)
)`;
const { expr, interval } = getUptimeQuery({
job: check.job,
instance: check.target,
frequency: check.frequency,
});

return useQuery({
// we add 'now' as an option so can't add it to the query key
// otherwise it would continuously refetch
// eslint-disable-next-line @tanstack/query/exhaustive-deps
queryKey: [...queryKeys.checkUptime, query, url],
queryFn: () => {
queryKey: [...queryKeys.checkUptime, expr, url],
queryFn: async () => {
if (!metricsDS) {
return Promise.reject(`You need to have a metrics datasource available.`);
}

return queryMetric<MetricCheckSuccess>(url, query, options);
return queryRangeMetric({ url, query: expr, ...getStartEnd(), step: interval });
Copy link
Contributor

Choose a reason for hiding this comment

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

Using interval as the step means a value is returned for each time range where there should be a sample. With a single probe, there's some chance for missing data that was published "too late" (and for the same reason, ignoring intervals where there are two samples, from different executions)

},
select: (data) => {
const vals = data[0].values;
const total = vals.reduce((acc, [_, value]) => {
return acc + Number(value);
}, 0);

if (vals.length === 0) {
return null;
}

return total / vals.length;
Comment on lines +71 to +81
Copy link
Contributor

Choose a reason for hiding this comment

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

I'm guessing this will ignore NODATA.

},
refetchInterval: (query) => STANDARD_REFRESH_INTERVAL,
enabled: Boolean(metricsDS),
});
}

export function useProbesReachabilitySuccessRate() {
const { options } = useQueryMetric();
const metricsDS = useMetricsDS();
const url = metricsDS?.url || ``;
const query = 'sum(rate(probe_all_success_sum[3h])) by (probe) / sum(rate(probe_all_success_count[3h])) by (probe)';
Expand All @@ -94,7 +100,7 @@ export function useProbesReachabilitySuccessRate() {
return Promise.reject(`You need to have a metrics datasource available.`);
}

return queryMetric<MetricProbeSuccessRate>(url, query, options);
return queryInstantMetric<MetricProbeSuccessRate>({ url, query, ...getStartEnd() });
},
refetchInterval: (query) => STANDARD_REFRESH_INTERVAL,
enabled: Boolean(metricsDS),
Expand All @@ -110,17 +116,3 @@ export function useProbeReachabilitySuccessRate(probeName?: string) {
data: probe,
};
}

function useQueryMetric(interval?: string) {
const now = Math.floor(Date.now() / 1000);
const threeHoursAgo = now - 60 * 60 * 3;

const options = {
start: threeHoursAgo,
end: now,
step: 0,
interval,
};

return { options };
}
70 changes: 67 additions & 3 deletions src/data/utils.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { AppEvents } from '@grafana/data';
import { isFetchError } from '@grafana/runtime';
import { FetchResponse, getBackendSrv, isFetchError } from '@grafana/runtime';
import appEvents from 'grafana/app/core/app_events';
import { firstValueFrom } from 'rxjs';

import { Check } from 'types';
import { MetricCheckSuccess } from 'datasource/responses.types';

import { InstantMetric, MetricCheckSuccess, MetricDatasourceResponse, RangeMetric } from 'datasource/responses.types';
const severityMapping = {
success: AppEvents.alertSuccess,
warning: AppEvents.alertWarning,
Expand All @@ -30,3 +30,67 @@ export function constructError(desc: string, error: unknown) {

return desc;
}

interface InstantMetricQueryOptions {
url: string;
query: string;
start: number;
end: number;
}

interface RangeMetricQueryOptions extends InstantMetricQueryOptions {
step: string;
}

export function queryInstantMetric<T extends InstantMetric>({ url, query, start, end }: InstantMetricQueryOptions) {
return firstValueFrom(
getBackendSrv().fetch<MetricDatasourceResponse<T>>({
method: 'GET',
url: `${url}/api/v1/query`,
params: {
query,
end,
start,
},
})
).then((res: FetchResponse<MetricDatasourceResponse<T>>) => {
return res.data.data.result.map((metric) => {
return {
...metric,
value: [metric.value[0], Number(metric.value[1])] as [number, number],
};
});
});
}

export function queryRangeMetric<T extends RangeMetric>({ url, query, start, end, step }: RangeMetricQueryOptions) {
return firstValueFrom(
getBackendSrv().fetch<MetricDatasourceResponse<T>>({
method: 'GET',
url: `${url}/api/v1/query_range`,
params: {
query,
end,
start,
step,
},
})
).then((res: FetchResponse<MetricDatasourceResponse<T>>) => {
return res.data.data.result.map((metric) => {
return {
...metric,
values: metric.values.map(([time, value]) => [time, Number(value)]),
};
});
});
}

export function getStartEnd() {
const now = Math.floor(Date.now() / 1000);
const THREE_HOURS_AGO = now - 60 * 60 * 3;

return {
start: THREE_HOURS_AGO,
end: now,
};
}
15 changes: 10 additions & 5 deletions src/datasource/responses.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,11 +110,16 @@ export type UpdateTenantSettingsResult = {

export type Time = number;

export interface Metric {
metric: {};
export interface InstantMetric {
metric: Record<string, string>;
value: [Time, string];
}

export interface RangeMetric {
metric: {};
values: Array<[Time, string]>;
}

export interface MetricDatasourceResponse<T> {
status: string;
data: {
Expand All @@ -123,20 +128,20 @@ export interface MetricDatasourceResponse<T> {
};
}

export interface MetricProbeSuccessRate extends Metric {
export interface MetricProbeSuccessRate extends InstantMetric {
metric: {
probe: string;
};
}

export interface MetricCheckSuccess extends Metric {
export interface MetricCheckSuccess extends InstantMetric {
metric: {
instance: string;
job: string;
};
}

export interface MetricLatency extends Metric {
export interface MetricLatency extends InstantMetric {
metric: {};
}

Expand Down
23 changes: 13 additions & 10 deletions src/page/CheckList/CheckList.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -527,26 +527,29 @@ describe(`bulk select behaviour`, () => {

test(`Sorts by check execution frequency`, async () => {
const { user } = await renderCheckList([BASIC_TCP_CHECK, BASIC_TRACEROUTE_CHECK]);
const checks = await screen.findAllByTestId('check-card');
const checksA = await screen.findAllByTestId('check-card');

expect(checks.length).toBe(2);
expect(checks[0]).toHaveTextContent(`89280 executions / month`);
expect(checks[1]).toHaveTextContent(`44640 executions / month`);
expect(checksA.length).toBe(2);
expect(checksA[0]).toHaveTextContent(`89280 executions / month`);
expect(checksA[1]).toHaveTextContent(`44640 executions / month`);

const sortPicker = await screen.getByLabelText('Sort checks by');
await user.click(sortPicker);
await user.click(screen.getByText(`Asc. Executions`, { selector: 'span' }));

expect(checks.length).toBe(2);
expect(checks[0]).toHaveTextContent(`44640 executions / month`);
expect(checks[1]).toHaveTextContent(`89280 executions / month`);
const checksB = await screen.findAllByTestId('check-card');
expect(checksB.length).toBe(2);

expect(checksB[0]).toHaveTextContent(`44640 executions / month`);
expect(checksB[1]).toHaveTextContent(`89280 executions / month`);

await user.click(sortPicker);
await user.click(screen.getByText(`Desc. Executions`, { selector: 'span' }));

expect(checks.length).toBe(2);
expect(checks[0]).toHaveTextContent(`89280 executions / month`);
expect(checks[1]).toHaveTextContent(`44640 executions / month`);
const checksC = await screen.findAllByTestId('check-card');
expect(checksC.length).toBe(2);
expect(checksC[0]).toHaveTextContent(`89280 executions / month`);
expect(checksC[1]).toHaveTextContent(`44640 executions / month`);
});
});

Expand Down
2 changes: 1 addition & 1 deletion src/page/CheckList/CheckList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ const CheckListContent = ({ onChangeViewType, viewType }: CheckListContentProps)
{currentPageChecks.map((check, index) => (
<CheckListItem
check={check}
key={index}
key={check.id}
onLabelSelect={handleLabelSelect}
onStatusSelect={handleStatusSelect}
onTypeSelect={handleTypeSelect}
Expand Down
Loading
Loading