Prometheus: Fix applying ad-hoc filters to the expression that has a template variable (#75250)

* Interpolate first and then apply ad-hoc filters

* More tests
This commit is contained in:
ismail simsek 2023-09-22 17:32:19 +02:00 committed by GitHub
parent 13ea22ac1e
commit d076f733e9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 56 additions and 4 deletions

View File

@ -835,6 +835,55 @@ describe('PrometheusDatasource', () => {
const result = ds.applyTemplateVariables(query, {});
expect(result).toMatchObject({ expr: 'test{job="bar", k1="v1", k2!="v2"}' });
});
it('should add ad-hoc filters only to expr', () => {
replaceMock.mockImplementation((a: string) => a?.replace('$A', '99') ?? a);
getAdhocFiltersMock.mockReturnValue([
{
key: 'k1',
operator: '=',
value: 'v1',
},
{
key: 'k2',
operator: '!=',
value: 'v2',
},
]);
const query = {
expr: 'test{job="bar"} > $A',
refId: 'A',
};
const result = ds.applyTemplateVariables(query, {});
expect(result).toMatchObject({ expr: 'test{job="bar", k1="v1", k2!="v2"} > 99' });
});
it('should add ad-hoc filters only to expr and expression has template variable as label value??', () => {
const searchPattern = /\$A/g;
replaceMock.mockImplementation((a: string) => a?.replace(searchPattern, '99') ?? a);
getAdhocFiltersMock.mockReturnValue([
{
key: 'k1',
operator: '=',
value: 'v1',
},
{
key: 'k2',
operator: '!=',
value: 'v2',
},
]);
const query = {
expr: 'test{job="$A"} > $A',
refId: 'A',
};
const result = ds.applyTemplateVariables(query, {});
expect(result).toMatchObject({ expr: 'test{job="99", k1="v1", k2!="v2"} > 99' });
});
});
describe('metricFindQuery', () => {

View File

@ -1280,14 +1280,17 @@ export class PrometheusDatasource
delete variables.__interval;
delete variables.__interval_ms;
//Add ad hoc filters
const expr = this.enhanceExprWithAdHocFilters(target.expr);
// interpolate expression
const expr = this.templateSrv.replace(target.expr, variables, this.interpolateQueryExpr);
// Add ad hoc filters
const exprWithAdHocFilters = this.enhanceExprWithAdHocFilters(expr);
return {
...target,
legendFormat: this.templateSrv.replace(target.legendFormat, variables),
expr: this.templateSrv.replace(expr, variables, this.interpolateQueryExpr),
expr: exprWithAdHocFilters,
interval: this.templateSrv.replace(target.interval, variables),
legendFormat: this.templateSrv.replace(target.legendFormat, variables),
};
}