datasource.test.ts 49 KB

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