datasource.test.ts 55 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637
  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, DataQueryRequest } from '@grafana/ui';
  13. import { PromOptions, PromQuery, PromContext } 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. ctx.ds.query(ctx.query).subscribe((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. ctx.ds.query(ctx.query).subscribe((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. ctx.ds.query(query).subscribe((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. it('should generate an error', () => {
  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. ctx.ds.query(query).subscribe((e: any) => {
  453. results = e.message;
  454. expect(results).toBe(`"${errMessage}"`);
  455. });
  456. });
  457. });
  458. });
  459. describe('When querying prometheus with one target which returns multiple series', () => {
  460. let results: any;
  461. const start = 60;
  462. const end = 360;
  463. const step = 60;
  464. const query = {
  465. range: { from: time({ seconds: start }), to: time({ seconds: end }) },
  466. targets: [{ expr: 'test{job="testjob"}', format: 'time_series' }],
  467. interval: '60s',
  468. };
  469. beforeEach(async () => {
  470. const response = {
  471. status: 'success',
  472. data: {
  473. data: {
  474. resultType: 'matrix',
  475. result: [
  476. {
  477. metric: { __name__: 'test', job: 'testjob', series: 'series 1' },
  478. values: [[start + step * 1, '3846'], [start + step * 3, '3847'], [end - step * 1, '3848']],
  479. },
  480. {
  481. metric: { __name__: 'test', job: 'testjob', series: 'series 2' },
  482. values: [[start + step * 2, '4846']],
  483. },
  484. ],
  485. },
  486. },
  487. };
  488. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  489. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  490. ctx.ds.query(query).subscribe((data: any) => {
  491. results = data;
  492. });
  493. });
  494. it('should be same length', () => {
  495. expect(results.data.length).toBe(2);
  496. expect(results.data[0].datapoints.length).toBe((end - start) / step + 1);
  497. expect(results.data[1].datapoints.length).toBe((end - start) / step + 1);
  498. });
  499. it('should fill null until first datapoint in response', () => {
  500. expect(results.data[0].datapoints[0][1]).toBe(start * 1000);
  501. expect(results.data[0].datapoints[0][0]).toBe(null);
  502. expect(results.data[0].datapoints[1][1]).toBe((start + step * 1) * 1000);
  503. expect(results.data[0].datapoints[1][0]).toBe(3846);
  504. });
  505. it('should fill null after last datapoint in response', () => {
  506. const length = (end - start) / step + 1;
  507. expect(results.data[0].datapoints[length - 2][1]).toBe((end - step * 1) * 1000);
  508. expect(results.data[0].datapoints[length - 2][0]).toBe(3848);
  509. expect(results.data[0].datapoints[length - 1][1]).toBe(end * 1000);
  510. expect(results.data[0].datapoints[length - 1][0]).toBe(null);
  511. });
  512. it('should fill null at gap between series', () => {
  513. expect(results.data[0].datapoints[2][1]).toBe((start + step * 2) * 1000);
  514. expect(results.data[0].datapoints[2][0]).toBe(null);
  515. expect(results.data[1].datapoints[1][1]).toBe((start + step * 1) * 1000);
  516. expect(results.data[1].datapoints[1][0]).toBe(null);
  517. expect(results.data[1].datapoints[3][1]).toBe((start + step * 3) * 1000);
  518. expect(results.data[1].datapoints[3][0]).toBe(null);
  519. });
  520. });
  521. describe('When querying prometheus with one target and instant = true', () => {
  522. let results: any;
  523. const urlExpected = 'proxied/api/v1/query?query=' + encodeURIComponent('test{job="testjob"}') + '&time=123';
  524. const query = {
  525. range: { from: time({ seconds: 63 }), to: time({ seconds: 123 }) },
  526. targets: [{ expr: 'test{job="testjob"}', format: 'time_series', instant: true }],
  527. interval: '60s',
  528. };
  529. beforeEach(async () => {
  530. const response = {
  531. status: 'success',
  532. data: {
  533. data: {
  534. resultType: 'vector',
  535. result: [
  536. {
  537. metric: { __name__: 'test', job: 'testjob' },
  538. value: [123, '3846'],
  539. },
  540. ],
  541. },
  542. },
  543. };
  544. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  545. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  546. ctx.ds.query(query).subscribe((data: any) => {
  547. results = data;
  548. });
  549. });
  550. it('should generate the correct query', () => {
  551. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  552. expect(res.method).toBe('GET');
  553. expect(res.url).toBe(urlExpected);
  554. });
  555. it('should return series list', () => {
  556. expect(results.data.length).toBe(1);
  557. expect(results.data[0].target).toBe('test{job="testjob"}');
  558. });
  559. });
  560. describe('When performing annotationQuery', () => {
  561. let results: any;
  562. const options: any = {
  563. annotation: {
  564. expr: 'ALERTS{alertstate="firing"}',
  565. tagKeys: 'job',
  566. titleFormat: '{{alertname}}',
  567. textFormat: '{{instance}}',
  568. },
  569. range: {
  570. from: time({ seconds: 63 }),
  571. to: time({ seconds: 123 }),
  572. },
  573. };
  574. const response = {
  575. status: 'success',
  576. data: {
  577. data: {
  578. resultType: 'matrix',
  579. result: [
  580. {
  581. metric: {
  582. __name__: 'ALERTS',
  583. alertname: 'InstanceDown',
  584. alertstate: 'firing',
  585. instance: 'testinstance',
  586. job: 'testjob',
  587. },
  588. values: [[123, '1']],
  589. },
  590. ],
  591. },
  592. },
  593. };
  594. describe('when time series query is cancelled', () => {
  595. it('should return empty results', async () => {
  596. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve({ cancelled: true }));
  597. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  598. await ctx.ds.annotationQuery(options).then((data: any) => {
  599. results = data;
  600. });
  601. expect(results).toEqual([]);
  602. });
  603. });
  604. describe('not use useValueForTime', () => {
  605. beforeEach(async () => {
  606. options.annotation.useValueForTime = false;
  607. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  608. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  609. await ctx.ds.annotationQuery(options).then((data: any) => {
  610. results = data;
  611. });
  612. });
  613. it('should return annotation list', () => {
  614. expect(results.length).toBe(1);
  615. expect(results[0].tags).toContain('testjob');
  616. expect(results[0].title).toBe('InstanceDown');
  617. expect(results[0].text).toBe('testinstance');
  618. expect(results[0].time).toBe(123 * 1000);
  619. });
  620. });
  621. describe('use useValueForTime', () => {
  622. beforeEach(async () => {
  623. options.annotation.useValueForTime = true;
  624. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  625. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  626. await ctx.ds.annotationQuery(options).then((data: any) => {
  627. results = data;
  628. });
  629. });
  630. it('should return annotation list', () => {
  631. expect(results[0].time).toEqual(1);
  632. });
  633. });
  634. describe('step parameter', () => {
  635. beforeEach(() => {
  636. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  637. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  638. });
  639. it('should use default step for short range if no interval is given', () => {
  640. const query = {
  641. ...options,
  642. range: {
  643. from: time({ seconds: 63 }),
  644. to: time({ seconds: 123 }),
  645. },
  646. };
  647. ctx.ds.annotationQuery(query);
  648. const req = backendSrv.datasourceRequest.mock.calls[0][0];
  649. expect(req.url).toContain('step=60');
  650. });
  651. it('should use custom step for short range', () => {
  652. const annotation = {
  653. ...options.annotation,
  654. step: '10s',
  655. };
  656. const query = {
  657. ...options,
  658. annotation,
  659. range: {
  660. from: time({ seconds: 63 }),
  661. to: time({ seconds: 123 }),
  662. },
  663. };
  664. ctx.ds.annotationQuery(query);
  665. const req = backendSrv.datasourceRequest.mock.calls[0][0];
  666. expect(req.url).toContain('step=10');
  667. });
  668. it('should use custom step for short range', () => {
  669. const annotation = {
  670. ...options.annotation,
  671. step: '10s',
  672. };
  673. const query = {
  674. ...options,
  675. annotation,
  676. range: {
  677. from: time({ seconds: 63 }),
  678. to: time({ seconds: 123 }),
  679. },
  680. };
  681. ctx.ds.annotationQuery(query);
  682. const req = backendSrv.datasourceRequest.mock.calls[0][0];
  683. expect(req.url).toContain('step=10');
  684. });
  685. it('should use dynamic step on long ranges if no option was given', () => {
  686. const query = {
  687. ...options,
  688. range: {
  689. from: time({ seconds: 63 }),
  690. to: time({ hours: 24 * 30, seconds: 63 }),
  691. },
  692. };
  693. ctx.ds.annotationQuery(query);
  694. const req = backendSrv.datasourceRequest.mock.calls[0][0];
  695. // Range in seconds: (to - from) / 1000
  696. // Max_datapoints: 11000
  697. // Step: range / max_datapoints
  698. const step = 236;
  699. expect(req.url).toContain(`step=${step}`);
  700. });
  701. });
  702. });
  703. describe('When resultFormat is table and instant = true', () => {
  704. let results: any;
  705. const query = {
  706. range: { from: time({ seconds: 63 }), to: time({ seconds: 123 }) },
  707. targets: [{ expr: 'test{job="testjob"}', format: 'time_series', instant: true }],
  708. interval: '60s',
  709. };
  710. beforeEach(async () => {
  711. const response = {
  712. status: 'success',
  713. data: {
  714. data: {
  715. resultType: 'vector',
  716. result: [
  717. {
  718. metric: { __name__: 'test', job: 'testjob' },
  719. value: [123, '3846'],
  720. },
  721. ],
  722. },
  723. },
  724. };
  725. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  726. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  727. ctx.ds.query(query).subscribe((data: any) => {
  728. results = data;
  729. });
  730. });
  731. it('should return result', () => {
  732. expect(results).not.toBe(null);
  733. });
  734. });
  735. describe('The "step" query parameter', () => {
  736. const response = {
  737. status: 'success',
  738. data: {
  739. data: {
  740. resultType: 'matrix',
  741. result: [] as DataQueryResponseData[],
  742. },
  743. },
  744. };
  745. it('should be min interval when greater than auto interval', async () => {
  746. const query = {
  747. // 6 minute range
  748. range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) },
  749. targets: [
  750. {
  751. expr: 'test',
  752. interval: '10s',
  753. },
  754. ],
  755. interval: '5s',
  756. };
  757. const urlExpected = 'proxied/api/v1/query_range?query=test&start=60&end=420&step=10';
  758. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  759. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  760. ctx.ds.query(query);
  761. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  762. expect(res.method).toBe('GET');
  763. expect(res.url).toBe(urlExpected);
  764. });
  765. it('step should never go below 1', async () => {
  766. const query = {
  767. // 6 minute range
  768. range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) },
  769. targets: [{ expr: 'test' }],
  770. interval: '100ms',
  771. };
  772. const urlExpected = 'proxied/api/v1/query_range?query=test&start=60&end=420&step=1';
  773. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  774. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  775. ctx.ds.query(query);
  776. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  777. expect(res.method).toBe('GET');
  778. expect(res.url).toBe(urlExpected);
  779. });
  780. it('should be auto interval when greater than min interval', async () => {
  781. const query = {
  782. // 6 minute range
  783. range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) },
  784. targets: [
  785. {
  786. expr: 'test',
  787. interval: '5s',
  788. },
  789. ],
  790. interval: '10s',
  791. };
  792. const urlExpected = 'proxied/api/v1/query_range?query=test&start=60&end=420&step=10';
  793. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  794. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  795. ctx.ds.query(query);
  796. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  797. expect(res.method).toBe('GET');
  798. expect(res.url).toBe(urlExpected);
  799. });
  800. it('should result in querying fewer than 11000 data points', async () => {
  801. const query = {
  802. // 6 hour range
  803. range: { from: time({ hours: 1 }), to: time({ hours: 7 }) },
  804. targets: [{ expr: 'test' }],
  805. interval: '1s',
  806. };
  807. const end = 7 * 60 * 60;
  808. const start = 60 * 60;
  809. const urlExpected = 'proxied/api/v1/query_range?query=test&start=' + start + '&end=' + end + '&step=2';
  810. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  811. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  812. ctx.ds.query(query);
  813. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  814. expect(res.method).toBe('GET');
  815. expect(res.url).toBe(urlExpected);
  816. });
  817. it('should not apply min interval when interval * intervalFactor greater', async () => {
  818. const query = {
  819. // 6 minute range
  820. range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) },
  821. targets: [
  822. {
  823. expr: 'test',
  824. interval: '10s',
  825. intervalFactor: 10,
  826. },
  827. ],
  828. interval: '5s',
  829. };
  830. // times get rounded up to interval
  831. const urlExpected = 'proxied/api/v1/query_range?query=test&start=50&end=400&step=50';
  832. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  833. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  834. ctx.ds.query(query);
  835. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  836. expect(res.method).toBe('GET');
  837. expect(res.url).toBe(urlExpected);
  838. });
  839. it('should apply min interval when interval * intervalFactor smaller', async () => {
  840. const query = {
  841. // 6 minute range
  842. range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) },
  843. targets: [
  844. {
  845. expr: 'test',
  846. interval: '15s',
  847. intervalFactor: 2,
  848. },
  849. ],
  850. interval: '5s',
  851. };
  852. const urlExpected = 'proxied/api/v1/query_range?query=test' + '&start=60&end=420&step=15';
  853. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  854. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  855. ctx.ds.query(query);
  856. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  857. expect(res.method).toBe('GET');
  858. expect(res.url).toBe(urlExpected);
  859. });
  860. it('should apply intervalFactor to auto interval when greater', async () => {
  861. const query = {
  862. // 6 minute range
  863. range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) },
  864. targets: [
  865. {
  866. expr: 'test',
  867. interval: '5s',
  868. intervalFactor: 10,
  869. },
  870. ],
  871. interval: '10s',
  872. };
  873. // times get aligned to interval
  874. const urlExpected = 'proxied/api/v1/query_range?query=test' + '&start=0&end=400&step=100';
  875. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  876. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  877. ctx.ds.query(query);
  878. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  879. expect(res.method).toBe('GET');
  880. expect(res.url).toBe(urlExpected);
  881. });
  882. it('should not not be affected by the 11000 data points limit when large enough', async () => {
  883. const query = {
  884. // 1 week range
  885. range: { from: time({}), to: time({ hours: 7 * 24 }) },
  886. targets: [
  887. {
  888. expr: 'test',
  889. intervalFactor: 10,
  890. },
  891. ],
  892. interval: '10s',
  893. };
  894. const end = 7 * 24 * 60 * 60;
  895. const start = 0;
  896. const urlExpected = 'proxied/api/v1/query_range?query=test' + '&start=' + start + '&end=' + end + '&step=100';
  897. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  898. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  899. ctx.ds.query(query);
  900. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  901. expect(res.method).toBe('GET');
  902. expect(res.url).toBe(urlExpected);
  903. });
  904. it('should be determined by the 11000 data points limit when too small', async () => {
  905. const query = {
  906. // 1 week range
  907. range: { from: time({}), to: time({ hours: 7 * 24 }) },
  908. targets: [
  909. {
  910. expr: 'test',
  911. intervalFactor: 10,
  912. },
  913. ],
  914. interval: '5s',
  915. };
  916. const end = 7 * 24 * 60 * 60;
  917. const start = 0;
  918. const urlExpected = 'proxied/api/v1/query_range?query=test' + '&start=' + start + '&end=' + end + '&step=60';
  919. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  920. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  921. ctx.ds.query(query);
  922. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  923. expect(res.method).toBe('GET');
  924. expect(res.url).toBe(urlExpected);
  925. });
  926. });
  927. describe('The __interval and __interval_ms template variables', () => {
  928. const response = {
  929. status: 'success',
  930. data: {
  931. data: {
  932. resultType: 'matrix',
  933. result: [] as DataQueryResponseData[],
  934. },
  935. },
  936. };
  937. it('should be unchanged when auto interval is greater than min interval', async () => {
  938. const query = {
  939. // 6 minute range
  940. range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) },
  941. targets: [
  942. {
  943. expr: 'rate(test[$__interval])',
  944. interval: '5s',
  945. },
  946. ],
  947. interval: '10s',
  948. scopedVars: {
  949. __interval: { text: '10s', value: '10s' },
  950. __interval_ms: { text: 10 * 1000, value: 10 * 1000 },
  951. },
  952. };
  953. const urlExpected =
  954. 'proxied/api/v1/query_range?query=' +
  955. encodeURIComponent('rate(test[$__interval])') +
  956. '&start=60&end=420&step=10';
  957. templateSrv.replace = jest.fn(str => str);
  958. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  959. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  960. ctx.ds.query(query);
  961. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  962. expect(res.method).toBe('GET');
  963. expect(res.url).toBe(urlExpected);
  964. // @ts-ignore
  965. expect(templateSrv.replace.mock.calls[0][1]).toEqual({
  966. __interval: {
  967. text: '10s',
  968. value: '10s',
  969. },
  970. __interval_ms: {
  971. text: 10000,
  972. value: 10000,
  973. },
  974. });
  975. });
  976. it('should be min interval when it is greater than auto interval', async () => {
  977. const query = {
  978. // 6 minute range
  979. range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) },
  980. targets: [
  981. {
  982. expr: 'rate(test[$__interval])',
  983. interval: '10s',
  984. },
  985. ],
  986. interval: '5s',
  987. scopedVars: {
  988. __interval: { text: '5s', value: '5s' },
  989. __interval_ms: { text: 5 * 1000, value: 5 * 1000 },
  990. },
  991. };
  992. const urlExpected =
  993. 'proxied/api/v1/query_range?query=' +
  994. encodeURIComponent('rate(test[$__interval])') +
  995. '&start=60&end=420&step=10';
  996. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  997. templateSrv.replace = jest.fn(str => str);
  998. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  999. ctx.ds.query(query);
  1000. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  1001. expect(res.method).toBe('GET');
  1002. expect(res.url).toBe(urlExpected);
  1003. // @ts-ignore
  1004. expect(templateSrv.replace.mock.calls[0][1]).toEqual({
  1005. __interval: {
  1006. text: '5s',
  1007. value: '5s',
  1008. },
  1009. __interval_ms: {
  1010. text: 5000,
  1011. value: 5000,
  1012. },
  1013. });
  1014. });
  1015. it('should account for intervalFactor', async () => {
  1016. const query = {
  1017. // 6 minute range
  1018. range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) },
  1019. targets: [
  1020. {
  1021. expr: 'rate(test[$__interval])',
  1022. interval: '5s',
  1023. intervalFactor: 10,
  1024. },
  1025. ],
  1026. interval: '10s',
  1027. scopedVars: {
  1028. __interval: { text: '10s', value: '10s' },
  1029. __interval_ms: { text: 10 * 1000, value: 10 * 1000 },
  1030. },
  1031. };
  1032. const urlExpected =
  1033. 'proxied/api/v1/query_range?query=' +
  1034. encodeURIComponent('rate(test[$__interval])') +
  1035. '&start=0&end=400&step=100';
  1036. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  1037. templateSrv.replace = jest.fn(str => str);
  1038. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  1039. ctx.ds.query(query);
  1040. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  1041. expect(res.method).toBe('GET');
  1042. expect(res.url).toBe(urlExpected);
  1043. // @ts-ignore
  1044. expect(templateSrv.replace.mock.calls[0][1]).toEqual({
  1045. __interval: {
  1046. text: '10s',
  1047. value: '10s',
  1048. },
  1049. __interval_ms: {
  1050. text: 10000,
  1051. value: 10000,
  1052. },
  1053. });
  1054. expect(query.scopedVars.__interval.text).toBe('10s');
  1055. expect(query.scopedVars.__interval.value).toBe('10s');
  1056. expect(query.scopedVars.__interval_ms.text).toBe(10 * 1000);
  1057. expect(query.scopedVars.__interval_ms.value).toBe(10 * 1000);
  1058. });
  1059. it('should be interval * intervalFactor when greater than min interval', async () => {
  1060. const query = {
  1061. // 6 minute range
  1062. range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) },
  1063. targets: [
  1064. {
  1065. expr: 'rate(test[$__interval])',
  1066. interval: '10s',
  1067. intervalFactor: 10,
  1068. },
  1069. ],
  1070. interval: '5s',
  1071. scopedVars: {
  1072. __interval: { text: '5s', value: '5s' },
  1073. __interval_ms: { text: 5 * 1000, value: 5 * 1000 },
  1074. },
  1075. };
  1076. const urlExpected =
  1077. 'proxied/api/v1/query_range?query=' +
  1078. encodeURIComponent('rate(test[$__interval])') +
  1079. '&start=50&end=400&step=50';
  1080. templateSrv.replace = jest.fn(str => str);
  1081. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  1082. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  1083. ctx.ds.query(query);
  1084. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  1085. expect(res.method).toBe('GET');
  1086. expect(res.url).toBe(urlExpected);
  1087. // @ts-ignore
  1088. expect(templateSrv.replace.mock.calls[0][1]).toEqual({
  1089. __interval: {
  1090. text: '5s',
  1091. value: '5s',
  1092. },
  1093. __interval_ms: {
  1094. text: 5000,
  1095. value: 5000,
  1096. },
  1097. });
  1098. });
  1099. it('should be min interval when greater than interval * intervalFactor', async () => {
  1100. const query = {
  1101. // 6 minute range
  1102. range: { from: time({ minutes: 1 }), to: time({ minutes: 7 }) },
  1103. targets: [
  1104. {
  1105. expr: 'rate(test[$__interval])',
  1106. interval: '15s',
  1107. intervalFactor: 2,
  1108. },
  1109. ],
  1110. interval: '5s',
  1111. scopedVars: {
  1112. __interval: { text: '5s', value: '5s' },
  1113. __interval_ms: { text: 5 * 1000, value: 5 * 1000 },
  1114. },
  1115. };
  1116. const urlExpected =
  1117. 'proxied/api/v1/query_range?query=' +
  1118. encodeURIComponent('rate(test[$__interval])') +
  1119. '&start=60&end=420&step=15';
  1120. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  1121. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  1122. ctx.ds.query(query);
  1123. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  1124. expect(res.method).toBe('GET');
  1125. expect(res.url).toBe(urlExpected);
  1126. // @ts-ignore
  1127. expect(templateSrv.replace.mock.calls[0][1]).toEqual({
  1128. __interval: {
  1129. text: '5s',
  1130. value: '5s',
  1131. },
  1132. __interval_ms: {
  1133. text: 5000,
  1134. value: 5000,
  1135. },
  1136. });
  1137. });
  1138. it('should be determined by the 11000 data points limit, accounting for intervalFactor', async () => {
  1139. const query = {
  1140. // 1 week range
  1141. range: { from: time({}), to: time({ hours: 7 * 24 }) },
  1142. targets: [
  1143. {
  1144. expr: 'rate(test[$__interval])',
  1145. intervalFactor: 10,
  1146. },
  1147. ],
  1148. interval: '5s',
  1149. scopedVars: {
  1150. __interval: { text: '5s', value: '5s' },
  1151. __interval_ms: { text: 5 * 1000, value: 5 * 1000 },
  1152. },
  1153. };
  1154. const end = 7 * 24 * 60 * 60;
  1155. const start = 0;
  1156. const urlExpected =
  1157. 'proxied/api/v1/query_range?query=' +
  1158. encodeURIComponent('rate(test[$__interval])') +
  1159. '&start=' +
  1160. start +
  1161. '&end=' +
  1162. end +
  1163. '&step=60';
  1164. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  1165. templateSrv.replace = jest.fn(str => str);
  1166. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  1167. ctx.ds.query(query);
  1168. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  1169. expect(res.method).toBe('GET');
  1170. expect(res.url).toBe(urlExpected);
  1171. // @ts-ignore
  1172. expect(templateSrv.replace.mock.calls[0][1]).toEqual({
  1173. __interval: {
  1174. text: '5s',
  1175. value: '5s',
  1176. },
  1177. __interval_ms: {
  1178. text: 5000,
  1179. value: 5000,
  1180. },
  1181. });
  1182. });
  1183. });
  1184. describe('The __range, __range_s and __range_ms variables', () => {
  1185. const response = {
  1186. status: 'success',
  1187. data: {
  1188. data: {
  1189. resultType: 'matrix',
  1190. result: [] as DataQueryResponseData[],
  1191. },
  1192. },
  1193. };
  1194. it('should use overridden ranges, not dashboard ranges', async () => {
  1195. const expectedRangeSecond = 3600;
  1196. const expectedRangeString = '1h';
  1197. const query = {
  1198. range: {
  1199. from: time({}),
  1200. to: time({ hours: 1 }),
  1201. },
  1202. targets: [
  1203. {
  1204. expr: 'test[${__range_s}s]',
  1205. },
  1206. ],
  1207. interval: '60s',
  1208. };
  1209. const urlExpected = `proxied/api/v1/query_range?query=${encodeURIComponent(
  1210. query.targets[0].expr
  1211. )}&start=0&end=3600&step=60`;
  1212. templateSrv.replace = jest.fn(str => str);
  1213. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  1214. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  1215. ctx.ds.query(query);
  1216. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  1217. expect(res.url).toBe(urlExpected);
  1218. // @ts-ignore
  1219. expect(templateSrv.replace.mock.calls[1][1]).toEqual({
  1220. __range_s: {
  1221. text: expectedRangeSecond,
  1222. value: expectedRangeSecond,
  1223. },
  1224. __range: {
  1225. text: expectedRangeString,
  1226. value: expectedRangeString,
  1227. },
  1228. __range_ms: {
  1229. text: expectedRangeSecond * 1000,
  1230. value: expectedRangeSecond * 1000,
  1231. },
  1232. });
  1233. });
  1234. });
  1235. });
  1236. describe('PrometheusDatasource for POST', () => {
  1237. // const ctx = new helpers.ServiceTestContext();
  1238. const instanceSettings = ({
  1239. url: 'proxied',
  1240. directUrl: 'direct',
  1241. user: 'test',
  1242. password: 'mupp',
  1243. jsonData: { httpMethod: 'POST' },
  1244. } as unknown) as DataSourceInstanceSettings<PromOptions>;
  1245. describe('When querying prometheus with one target using query editor target spec', () => {
  1246. let results: any;
  1247. const urlExpected = 'proxied/api/v1/query_range';
  1248. const dataExpected = {
  1249. query: 'test{job="testjob"}',
  1250. start: 1 * 60,
  1251. end: 2 * 60,
  1252. step: 60,
  1253. };
  1254. const query = {
  1255. range: { from: time({ minutes: 1, seconds: 3 }), to: time({ minutes: 2, seconds: 3 }) },
  1256. targets: [{ expr: 'test{job="testjob"}', format: 'time_series' }],
  1257. interval: '60s',
  1258. };
  1259. beforeEach(async () => {
  1260. const response = {
  1261. status: 'success',
  1262. data: {
  1263. data: {
  1264. resultType: 'matrix',
  1265. result: [
  1266. {
  1267. metric: { __name__: 'test', job: 'testjob' },
  1268. values: [[2 * 60, '3846']],
  1269. },
  1270. ],
  1271. },
  1272. },
  1273. };
  1274. backendSrv.datasourceRequest = jest.fn(() => Promise.resolve(response));
  1275. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  1276. ctx.ds.query(query).subscribe((data: any) => {
  1277. results = data;
  1278. });
  1279. });
  1280. it('should generate the correct query', () => {
  1281. const res = backendSrv.datasourceRequest.mock.calls[0][0];
  1282. expect(res.method).toBe('POST');
  1283. expect(res.url).toBe(urlExpected);
  1284. expect(res.data).toEqual(dataExpected);
  1285. });
  1286. it('should return series list', () => {
  1287. expect(results.data.length).toBe(1);
  1288. expect(results.data[0].target).toBe('test{job="testjob"}');
  1289. });
  1290. });
  1291. describe('When querying prometheus via check headers X-Dashboard-Id and X-Panel-Id', () => {
  1292. const options = { dashboardId: 1, panelId: 2 };
  1293. const httpOptions = {
  1294. headers: {} as { [key: string]: number | undefined },
  1295. };
  1296. it('with proxy access tracing headers should be added', () => {
  1297. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  1298. ctx.ds._addTracingHeaders(httpOptions, options);
  1299. expect(httpOptions.headers['X-Dashboard-Id']).toBe(1);
  1300. expect(httpOptions.headers['X-Panel-Id']).toBe(2);
  1301. });
  1302. it('with direct access tracing headers should not be added', () => {
  1303. instanceSettings.url = 'http://127.0.0.1:8000';
  1304. ctx.ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  1305. ctx.ds._addTracingHeaders(httpOptions, options);
  1306. expect(httpOptions.headers['X-Dashboard-Id']).toBe(undefined);
  1307. expect(httpOptions.headers['X-Panel-Id']).toBe(undefined);
  1308. });
  1309. });
  1310. });
  1311. const getPrepareTargetsContext = (target: PromQuery) => {
  1312. const instanceSettings = ({
  1313. url: 'proxied',
  1314. directUrl: 'direct',
  1315. user: 'test',
  1316. password: 'mupp',
  1317. jsonData: { httpMethod: 'POST' },
  1318. } as unknown) as DataSourceInstanceSettings<PromOptions>;
  1319. const start = 0;
  1320. const end = 1;
  1321. const panelId = '2';
  1322. const options = ({ targets: [target], interval: '1s', panelId } as any) as DataQueryRequest<PromQuery>;
  1323. const ds = new PrometheusDatasource(instanceSettings, q, backendSrv as any, templateSrv as any, timeSrv as any);
  1324. const { queries, activeTargets } = ds.prepareTargets(options, start, end);
  1325. return {
  1326. queries,
  1327. activeTargets,
  1328. start,
  1329. end,
  1330. panelId,
  1331. };
  1332. };
  1333. describe('prepareTargets', () => {
  1334. describe('when run from a Panel', () => {
  1335. it('then it should just add targets', () => {
  1336. const target: PromQuery = {
  1337. refId: 'A',
  1338. expr: 'up',
  1339. context: PromContext.Panel,
  1340. };
  1341. const { queries, activeTargets, panelId, end, start } = getPrepareTargetsContext(target);
  1342. expect(queries.length).toBe(1);
  1343. expect(activeTargets.length).toBe(1);
  1344. expect(queries[0]).toEqual({
  1345. end,
  1346. expr: 'up',
  1347. headers: {
  1348. 'X-Dashboard-Id': undefined,
  1349. 'X-Panel-Id': panelId,
  1350. },
  1351. hinting: undefined,
  1352. instant: undefined,
  1353. refId: target.refId,
  1354. requestId: panelId + target.refId,
  1355. start,
  1356. step: 1,
  1357. });
  1358. expect(activeTargets[0]).toEqual(target);
  1359. });
  1360. });
  1361. describe('when run from Explore', () => {
  1362. describe('and both Graph and Table are shown', () => {
  1363. it('then it should return both instant and time series related objects', () => {
  1364. const target: PromQuery = {
  1365. refId: 'A',
  1366. expr: 'up',
  1367. context: PromContext.Explore,
  1368. showingGraph: true,
  1369. showingTable: true,
  1370. };
  1371. const { queries, activeTargets, panelId, end, start } = getPrepareTargetsContext(target);
  1372. expect(queries.length).toBe(2);
  1373. expect(activeTargets.length).toBe(2);
  1374. expect(queries[0]).toEqual({
  1375. end,
  1376. expr: 'up',
  1377. headers: {
  1378. 'X-Dashboard-Id': undefined,
  1379. 'X-Panel-Id': panelId,
  1380. },
  1381. hinting: undefined,
  1382. instant: true,
  1383. refId: target.refId,
  1384. requestId: panelId + target.refId + '_instant',
  1385. start,
  1386. step: 1,
  1387. });
  1388. expect(activeTargets[0]).toEqual({
  1389. ...target,
  1390. format: 'table',
  1391. instant: true,
  1392. requestId: panelId + target.refId + '_instant',
  1393. valueWithRefId: true,
  1394. });
  1395. expect(queries[1]).toEqual({
  1396. end,
  1397. expr: 'up',
  1398. headers: {
  1399. 'X-Dashboard-Id': undefined,
  1400. 'X-Panel-Id': panelId,
  1401. },
  1402. hinting: undefined,
  1403. instant: false,
  1404. refId: target.refId,
  1405. requestId: panelId + target.refId,
  1406. start,
  1407. step: 1,
  1408. });
  1409. expect(activeTargets[1]).toEqual({
  1410. ...target,
  1411. format: 'time_series',
  1412. instant: false,
  1413. requestId: panelId + target.refId,
  1414. });
  1415. });
  1416. });
  1417. describe('and both Graph and Table are hidden', () => {
  1418. it('then it should return empty arrays', () => {
  1419. const target: PromQuery = {
  1420. refId: 'A',
  1421. expr: 'up',
  1422. context: PromContext.Explore,
  1423. showingGraph: false,
  1424. showingTable: false,
  1425. };
  1426. const { queries, activeTargets } = getPrepareTargetsContext(target);
  1427. expect(queries.length).toBe(0);
  1428. expect(activeTargets.length).toBe(0);
  1429. });
  1430. });
  1431. describe('and Graph is hidden', () => {
  1432. it('then it should return only intant related objects', () => {
  1433. const target: PromQuery = {
  1434. refId: 'A',
  1435. expr: 'up',
  1436. context: PromContext.Explore,
  1437. showingGraph: false,
  1438. showingTable: true,
  1439. };
  1440. const { queries, activeTargets, panelId, end, start } = getPrepareTargetsContext(target);
  1441. expect(queries.length).toBe(1);
  1442. expect(activeTargets.length).toBe(1);
  1443. expect(queries[0]).toEqual({
  1444. end,
  1445. expr: 'up',
  1446. headers: {
  1447. 'X-Dashboard-Id': undefined,
  1448. 'X-Panel-Id': panelId,
  1449. },
  1450. hinting: undefined,
  1451. instant: true,
  1452. refId: target.refId,
  1453. requestId: panelId + target.refId + '_instant',
  1454. start,
  1455. step: 1,
  1456. });
  1457. expect(activeTargets[0]).toEqual({
  1458. ...target,
  1459. format: 'table',
  1460. instant: true,
  1461. requestId: panelId + target.refId + '_instant',
  1462. valueWithRefId: true,
  1463. });
  1464. });
  1465. });
  1466. describe('and Table is hidden', () => {
  1467. it('then it should return only time series related objects', () => {
  1468. const target: PromQuery = {
  1469. refId: 'A',
  1470. expr: 'up',
  1471. context: PromContext.Explore,
  1472. showingGraph: true,
  1473. showingTable: false,
  1474. };
  1475. const { queries, activeTargets, panelId, end, start } = getPrepareTargetsContext(target);
  1476. expect(queries.length).toBe(1);
  1477. expect(activeTargets.length).toBe(1);
  1478. expect(queries[0]).toEqual({
  1479. end,
  1480. expr: 'up',
  1481. headers: {
  1482. 'X-Dashboard-Id': undefined,
  1483. 'X-Panel-Id': panelId,
  1484. },
  1485. hinting: undefined,
  1486. instant: false,
  1487. refId: target.refId,
  1488. requestId: panelId + target.refId,
  1489. start,
  1490. step: 1,
  1491. });
  1492. expect(activeTargets[0]).toEqual({
  1493. ...target,
  1494. format: 'time_series',
  1495. instant: false,
  1496. requestId: panelId + target.refId,
  1497. });
  1498. });
  1499. });
  1500. });
  1501. });