datasource.test.ts 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406
  1. import _ from 'lodash';
  2. // @ts-ignore
  3. import q from 'q';
  4. import {
  5. alignRange,
  6. extractRuleMappingFromGroups,
  7. PrometheusDatasource,
  8. prometheusRegularEscape,
  9. prometheusSpecialRegexEscape,
  10. } from '../datasource';
  11. import { dateTime } from '@grafana/ui/src/utils/moment_wrapper';
  12. import { DataSourceInstanceSettings, DataQueryResponseData } from '@grafana/ui';
  13. import { PromOptions } from '../types';
  14. import { TemplateSrv } from 'app/features/templating/template_srv';
  15. import { TimeSrv } from 'app/features/dashboard/services/TimeSrv';
  16. import { CustomVariable } from 'app/features/templating/custom_variable';
  17. jest.mock('../metric_find_query');
  18. const DEFAULT_TEMPLATE_SRV_MOCK = {
  19. getAdhocFilters: () => [] as any[],
  20. replace: (a: string) => a,
  21. };
  22. describe('PrometheusDatasource', () => {
  23. const ctx: any = {};
  24. const instanceSettings = ({
  25. url: 'proxied',
  26. directUrl: 'direct',
  27. user: 'test',
  28. password: 'mupp',
  29. jsonData: {} as any,
  30. } as unknown) as DataSourceInstanceSettings<PromOptions>;
  31. ctx.backendSrvMock = {};
  32. ctx.templateSrvMock = DEFAULT_TEMPLATE_SRV_MOCK;
  33. ctx.timeSrvMock = {
  34. timeRange: () => {
  35. return {
  36. from: dateTime(1531468681),
  37. to: dateTime(1531489712),
  38. };
  39. },
  40. };
  41. beforeEach(() => {
  42. ctx.ds = new PrometheusDatasource(instanceSettings, q, ctx.backendSrvMock, ctx.templateSrvMock, ctx.timeSrvMock);
  43. });
  44. describe('Datasource metadata requests', () => {
  45. it('should perform a GET request with the default config', () => {
  46. ctx.backendSrvMock.datasourceRequest = jest.fn();
  47. ctx.ds.metadataRequest('/foo');
  48. expect(ctx.backendSrvMock.datasourceRequest.mock.calls.length).toBe(1);
  49. expect(ctx.backendSrvMock.datasourceRequest.mock.calls[0][0].method).toBe('GET');
  50. });
  51. it('should still perform a GET request with the DS HTTP method set to POST', () => {
  52. ctx.backendSrvMock.datasourceRequest = jest.fn();
  53. const postSettings = _.cloneDeep(instanceSettings);
  54. postSettings.jsonData.httpMethod = 'POST';
  55. const ds = new PrometheusDatasource(postSettings, q, ctx.backendSrvMock, ctx.templateSrvMock, ctx.timeSrvMock);
  56. ds.metadataRequest('/foo');
  57. expect(ctx.backendSrvMock.datasourceRequest.mock.calls.length).toBe(1);
  58. expect(ctx.backendSrvMock.datasourceRequest.mock.calls[0][0].method).toBe('GET');
  59. });
  60. });
  61. describe('When using adhoc filters', () => {
  62. const DEFAULT_QUERY_EXPRESSION = 'metric{job="foo"} - metric';
  63. const target = { expr: DEFAULT_QUERY_EXPRESSION };
  64. afterEach(() => {
  65. ctx.templateSrvMock.getAdhocFilters = DEFAULT_TEMPLATE_SRV_MOCK.getAdhocFilters;
  66. });
  67. it('should not modify expression with no filters', () => {
  68. const result = ctx.ds.createQuery(target, { interval: '15s' });
  69. expect(result).toMatchObject({ expr: DEFAULT_QUERY_EXPRESSION });
  70. });
  71. it('should add filters to expression', () => {
  72. ctx.templateSrvMock.getAdhocFilters = () => [
  73. {
  74. key: 'k1',
  75. operator: '=',
  76. value: 'v1',
  77. },
  78. {
  79. key: 'k2',
  80. operator: '!=',
  81. value: 'v2',
  82. },
  83. ];
  84. const result = ctx.ds.createQuery(target, { interval: '15s' });
  85. expect(result).toMatchObject({ expr: 'metric{job="foo",k1="v1",k2!="v2"} - metric{k1="v1",k2!="v2"}' });
  86. });
  87. it('should add escaping if needed to regex filter expressions', () => {
  88. ctx.templateSrvMock.getAdhocFilters = () => [
  89. {
  90. key: 'k1',
  91. operator: '=~',
  92. value: 'v.*',
  93. },
  94. {
  95. key: 'k2',
  96. operator: '=~',
  97. value: `v'.*`,
  98. },
  99. ];
  100. const result = ctx.ds.createQuery(target, { interval: '15s' });
  101. expect(result).toMatchObject({
  102. expr: `metric{job="foo",k1=~"v.*",k2=~"v\\\\'.*"} - metric{k1=~"v.*",k2=~"v\\\\'.*"}`,
  103. });
  104. });
  105. });
  106. describe('When performing performSuggestQuery', () => {
  107. it('should cache response', async () => {
  108. ctx.backendSrvMock.datasourceRequest.mockReturnValue(
  109. Promise.resolve({
  110. status: 'success',
  111. data: { data: ['value1', 'value2', 'value3'] },
  112. })
  113. );
  114. let results = await ctx.ds.performSuggestQuery('value', true);
  115. expect(results).toHaveLength(3);
  116. ctx.backendSrvMock.datasourceRequest.mockReset();
  117. results = await ctx.ds.performSuggestQuery('value', true);
  118. expect(results).toHaveLength(3);
  119. });
  120. });
  121. describe('When converting prometheus histogram to heatmap format', () => {
  122. beforeEach(() => {
  123. ctx.query = {
  124. range: { from: dateTime(1443454528000), to: dateTime(1443454528000) },
  125. targets: [{ expr: 'test{job="testjob"}', format: 'heatmap', legendFormat: '{{le}}' }],
  126. interval: '1s',
  127. };
  128. });
  129. it('should convert cumullative histogram to ordinary', () => {
  130. const resultMock = [
  131. {
  132. metric: { __name__: 'metric', job: 'testjob', le: '10' },
  133. values: [[1443454528.0, '10'], [1443454528.0, '10']],
  134. },
  135. {
  136. metric: { __name__: 'metric', job: 'testjob', le: '20' },
  137. values: [[1443454528.0, '20'], [1443454528.0, '10']],
  138. },
  139. {
  140. metric: { __name__: 'metric', job: 'testjob', le: '30' },
  141. values: [[1443454528.0, '25'], [1443454528.0, '10']],
  142. },
  143. ];
  144. const responseMock = { data: { data: { result: resultMock } } };
  145. const expected = [
  146. {
  147. target: '10',
  148. datapoints: [[10, 1443454528000], [10, 1443454528000]],
  149. },
  150. {
  151. target: '20',
  152. datapoints: [[10, 1443454528000], [0, 1443454528000]],
  153. },
  154. {
  155. target: '30',
  156. datapoints: [[5, 1443454528000], [0, 1443454528000]],
  157. },
  158. ];
  159. ctx.ds.performTimeSeriesQuery = jest.fn().mockReturnValue(responseMock);
  160. return ctx.ds.query(ctx.query).then((result: any) => {
  161. const results = result.data;
  162. return expect(results).toMatchObject(expected);
  163. });
  164. });
  165. it('should sort series by label value', () => {
  166. const resultMock = [
  167. {
  168. metric: { __name__: 'metric', job: 'testjob', le: '2' },
  169. values: [[1443454528.0, '10'], [1443454528.0, '10']],
  170. },
  171. {
  172. metric: { __name__: 'metric', job: 'testjob', le: '4' },
  173. values: [[1443454528.0, '20'], [1443454528.0, '10']],
  174. },
  175. {
  176. metric: { __name__: 'metric', job: 'testjob', le: '+Inf' },
  177. values: [[1443454528.0, '25'], [1443454528.0, '10']],
  178. },
  179. {
  180. metric: { __name__: 'metric', job: 'testjob', le: '1' },
  181. values: [[1443454528.0, '25'], [1443454528.0, '10']],
  182. },
  183. ];
  184. const responseMock = { data: { data: { result: resultMock } } };
  185. const expected = ['1', '2', '4', '+Inf'];
  186. ctx.ds.performTimeSeriesQuery = jest.fn().mockReturnValue(responseMock);
  187. return ctx.ds.query(ctx.query).then((result: any) => {
  188. const seriesLabels = _.map(result.data, 'target');
  189. return expect(seriesLabels).toEqual(expected);
  190. });
  191. });
  192. });
  193. describe('alignRange', () => {
  194. it('does not modify already aligned intervals with perfect step', () => {
  195. const range = alignRange(0, 3, 3);
  196. expect(range.start).toEqual(0);
  197. expect(range.end).toEqual(3);
  198. });
  199. it('does modify end-aligned intervals to reflect number of steps possible', () => {
  200. const range = alignRange(1, 6, 3);
  201. expect(range.start).toEqual(0);
  202. expect(range.end).toEqual(6);
  203. });
  204. it('does align intervals that are a multiple of steps', () => {
  205. const range = alignRange(1, 4, 3);
  206. expect(range.start).toEqual(0);
  207. expect(range.end).toEqual(3);
  208. });
  209. it('does align intervals that are not a multiple of steps', () => {
  210. const range = alignRange(1, 5, 3);
  211. expect(range.start).toEqual(0);
  212. expect(range.end).toEqual(3);
  213. });
  214. });
  215. describe('extractRuleMappingFromGroups()', () => {
  216. it('returns empty mapping for no rule groups', () => {
  217. expect(extractRuleMappingFromGroups([])).toEqual({});
  218. });
  219. it('returns a mapping for recording rules only', () => {
  220. const groups = [
  221. {
  222. rules: [
  223. {
  224. name: 'HighRequestLatency',
  225. query: 'job:request_latency_seconds:mean5m{job="myjob"} > 0.5',
  226. type: 'alerting',
  227. },
  228. {
  229. name: 'job:http_inprogress_requests:sum',
  230. query: 'sum(http_inprogress_requests) by (job)',
  231. type: 'recording',
  232. },
  233. ],
  234. file: '/rules.yaml',
  235. interval: 60,
  236. name: 'example',
  237. },
  238. ];
  239. const mapping = extractRuleMappingFromGroups(groups);
  240. expect(mapping).toEqual({ 'job:http_inprogress_requests:sum': 'sum(http_inprogress_requests) by (job)' });
  241. });
  242. });
  243. describe('Prometheus regular escaping', () => {
  244. it('should not escape non-string', () => {
  245. expect(prometheusRegularEscape(12)).toEqual(12);
  246. });
  247. it('should not escape simple string', () => {
  248. expect(prometheusRegularEscape('cryptodepression')).toEqual('cryptodepression');
  249. });
  250. it("should escape '", () => {
  251. expect(prometheusRegularEscape("looking'glass")).toEqual("looking\\\\'glass");
  252. });
  253. it('should escape multiple characters', () => {
  254. expect(prometheusRegularEscape("'looking'glass'")).toEqual("\\\\'looking\\\\'glass\\\\'");
  255. });
  256. });
  257. describe('Prometheus regexes escaping', () => {
  258. it('should not escape simple string', () => {
  259. expect(prometheusSpecialRegexEscape('cryptodepression')).toEqual('cryptodepression');
  260. });
  261. it('should escape $^*+?.()|\\', () => {
  262. expect(prometheusSpecialRegexEscape("looking'glass")).toEqual("looking\\\\'glass");
  263. expect(prometheusSpecialRegexEscape('looking{glass')).toEqual('looking\\\\{glass');
  264. expect(prometheusSpecialRegexEscape('looking}glass')).toEqual('looking\\\\}glass');
  265. expect(prometheusSpecialRegexEscape('looking[glass')).toEqual('looking\\\\[glass');
  266. expect(prometheusSpecialRegexEscape('looking]glass')).toEqual('looking\\\\]glass');
  267. expect(prometheusSpecialRegexEscape('looking$glass')).toEqual('looking\\\\$glass');
  268. expect(prometheusSpecialRegexEscape('looking^glass')).toEqual('looking\\\\^glass');
  269. expect(prometheusSpecialRegexEscape('looking*glass')).toEqual('looking\\\\*glass');
  270. expect(prometheusSpecialRegexEscape('looking+glass')).toEqual('looking\\\\+glass');
  271. expect(prometheusSpecialRegexEscape('looking?glass')).toEqual('looking\\\\?glass');
  272. expect(prometheusSpecialRegexEscape('looking.glass')).toEqual('looking\\\\.glass');
  273. expect(prometheusSpecialRegexEscape('looking(glass')).toEqual('looking\\\\(glass');
  274. expect(prometheusSpecialRegexEscape('looking)glass')).toEqual('looking\\\\)glass');
  275. expect(prometheusSpecialRegexEscape('looking\\glass')).toEqual('looking\\\\\\\\glass');
  276. expect(prometheusSpecialRegexEscape('looking|glass')).toEqual('looking\\\\|glass');
  277. });
  278. it('should escape multiple special characters', () => {
  279. expect(prometheusSpecialRegexEscape('+looking$glass?')).toEqual('\\\\+looking\\\\$glass\\\\?');
  280. });
  281. });
  282. describe('When interpolating variables', () => {
  283. beforeEach(() => {
  284. ctx.ds = new PrometheusDatasource(instanceSettings, q, ctx.backendSrvMock, ctx.templateSrvMock, ctx.timeSrvMock);
  285. ctx.variable = new CustomVariable({}, {});
  286. });
  287. describe('and value is a string', () => {
  288. it('should only escape single quotes', () => {
  289. expect(ctx.ds.interpolateQueryExpr("abc'$^*{}[]+?.()|", ctx.variable)).toEqual("abc\\\\'$^*{}[]+?.()|");
  290. });
  291. });
  292. describe('and value is a number', () => {
  293. it('should return a number', () => {
  294. expect(ctx.ds.interpolateQueryExpr(1000, ctx.variable)).toEqual(1000);
  295. });
  296. });
  297. describe('and variable allows multi-value', () => {
  298. beforeEach(() => {
  299. ctx.variable.multi = true;
  300. });
  301. it('should regex escape values if the value is a string', () => {
  302. expect(ctx.ds.interpolateQueryExpr('looking*glass', ctx.variable)).toEqual('looking\\\\*glass');
  303. });
  304. it('should return pipe separated values if the value is an array of strings', () => {
  305. expect(ctx.ds.interpolateQueryExpr(['a|bc', 'de|f'], ctx.variable)).toEqual('a\\\\|bc|de\\\\|f');
  306. });
  307. });
  308. describe('and variable allows all', () => {
  309. beforeEach(() => {
  310. ctx.variable.includeAll = true;
  311. });
  312. it('should regex escape values if the array is a string', () => {
  313. expect(ctx.ds.interpolateQueryExpr('looking*glass', ctx.variable)).toEqual('looking\\\\*glass');
  314. });
  315. it('should return pipe separated values if the value is an array of strings', () => {
  316. expect(ctx.ds.interpolateQueryExpr(['a|bc', 'de|f'], ctx.variable)).toEqual('a\\\\|bc|de\\\\|f');
  317. });
  318. });
  319. });
  320. describe('metricFindQuery', () => {
  321. beforeEach(() => {
  322. const query = 'query_result(topk(5,rate(http_request_duration_microseconds_count[$__interval])))';
  323. ctx.templateSrvMock.replace = jest.fn();
  324. ctx.timeSrvMock.timeRange = () => {
  325. return {
  326. from: dateTime(1531468681),
  327. to: dateTime(1531489712),
  328. };
  329. };
  330. ctx.ds = new PrometheusDatasource(instanceSettings, q, ctx.backendSrvMock, ctx.templateSrvMock, ctx.timeSrvMock);
  331. ctx.ds.metricFindQuery(query);
  332. });
  333. it('should call templateSrv.replace with scopedVars', () => {
  334. expect(ctx.templateSrvMock.replace.mock.calls[0][1]).toBeDefined();
  335. });
  336. it('should have the correct range and range_ms', () => {
  337. const range = ctx.templateSrvMock.replace.mock.calls[0][1].__range;
  338. const rangeMs = ctx.templateSrvMock.replace.mock.calls[0][1].__range_ms;
  339. const rangeS = ctx.templateSrvMock.replace.mock.calls[0][1].__range_s;
  340. expect(range).toEqual({ text: '21s', value: '21s' });
  341. expect(rangeMs).toEqual({ text: 21031, value: 21031 });
  342. expect(rangeS).toEqual({ text: 21, value: 21 });
  343. });
  344. it('should pass the default interval value', () => {
  345. const interval = ctx.templateSrvMock.replace.mock.calls[0][1].__interval;
  346. const intervalMs = ctx.templateSrvMock.replace.mock.calls[0][1].__interval_ms;
  347. expect(interval).toEqual({ text: '15s', value: '15s' });
  348. expect(intervalMs).toEqual({ text: 15000, value: 15000 });
  349. });
  350. });
  351. });
  352. const SECOND = 1000;
  353. const MINUTE = 60 * SECOND;
  354. const HOUR = 60 * MINUTE;
  355. const time = ({ hours = 0, seconds = 0, minutes = 0 }) => dateTime(hours * HOUR + minutes * MINUTE + seconds * SECOND);
  356. const ctx = {} as any;
  357. const instanceSettings = ({
  358. url: 'proxied',
  359. directUrl: 'direct',
  360. user: 'test',
  361. password: 'mupp',
  362. jsonData: { httpMethod: 'GET' },
  363. } as unknown) as DataSourceInstanceSettings<PromOptions>;
  364. const backendSrv = {
  365. datasourceRequest: jest.fn(),
  366. } as any;
  367. const templateSrv = ({
  368. getAdhocFilters: (): any[] => [],
  369. replace: jest.fn(str => str),
  370. } as unknown) as TemplateSrv;
  371. const timeSrv = ({
  372. timeRange: () => {
  373. return { to: { diff: () => 2000 }, from: '' };
  374. },
  375. } as unknown) as TimeSrv;
  376. describe('PrometheusDatasource', () => {
  377. describe('When querying prometheus with one target using query editor target spec', () => {
  378. describe('and query syntax is valid', () => {
  379. let results: any;
  380. const query = {
  381. range: { from: time({ seconds: 63 }), to: time({ seconds: 183 }) },
  382. targets: [{ expr: 'test{job="testjob"}', format: 'time_series' }],
  383. interval: '60s',
  384. };
  385. // Interval alignment with step
  386. const urlExpected =
  387. 'proxied/api/v1/query_range?query=' + encodeURIComponent('test{job="testjob"}') + '&start=60&end=180&step=60';
  388. beforeEach(async () => {
  389. const response = {
  390. data: {
  391. status: 'success',
  392. data: {
  393. resultType: 'matrix',
  394. result: [
  395. {
  396. metric: { __name__: 'test', job: 'testjob' },
  397. values: [[60, '3846']],
  398. },
  399. ],
  400. },
  401. },
  402. };
  403. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  404. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  405. await ctx.ds.query(query).then((data: any) => {
  406. results = data;
  407. });
  408. });
  409. it('should generate the correct query', () => {
  410. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  411. expect(res.method).toBe('GET');
  412. expect(res.url).toBe(urlExpected);
  413. });
  414. it('should return series list', async () => {
  415. expect(results.data.length).toBe(1);
  416. expect(results.data[0].target).toBe('test{job="testjob"}');
  417. });
  418. });
  419. describe('and query syntax is invalid', () => {
  420. let results: string;
  421. const query = {
  422. range: { from: time({ seconds: 63 }), to: time({ seconds: 183 }) },
  423. targets: [{ expr: 'tes;;t{job="testjob"}', format: 'time_series' }],
  424. interval: '60s',
  425. };
  426. const errMessage = 'parse error at char 25: could not parse remaining input';
  427. const response = {
  428. data: {
  429. status: 'error',
  430. errorType: 'bad_data',
  431. error: errMessage,
  432. },
  433. };
  434. beforeEach(async () => {
  435. backendSrv.datasourceRequest = jest.fn(() => Promise.reject(response));
  436. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  437. await ctx.ds.query(query).catch((e: any) => {
  438. results = e.message;
  439. });
  440. });
  441. it('should generate an error', () => {
  442. expect(results).toBe(`"${errMessage}"`);
  443. });
  444. });
  445. });
  446. describe('When querying prometheus with one target which returns multiple series', () => {
  447. let results: any;
  448. const start = 60;
  449. const end = 360;
  450. const step = 60;
  451. const query = {
  452. range: { from: time({ seconds: start }), to: time({ seconds: end }) },
  453. targets: [{ expr: 'test{job="testjob"}', format: 'time_series' }],
  454. interval: '60s',
  455. };
  456. beforeEach(async () => {
  457. const response = {
  458. status: 'success',
  459. data: {
  460. data: {
  461. resultType: 'matrix',
  462. result: [
  463. {
  464. metric: { __name__: 'test', job: 'testjob', series: 'series 1' },
  465. values: [[start + step * 1, '3846'], [start + step * 3, '3847'], [end - step * 1, '3848']],
  466. },
  467. {
  468. metric: { __name__: 'test', job: 'testjob', series: 'series 2' },
  469. values: [[start + step * 2, '4846']],
  470. },
  471. ],
  472. },
  473. },
  474. };
  475. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  476. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  477. await ctx.ds.query(query).then((data: any) => {
  478. results = data;
  479. });
  480. });
  481. it('should be same length', () => {
  482. expect(results.data.length).toBe(2);
  483. expect(results.data[0].datapoints.length).toBe((end - start) / step + 1);
  484. expect(results.data[1].datapoints.length).toBe((end - start) / step + 1);
  485. });
  486. it('should fill null until first datapoint in response', () => {
  487. expect(results.data[0].datapoints[0][1]).toBe(start * 1000);
  488. expect(results.data[0].datapoints[0][0]).toBe(null);
  489. expect(results.data[0].datapoints[1][1]).toBe((start + step * 1) * 1000);
  490. expect(results.data[0].datapoints[1][0]).toBe(3846);
  491. });
  492. it('should fill null after last datapoint in response', () => {
  493. const length = (end - start) / step + 1;
  494. expect(results.data[0].datapoints[length - 2][1]).toBe((end - step * 1) * 1000);
  495. expect(results.data[0].datapoints[length - 2][0]).toBe(3848);
  496. expect(results.data[0].datapoints[length - 1][1]).toBe(end * 1000);
  497. expect(results.data[0].datapoints[length - 1][0]).toBe(null);
  498. });
  499. it('should fill null at gap between series', () => {
  500. expect(results.data[0].datapoints[2][1]).toBe((start + step * 2) * 1000);
  501. expect(results.data[0].datapoints[2][0]).toBe(null);
  502. expect(results.data[1].datapoints[1][1]).toBe((start + step * 1) * 1000);
  503. expect(results.data[1].datapoints[1][0]).toBe(null);
  504. expect(results.data[1].datapoints[3][1]).toBe((start + step * 3) * 1000);
  505. expect(results.data[1].datapoints[3][0]).toBe(null);
  506. });
  507. });
  508. describe('When querying prometheus with one target and instant = true', () => {
  509. let results: any;
  510. const urlExpected = 'proxied/api/v1/query?query=' + encodeURIComponent('test{job="testjob"}') + '&time=123';
  511. const query = {
  512. range: { from: time({ seconds: 63 }), to: time({ seconds: 123 }) },
  513. targets: [{ expr: 'test{job="testjob"}', format: 'time_series', instant: true }],
  514. interval: '60s',
  515. };
  516. beforeEach(async () => {
  517. const response = {
  518. status: 'success',
  519. data: {
  520. data: {
  521. resultType: 'vector',
  522. result: [
  523. {
  524. metric: { __name__: 'test', job: 'testjob' },
  525. value: [123, '3846'],
  526. },
  527. ],
  528. },
  529. },
  530. };
  531. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  532. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  533. await ctx.ds.query(query).then((data: any) => {
  534. results = data;
  535. });
  536. });
  537. it('should generate the correct query', () => {
  538. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  539. expect(res.method).toBe('GET');
  540. expect(res.url).toBe(urlExpected);
  541. });
  542. it('should return series list', () => {
  543. expect(results.data.length).toBe(1);
  544. expect(results.data[0].target).toBe('test{job="testjob"}');
  545. });
  546. });
  547. describe('When performing annotationQuery', () => {
  548. let results: any;
  549. const options: any = {
  550. annotation: {
  551. expr: 'ALERTS{alertstate="firing"}',
  552. tagKeys: 'job',
  553. titleFormat: '{{alertname}}',
  554. textFormat: '{{instance}}',
  555. },
  556. range: {
  557. from: time({ seconds: 63 }),
  558. to: time({ seconds: 123 }),
  559. },
  560. };
  561. const response = {
  562. status: 'success',
  563. data: {
  564. data: {
  565. resultType: 'matrix',
  566. result: [
  567. {
  568. metric: {
  569. __name__: 'ALERTS',
  570. alertname: 'InstanceDown',
  571. alertstate: 'firing',
  572. instance: 'testinstance',
  573. job: 'testjob',
  574. },
  575. values: [[123, '1']],
  576. },
  577. ],
  578. },
  579. },
  580. };
  581. describe('not use useValueForTime', () => {
  582. beforeEach(async () => {
  583. options.annotation.useValueForTime = false;
  584. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  585. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  586. await ctx.ds.annotationQuery(options).then((data: any) => {
  587. results = data;
  588. });
  589. });
  590. it('should return annotation list', () => {
  591. expect(results.length).toBe(1);
  592. expect(results[0].tags).toContain('testjob');
  593. expect(results[0].title).toBe('InstanceDown');
  594. expect(results[0].text).toBe('testinstance');
  595. expect(results[0].time).toBe(123 * 1000);
  596. });
  597. });
  598. describe('use useValueForTime', () => {
  599. beforeEach(async () => {
  600. options.annotation.useValueForTime = true;
  601. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  602. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  603. await ctx.ds.annotationQuery(options).then((data: any) => {
  604. results = data;
  605. });
  606. });
  607. it('should return annotation list', () => {
  608. expect(results[0].time).toEqual(1);
  609. });
  610. });
  611. describe('step parameter', () => {
  612. beforeEach(() => {
  613. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  614. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  615. });
  616. it('should use default step for short range if no interval is given', () => {
  617. const query = {
  618. ...options,
  619. range: {
  620. from: time({ seconds: 63 }),
  621. to: time({ seconds: 123 }),
  622. },
  623. };
  624. ctx.ds.annotationQuery(query);
  625. const req = backendSrv.datasourceRequest.mock.calls[0][0];
  626. expect(req.url).toContain('step=60');
  627. });
  628. it('should use custom step for short range', () => {
  629. const annotation = {
  630. ...options.annotation,
  631. step: '10s',
  632. };
  633. const query = {
  634. ...options,
  635. annotation,
  636. range: {
  637. from: time({ seconds: 63 }),
  638. to: time({ seconds: 123 }),
  639. },
  640. };
  641. ctx.ds.annotationQuery(query);
  642. const req = backendSrv.datasourceRequest.mock.calls[0][0];
  643. expect(req.url).toContain('step=10');
  644. });
  645. it('should use custom step for short range', () => {
  646. const annotation = {
  647. ...options.annotation,
  648. step: '10s',
  649. };
  650. const query = {
  651. ...options,
  652. annotation,
  653. range: {
  654. from: time({ seconds: 63 }),
  655. to: time({ seconds: 123 }),
  656. },
  657. };
  658. ctx.ds.annotationQuery(query);
  659. const req = backendSrv.datasourceRequest.mock.calls[0][0];
  660. expect(req.url).toContain('step=10');
  661. });
  662. it('should use dynamic step on long ranges if no option was given', () => {
  663. const query = {
  664. ...options,
  665. range: {
  666. from: time({ seconds: 63 }),
  667. to: time({ hours: 24 * 30, seconds: 63 }),
  668. },
  669. };
  670. ctx.ds.annotationQuery(query);
  671. const req = backendSrv.datasourceRequest.mock.calls[0][0];
  672. // Range in seconds: (to - from) / 1000
  673. // Max_datapoints: 11000
  674. // Step: range / max_datapoints
  675. const step = 236;
  676. expect(req.url).toContain(`step=${step}`);
  677. });
  678. });
  679. });
  680. describe('When resultFormat is table and instant = true', () => {
  681. let results: any;
  682. const query = {
  683. range: { from: time({ seconds: 63 }), to: time({ seconds: 123 }) },
  684. targets: [{ expr: 'test{job="testjob"}', format: 'time_series', instant: true }],
  685. interval: '60s',
  686. };
  687. beforeEach(async () => {
  688. const response = {
  689. status: 'success',
  690. data: {
  691. data: {
  692. resultType: 'vector',
  693. result: [
  694. {
  695. metric: { __name__: 'test', job: 'testjob' },
  696. value: [123, '3846'],
  697. },
  698. ],
  699. },
  700. },
  701. };
  702. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  703. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  704. await ctx.ds.query(query).then((data: any) => {
  705. results = data;
  706. });
  707. });
  708. it('should return result', () => {
  709. expect(results).not.toBe(null);
  710. });
  711. });
  712. describe('The "step" query parameter', () => {
  713. const response = {
  714. status: 'success',
  715. data: {
  716. data: {
  717. resultType: 'matrix',
  718. result: [] as DataQueryResponseData[],
  719. },
  720. },
  721. };
  722. it('should be min interval when greater than auto interval', async () => {
  723. const query = {
  724. // 6 minute range
  725. range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) },
  726. targets: [
  727. {
  728. expr: 'test',
  729. interval: '10s',
  730. },
  731. ],
  732. interval: '5s',
  733. };
  734. const urlExpected = 'proxied/api/v1/query_range?query=test&start=60&end=420&step=10';
  735. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  736. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  737. await ctx.ds.query(query);
  738. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  739. expect(res.method).toBe('GET');
  740. expect(res.url).toBe(urlExpected);
  741. });
  742. it('step should never go below 1', async () => {
  743. const query = {
  744. // 6 minute range
  745. range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) },
  746. targets: [{ expr: 'test' }],
  747. interval: '100ms',
  748. };
  749. const urlExpected = 'proxied/api/v1/query_range?query=test&start=60&end=420&step=1';
  750. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  751. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  752. await ctx.ds.query(query);
  753. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  754. expect(res.method).toBe('GET');
  755. expect(res.url).toBe(urlExpected);
  756. });
  757. it('should be auto interval when greater than min interval', async () => {
  758. const query = {
  759. // 6 minute range
  760. range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) },
  761. targets: [
  762. {
  763. expr: 'test',
  764. interval: '5s',
  765. },
  766. ],
  767. interval: '10s',
  768. };
  769. const urlExpected = 'proxied/api/v1/query_range?query=test&start=60&end=420&step=10';
  770. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  771. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  772. await ctx.ds.query(query);
  773. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  774. expect(res.method).toBe('GET');
  775. expect(res.url).toBe(urlExpected);
  776. });
  777. it('should result in querying fewer than 11000 data points', async () => {
  778. const query = {
  779. // 6 hour range
  780. range: { from: time({ hours: 1 }), to: time({ hours: 7 }) },
  781. targets: [{ expr: 'test' }],
  782. interval: '1s',
  783. };
  784. const end = 7 * 60 * 60;
  785. const start = 60 * 60;
  786. const urlExpected = 'proxied/api/v1/query_range?query=test&start=' + start + '&end=' + end + '&step=2';
  787. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  788. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  789. await ctx.ds.query(query);
  790. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  791. expect(res.method).toBe('GET');
  792. expect(res.url).toBe(urlExpected);
  793. });
  794. it('should not apply min interval when interval * intervalFactor greater', async () => {
  795. const query = {
  796. // 6 minute range
  797. range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) },
  798. targets: [
  799. {
  800. expr: 'test',
  801. interval: '10s',
  802. intervalFactor: 10,
  803. },
  804. ],
  805. interval: '5s',
  806. };
  807. // times get rounded up to interval
  808. const urlExpected = 'proxied/api/v1/query_range?query=test&start=50&end=400&step=50';
  809. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  810. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  811. await ctx.ds.query(query);
  812. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  813. expect(res.method).toBe('GET');
  814. expect(res.url).toBe(urlExpected);
  815. });
  816. it('should apply min interval when interval * intervalFactor smaller', async () => {
  817. const query = {
  818. // 6 minute range
  819. range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) },
  820. targets: [
  821. {
  822. expr: 'test',
  823. interval: '15s',
  824. intervalFactor: 2,
  825. },
  826. ],
  827. interval: '5s',
  828. };
  829. const urlExpected = 'proxied/api/v1/query_range?query=test' + '&start=60&end=420&step=15';
  830. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  831. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  832. await ctx.ds.query(query);
  833. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  834. expect(res.method).toBe('GET');
  835. expect(res.url).toBe(urlExpected);
  836. });
  837. it('should apply intervalFactor to auto interval when greater', async () => {
  838. const query = {
  839. // 6 minute range
  840. range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) },
  841. targets: [
  842. {
  843. expr: 'test',
  844. interval: '5s',
  845. intervalFactor: 10,
  846. },
  847. ],
  848. interval: '10s',
  849. };
  850. // times get aligned to interval
  851. const urlExpected = 'proxied/api/v1/query_range?query=test' + '&start=0&end=400&step=100';
  852. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  853. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  854. await ctx.ds.query(query);
  855. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  856. expect(res.method).toBe('GET');
  857. expect(res.url).toBe(urlExpected);
  858. });
  859. it('should not not be affected by the 11000 data points limit when large enough', async () => {
  860. const query = {
  861. // 1 week range
  862. range: { from: time({}), to: time({ hours: 7 * 24 }) },
  863. targets: [
  864. {
  865. expr: 'test',
  866. intervalFactor: 10,
  867. },
  868. ],
  869. interval: '10s',
  870. };
  871. const end = 7 * 24 * 60 * 60;
  872. const start = 0;
  873. const urlExpected = 'proxied/api/v1/query_range?query=test' + '&start=' + start + '&end=' + end + '&step=100';
  874. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  875. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  876. await ctx.ds.query(query);
  877. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  878. expect(res.method).toBe('GET');
  879. expect(res.url).toBe(urlExpected);
  880. });
  881. it('should be determined by the 11000 data points limit when too small', async () => {
  882. const query = {
  883. // 1 week range
  884. range: { from: time({}), to: time({ hours: 7 * 24 }) },
  885. targets: [
  886. {
  887. expr: 'test',
  888. intervalFactor: 10,
  889. },
  890. ],
  891. interval: '5s',
  892. };
  893. const end = 7 * 24 * 60 * 60;
  894. const start = 0;
  895. const urlExpected = 'proxied/api/v1/query_range?query=test' + '&start=' + start + '&end=' + end + '&step=60';
  896. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  897. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  898. await ctx.ds.query(query);
  899. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  900. expect(res.method).toBe('GET');
  901. expect(res.url).toBe(urlExpected);
  902. });
  903. });
  904. describe('The __interval and __interval_ms template variables', () => {
  905. const response = {
  906. status: 'success',
  907. data: {
  908. data: {
  909. resultType: 'matrix',
  910. result: [] as DataQueryResponseData[],
  911. },
  912. },
  913. };
  914. it('should be unchanged when auto interval is greater than min interval', async () => {
  915. const query = {
  916. // 6 minute range
  917. range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) },
  918. targets: [
  919. {
  920. expr: 'rate(test[$__interval])',
  921. interval: '5s',
  922. },
  923. ],
  924. interval: '10s',
  925. scopedVars: {
  926. __interval: { text: '10s', value: '10s' },
  927. __interval_ms: { text: 10 * 1000, value: 10 * 1000 },
  928. },
  929. };
  930. const urlExpected =
  931. 'proxied/api/v1/query_range?query=' +
  932. encodeURIComponent('rate(test[$__interval])') +
  933. '&start=60&end=420&step=10';
  934. templateSrv.replace = jest.fn(str => str);
  935. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  936. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  937. await ctx.ds.query(query);
  938. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  939. expect(res.method).toBe('GET');
  940. expect(res.url).toBe(urlExpected);
  941. // @ts-ignore
  942. expect(templateSrv.replace.mock.calls[0][1]).toEqual({
  943. __interval: {
  944. text: '10s',
  945. value: '10s',
  946. },
  947. __interval_ms: {
  948. text: 10000,
  949. value: 10000,
  950. },
  951. });
  952. });
  953. it('should be min interval when it is greater than auto interval', async () => {
  954. const query = {
  955. // 6 minute range
  956. range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) },
  957. targets: [
  958. {
  959. expr: 'rate(test[$__interval])',
  960. interval: '10s',
  961. },
  962. ],
  963. interval: '5s',
  964. scopedVars: {
  965. __interval: { text: '5s', value: '5s' },
  966. __interval_ms: { text: 5 * 1000, value: 5 * 1000 },
  967. },
  968. };
  969. const urlExpected =
  970. 'proxied/api/v1/query_range?query=' +
  971. encodeURIComponent('rate(test[$__interval])') +
  972. '&start=60&end=420&step=10';
  973. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  974. templateSrv.replace = jest.fn(str => str);
  975. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  976. await ctx.ds.query(query);
  977. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  978. expect(res.method).toBe('GET');
  979. expect(res.url).toBe(urlExpected);
  980. // @ts-ignore
  981. expect(templateSrv.replace.mock.calls[0][1]).toEqual({
  982. __interval: {
  983. text: '5s',
  984. value: '5s',
  985. },
  986. __interval_ms: {
  987. text: 5000,
  988. value: 5000,
  989. },
  990. });
  991. });
  992. it('should account for intervalFactor', async () => {
  993. const query = {
  994. // 6 minute range
  995. range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) },
  996. targets: [
  997. {
  998. expr: 'rate(test[$__interval])',
  999. interval: '5s',
  1000. intervalFactor: 10,
  1001. },
  1002. ],
  1003. interval: '10s',
  1004. scopedVars: {
  1005. __interval: { text: '10s', value: '10s' },
  1006. __interval_ms: { text: 10 * 1000, value: 10 * 1000 },
  1007. },
  1008. };
  1009. const urlExpected =
  1010. 'proxied/api/v1/query_range?query=' +
  1011. encodeURIComponent('rate(test[$__interval])') +
  1012. '&start=0&end=400&step=100';
  1013. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  1014. templateSrv.replace = jest.fn(str => str);
  1015. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  1016. await ctx.ds.query(query);
  1017. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  1018. expect(res.method).toBe('GET');
  1019. expect(res.url).toBe(urlExpected);
  1020. // @ts-ignore
  1021. expect(templateSrv.replace.mock.calls[0][1]).toEqual({
  1022. __interval: {
  1023. text: '10s',
  1024. value: '10s',
  1025. },
  1026. __interval_ms: {
  1027. text: 10000,
  1028. value: 10000,
  1029. },
  1030. });
  1031. expect(query.scopedVars.__interval.text).toBe('10s');
  1032. expect(query.scopedVars.__interval.value).toBe('10s');
  1033. expect(query.scopedVars.__interval_ms.text).toBe(10 * 1000);
  1034. expect(query.scopedVars.__interval_ms.value).toBe(10 * 1000);
  1035. });
  1036. it('should be interval * intervalFactor when greater than min interval', async () => {
  1037. const query = {
  1038. // 6 minute range
  1039. range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) },
  1040. targets: [
  1041. {
  1042. expr: 'rate(test[$__interval])',
  1043. interval: '10s',
  1044. intervalFactor: 10,
  1045. },
  1046. ],
  1047. interval: '5s',
  1048. scopedVars: {
  1049. __interval: { text: '5s', value: '5s' },
  1050. __interval_ms: { text: 5 * 1000, value: 5 * 1000 },
  1051. },
  1052. };
  1053. const urlExpected =
  1054. 'proxied/api/v1/query_range?query=' +
  1055. encodeURIComponent('rate(test[$__interval])') +
  1056. '&start=50&end=400&step=50';
  1057. templateSrv.replace = jest.fn(str => str);
  1058. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  1059. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  1060. await ctx.ds.query(query);
  1061. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  1062. expect(res.method).toBe('GET');
  1063. expect(res.url).toBe(urlExpected);
  1064. // @ts-ignore
  1065. expect(templateSrv.replace.mock.calls[0][1]).toEqual({
  1066. __interval: {
  1067. text: '5s',
  1068. value: '5s',
  1069. },
  1070. __interval_ms: {
  1071. text: 5000,
  1072. value: 5000,
  1073. },
  1074. });
  1075. });
  1076. it('should be min interval when greater than interval * intervalFactor', async () => {
  1077. const query = {
  1078. // 6 minute range
  1079. range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) },
  1080. targets: [
  1081. {
  1082. expr: 'rate(test[$__interval])',
  1083. interval: '15s',
  1084. intervalFactor: 2,
  1085. },
  1086. ],
  1087. interval: '5s',
  1088. scopedVars: {
  1089. __interval: { text: '5s', value: '5s' },
  1090. __interval_ms: { text: 5 * 1000, value: 5 * 1000 },
  1091. },
  1092. };
  1093. const urlExpected =
  1094. 'proxied/api/v1/query_range?query=' +
  1095. encodeURIComponent('rate(test[$__interval])') +
  1096. '&start=60&end=420&step=15';
  1097. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  1098. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  1099. await ctx.ds.query(query);
  1100. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  1101. expect(res.method).toBe('GET');
  1102. expect(res.url).toBe(urlExpected);
  1103. // @ts-ignore
  1104. expect(templateSrv.replace.mock.calls[0][1]).toEqual({
  1105. __interval: {
  1106. text: '5s',
  1107. value: '5s',
  1108. },
  1109. __interval_ms: {
  1110. text: 5000,
  1111. value: 5000,
  1112. },
  1113. });
  1114. });
  1115. it('should be determined by the 11000 data points limit, accounting for intervalFactor', async () => {
  1116. const query = {
  1117. // 1 week range
  1118. range: { from: time({}), to: time({ hours: 7 * 24 }) },
  1119. targets: [
  1120. {
  1121. expr: 'rate(test[$__interval])',
  1122. intervalFactor: 10,
  1123. },
  1124. ],
  1125. interval: '5s',
  1126. scopedVars: {
  1127. __interval: { text: '5s', value: '5s' },
  1128. __interval_ms: { text: 5 * 1000, value: 5 * 1000 },
  1129. },
  1130. };
  1131. const end = 7 * 24 * 60 * 60;
  1132. const start = 0;
  1133. const urlExpected =
  1134. 'proxied/api/v1/query_range?query=' +
  1135. encodeURIComponent('rate(test[$__interval])') +
  1136. '&start=' +
  1137. start +
  1138. '&end=' +
  1139. end +
  1140. '&step=60';
  1141. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  1142. templateSrv.replace = jest.fn(str => str);
  1143. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  1144. await ctx.ds.query(query);
  1145. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  1146. expect(res.method).toBe('GET');
  1147. expect(res.url).toBe(urlExpected);
  1148. // @ts-ignore
  1149. expect(templateSrv.replace.mock.calls[0][1]).toEqual({
  1150. __interval: {
  1151. text: '5s',
  1152. value: '5s',
  1153. },
  1154. __interval_ms: {
  1155. text: 5000,
  1156. value: 5000,
  1157. },
  1158. });
  1159. });
  1160. });
  1161. describe('The __range, __range_s and __range_ms variables', () => {
  1162. const response = {
  1163. status: 'success',
  1164. data: {
  1165. data: {
  1166. resultType: 'matrix',
  1167. result: [] as DataQueryResponseData[],
  1168. },
  1169. },
  1170. };
  1171. it('should use overridden ranges, not dashboard ranges', async () => {
  1172. const expectedRangeSecond = 3600;
  1173. const expectedRangeString = '1h';
  1174. const query = {
  1175. range: {
  1176. from: time({}),
  1177. to: time({ hours: 1 }),
  1178. },
  1179. targets: [
  1180. {
  1181. expr: 'test[${__range_s}s]',
  1182. },
  1183. ],
  1184. interval: '60s',
  1185. };
  1186. const urlExpected = `proxied/api/v1/query_range?query=${encodeURIComponent(
  1187. query.targets[0].expr
  1188. )}&start=0&end=3600&step=60`;
  1189. templateSrv.replace = jest.fn(str => str);
  1190. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  1191. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  1192. await ctx.ds.query(query);
  1193. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  1194. expect(res.url).toBe(urlExpected);
  1195. // @ts-ignore
  1196. expect(templateSrv.replace.mock.calls[1][1]).toEqual({
  1197. __range_s: {
  1198. text: expectedRangeSecond,
  1199. value: expectedRangeSecond,
  1200. },
  1201. __range: {
  1202. text: expectedRangeString,
  1203. value: expectedRangeString,
  1204. },
  1205. __range_ms: {
  1206. text: expectedRangeSecond * 1000,
  1207. value: expectedRangeSecond * 1000,
  1208. },
  1209. });
  1210. });
  1211. });
  1212. });
  1213. describe('PrometheusDatasource for POST', () => {
  1214. // const ctx = new helpers.ServiceTestContext();
  1215. const instanceSettings = ({
  1216. url: 'proxied',
  1217. directUrl: 'direct',
  1218. user: 'test',
  1219. password: 'mupp',
  1220. jsonData: { httpMethod: 'POST' },
  1221. } as unknown) as DataSourceInstanceSettings<PromOptions>;
  1222. describe('When querying prometheus with one target using query editor target spec', () => {
  1223. let results: any;
  1224. const urlExpected = 'proxied/api/v1/query_range';
  1225. const dataExpected = {
  1226. query: 'test{job="testjob"}',
  1227. start: 1 * 60,
  1228. end: 2 * 60,
  1229. step: 60,
  1230. };
  1231. const query = {
  1232. range: { from: time({ minutes: 1, seconds: 3 }), to: time({ minutes: 2, seconds: 3 }) },
  1233. targets: [{ expr: 'test{job="testjob"}', format: 'time_series' }],
  1234. interval: '60s',
  1235. };
  1236. beforeEach(async () => {
  1237. const response = {
  1238. status: 'success',
  1239. data: {
  1240. data: {
  1241. resultType: 'matrix',
  1242. result: [
  1243. {
  1244. metric: { __name__: 'test', job: 'testjob' },
  1245. values: [[2 * 60, '3846']],
  1246. },
  1247. ],
  1248. },
  1249. },
  1250. };
  1251. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  1252. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  1253. await ctx.ds.query(query).then((data: any) => {
  1254. results = data;
  1255. });
  1256. });
  1257. it('should generate the correct query', () => {
  1258. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  1259. expect(res.method).toBe('POST');
  1260. expect(res.url).toBe(urlExpected);
  1261. expect(res.data).toEqual(dataExpected);
  1262. });
  1263. it('should return series list', () => {
  1264. expect(results.data.length).toBe(1);
  1265. expect(results.data[0].target).toBe('test{job="testjob"}');
  1266. });
  1267. });
  1268. describe('When querying prometheus via check headers X-Dashboard-Id and X-Panel-Id', () => {
  1269. const options = { dashboardId: 1, panelId: 2 };
  1270. const httpOptions = {
  1271. headers: {} as { [key: string]: number | undefined },
  1272. };
  1273. it('with proxy access tracing headers should be added', () => {
  1274. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  1275. ctx.ds._addTracingHeaders(httpOptions, options);
  1276. expect(httpOptions.headers['X-Dashboard-Id']).toBe(1);
  1277. expect(httpOptions.headers['X-Panel-Id']).toBe(2);
  1278. });
  1279. it('with direct access tracing headers should not be added', () => {
  1280. instanceSettings.url = 'http://127.0.0.1:8000';
  1281. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  1282. ctx.ds._addTracingHeaders(httpOptions, options);
  1283. expect(httpOptions.headers['X-Dashboard-Id']).toBe(undefined);
  1284. expect(httpOptions.headers['X-Panel-Id']).toBe(undefined);
  1285. });
  1286. });
  1287. });