result_transformer.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. import { CircularDataFrame, FieldCache, FieldType, MutableDataFrame } from '@grafana/data';
  2. import { setTemplateSrv } from '@grafana/runtime';
  3. import { TemplateSrv } from 'app/features/templating/template_srv';
  4. import * as ResultTransformer from './result_transformer';
  5. import {
  6. LokiStreamResult,
  7. LokiTailResponse,
  8. LokiStreamResponse,
  9. LokiResultType,
  10. TransformerOptions,
  11. LokiMatrixResult,
  12. } from './types';
  13. const streamResult: LokiStreamResult[] = [
  14. {
  15. stream: {
  16. foo: 'bar',
  17. },
  18. values: [['1579857562021616000', "foo: 'bar'"]],
  19. },
  20. {
  21. stream: {
  22. bar: 'foo',
  23. },
  24. values: [['1579857562031616000', "bar: 'foo'"]],
  25. },
  26. ];
  27. const lokiResponse: LokiStreamResponse = {
  28. status: 'success',
  29. data: {
  30. result: streamResult,
  31. resultType: LokiResultType.Stream,
  32. stats: {
  33. summary: {
  34. bytesTotal: 900,
  35. },
  36. },
  37. },
  38. };
  39. jest.mock('@grafana/runtime', () => ({
  40. // @ts-ignore
  41. ...jest.requireActual('@grafana/runtime'),
  42. getDataSourceSrv: () => {
  43. return {
  44. getInstanceSettings: () => {
  45. return { name: 'Loki1' };
  46. },
  47. };
  48. },
  49. }));
  50. describe('loki result transformer', () => {
  51. beforeAll(() => {
  52. setTemplateSrv(new TemplateSrv());
  53. });
  54. afterAll(() => {
  55. jest.restoreAllMocks();
  56. });
  57. afterEach(() => {
  58. jest.clearAllMocks();
  59. });
  60. describe('lokiStreamsToRawDataFrame', () => {
  61. it('converts streams to series', () => {
  62. const data = ResultTransformer.lokiStreamsToRawDataFrame(streamResult);
  63. expect(data.fields[0].values.get(0)).toStrictEqual({ foo: 'bar' });
  64. expect(data.fields[1].values.get(0)).toEqual('2020-01-24T09:19:22.021Z');
  65. expect(data.fields[2].values.get(0)).toEqual(streamResult[0].values[0][1]);
  66. expect(data.fields[3].values.get(0)).toEqual(streamResult[0].values[0][0]);
  67. expect(data.fields[4].values.get(0)).toEqual('4b79cb43-81ce-52f7-b1e9-a207fff144dc');
  68. expect(data.fields[0].values.get(1)).toStrictEqual({ bar: 'foo' });
  69. expect(data.fields[1].values.get(1)).toEqual('2020-01-24T09:19:22.031Z');
  70. expect(data.fields[2].values.get(1)).toEqual(streamResult[1].values[0][1]);
  71. expect(data.fields[3].values.get(1)).toEqual(streamResult[1].values[0][0]);
  72. expect(data.fields[4].values.get(1)).toEqual('73d144f6-57f2-5a45-a49c-eb998e2006b1');
  73. });
  74. it('should always generate unique ids for logs', () => {
  75. const streamResultWithDuplicateLogs: LokiStreamResult[] = [
  76. {
  77. stream: {
  78. foo: 'bar',
  79. },
  80. values: [
  81. ['1579857562021616000', 't=2020-02-12T15:04:51+0000 lvl=info msg="Duplicated"'],
  82. ['1579857562021616000', 't=2020-02-12T15:04:51+0000 lvl=info msg="Duplicated"'],
  83. ['1579857562021616000', 't=2020-02-12T15:04:51+0000 lvl=info msg="Non-duplicated"'],
  84. ['1579857562021616000', 't=2020-02-12T15:04:51+0000 lvl=info msg="Duplicated"'],
  85. ],
  86. },
  87. {
  88. stream: {
  89. bar: 'foo',
  90. },
  91. values: [['1579857562021617000', 't=2020-02-12T15:04:51+0000 lvl=info msg="Non-dupliicated"']],
  92. },
  93. ];
  94. const data = ResultTransformer.lokiStreamsToRawDataFrame(streamResultWithDuplicateLogs);
  95. expect(data.fields[4].values.get(0)).toEqual('b48fe7dc-36aa-5d37-bfba-087ef810d8fa');
  96. expect(data.fields[4].values.get(1)).toEqual('b48fe7dc-36aa-5d37-bfba-087ef810d8fa_1');
  97. expect(data.fields[4].values.get(2)).not.toEqual('b48fe7dc-36aa-5d37-bfba-087ef810d8fa_2');
  98. expect(data.fields[4].values.get(3)).toEqual('b48fe7dc-36aa-5d37-bfba-087ef810d8fa_2');
  99. expect(data.fields[4].values.get(4)).not.toEqual('b48fe7dc-36aa-5d37-bfba-087ef810d8fa_3');
  100. });
  101. it('should append refId to the unique ids if refId is provided', () => {
  102. const data = ResultTransformer.lokiStreamsToRawDataFrame(streamResult, 'B');
  103. expect(data.fields[4].values.get(0)).toEqual('4b79cb43-81ce-52f7-b1e9-a207fff144dc_B');
  104. expect(data.fields[4].values.get(1)).toEqual('73d144f6-57f2-5a45-a49c-eb998e2006b1_B');
  105. });
  106. });
  107. describe('lokiStreamsToDataFrames', () => {
  108. it('should enhance data frames', () => {
  109. jest.spyOn(ResultTransformer, 'enhanceDataFrame');
  110. const dataFrames = ResultTransformer.lokiStreamsToDataFrames(lokiResponse, { refId: 'B', expr: '' }, 500, {
  111. derivedFields: [
  112. {
  113. matcherRegex: 'trace=(w+)',
  114. name: 'test',
  115. url: 'example.com',
  116. },
  117. ],
  118. });
  119. expect(ResultTransformer.enhanceDataFrame).toBeCalled();
  120. dataFrames.forEach((frame) => {
  121. expect(
  122. frame.fields.filter((field) => field.name === 'test' && field.type === 'string').length
  123. ).toBeGreaterThanOrEqual(1);
  124. });
  125. });
  126. });
  127. describe('appendResponseToBufferedData', () => {
  128. it('should return a dataframe with ts in iso format', () => {
  129. const tailResponse: LokiTailResponse = {
  130. streams: [
  131. {
  132. stream: {
  133. filename: '/var/log/grafana/grafana.log',
  134. job: 'grafana',
  135. },
  136. values: [
  137. [
  138. '1581519914265798400',
  139. 't=2020-02-12T15:04:51+0000 lvl=info msg="Starting Grafana" logger=server version=6.7.0-pre commit=6f09bc9fb4 branch=issue-21929 compiled=2020-02-11T20:43:28+0000',
  140. ],
  141. ],
  142. },
  143. ],
  144. };
  145. const data = new CircularDataFrame({ capacity: 1 });
  146. data.addField({ name: 'labels', type: FieldType.other });
  147. data.addField({ name: 'ts', type: FieldType.time, config: { displayName: 'Time' } });
  148. data.addField({ name: 'line', type: FieldType.string }).labels = { job: 'grafana' };
  149. data.addField({ name: 'id', type: FieldType.string });
  150. data.addField({ name: 'tsNs', type: FieldType.time, config: { displayName: 'Time ns' } });
  151. ResultTransformer.appendResponseToBufferedData(tailResponse, data);
  152. expect(data.get(0)).toEqual({
  153. ts: '2020-02-12T15:05:14.265Z',
  154. tsNs: '1581519914265798400',
  155. line: 't=2020-02-12T15:04:51+0000 lvl=info msg="Starting Grafana" logger=server version=6.7.0-pre commit=6f09bc9fb4 branch=issue-21929 compiled=2020-02-11T20:43:28+0000',
  156. labels: { filename: '/var/log/grafana/grafana.log' },
  157. id: '07f0607c-04ee-51bd-8a0c-fc0f85d37489',
  158. });
  159. });
  160. it('should always generate unique ids for logs', () => {
  161. const tailResponse: LokiTailResponse = {
  162. streams: [
  163. {
  164. stream: {
  165. filename: '/var/log/grafana/grafana.log',
  166. job: 'grafana',
  167. },
  168. values: [
  169. ['1581519914265798400', 't=2020-02-12T15:04:51+0000 lvl=info msg="Dupplicated 1"'],
  170. ['1581519914265798400', 't=2020-02-12T15:04:51+0000 lvl=info msg="Dupplicated 1"'],
  171. ['1581519914265798400', 't=2020-02-12T15:04:51+0000 lvl=info msg="Dupplicated 2"'],
  172. ['1581519914265798400', 't=2020-02-12T15:04:51+0000 lvl=info msg="Not dupplicated"'],
  173. ['1581519914265798400', 't=2020-02-12T15:04:51+0000 lvl=info msg="Dupplicated 1"'],
  174. ['1581519914265798400', 't=2020-02-12T15:04:51+0000 lvl=info msg="Dupplicated 2"'],
  175. ],
  176. },
  177. ],
  178. };
  179. const data = new CircularDataFrame({ capacity: 6 });
  180. data.addField({ name: 'labels', type: FieldType.other });
  181. data.addField({ name: 'ts', type: FieldType.time, config: { displayName: 'Time' } });
  182. data.addField({ name: 'line', type: FieldType.string }).labels = { job: 'grafana' };
  183. data.addField({ name: 'id', type: FieldType.string });
  184. data.addField({ name: 'tsNs', type: FieldType.time, config: { displayName: 'Time ns' } });
  185. data.refId = 'C';
  186. ResultTransformer.appendResponseToBufferedData(tailResponse, data);
  187. expect(data.get(0).id).toEqual('75e72b25-8589-5f99-8d10-ccb5eb27c1b4_C');
  188. expect(data.get(1).id).toEqual('75e72b25-8589-5f99-8d10-ccb5eb27c1b4_1_C');
  189. expect(data.get(2).id).toEqual('3ca99d6b-3ab5-5970-93c0-eb3c9449088e_C');
  190. expect(data.get(3).id).toEqual('ec9bea1d-70cb-556c-8519-d5d6ae18c004_C');
  191. expect(data.get(4).id).toEqual('75e72b25-8589-5f99-8d10-ccb5eb27c1b4_2_C');
  192. expect(data.get(5).id).toEqual('3ca99d6b-3ab5-5970-93c0-eb3c9449088e_1_C');
  193. });
  194. });
  195. describe('createMetricLabel', () => {
  196. it('should create correct label based on passed variables', () => {
  197. const label = ResultTransformer.createMetricLabel({}, {
  198. scopedVars: { testLabel: { selected: true, text: 'label1', value: 'label1' } },
  199. legendFormat: '{{$testLabel}}',
  200. } as unknown as TransformerOptions);
  201. expect(label).toBe('label1');
  202. });
  203. });
  204. describe('lokiResultsToTableModel', () => {
  205. it('should correctly set the type of the label column to be a string', () => {
  206. const lokiResultWithIntLabel = [
  207. { metric: { test: 1 }, value: [1610367143, 10] },
  208. { metric: { test: 2 }, value: [1610367144, 20] },
  209. ] as unknown as LokiMatrixResult[];
  210. const table = ResultTransformer.lokiResultsToTableModel(lokiResultWithIntLabel, 1, 'A', {});
  211. expect(table.columns[0].type).toBe('time');
  212. expect(table.columns[1].type).toBe('string');
  213. expect(table.columns[2].type).toBe('number');
  214. });
  215. });
  216. });
  217. describe('enhanceDataFrame', () => {
  218. it('adds links to fields', () => {
  219. const df = new MutableDataFrame({ fields: [{ name: 'Line', values: ['nothing', 'trace1=1234', 'trace2=foo'] }] });
  220. ResultTransformer.enhanceDataFrame(df, {
  221. derivedFields: [
  222. {
  223. matcherRegex: 'trace1=(\\w+)',
  224. name: 'trace1',
  225. url: 'http://localhost/${__value.raw}',
  226. },
  227. {
  228. matcherRegex: 'trace2=(\\w+)',
  229. name: 'trace2',
  230. url: 'test',
  231. datasourceUid: 'uid',
  232. },
  233. {
  234. matcherRegex: 'trace2=(\\w+)',
  235. name: 'trace2',
  236. url: 'test',
  237. datasourceUid: 'uid2',
  238. urlDisplayLabel: 'Custom Label',
  239. },
  240. ],
  241. });
  242. expect(df.fields.length).toBe(3);
  243. const fc = new FieldCache(df);
  244. expect(fc.getFieldByName('trace1')!.values.toArray()).toEqual([null, '1234', null]);
  245. expect(fc.getFieldByName('trace1')!.config.links![0]).toEqual({
  246. url: 'http://localhost/${__value.raw}',
  247. title: '',
  248. });
  249. expect(fc.getFieldByName('trace2')!.values.toArray()).toEqual([null, null, 'foo']);
  250. expect(fc.getFieldByName('trace2')!.config.links!.length).toBe(2);
  251. expect(fc.getFieldByName('trace2')!.config.links![0]).toEqual({
  252. title: '',
  253. internal: { datasourceName: 'Loki1', datasourceUid: 'uid', query: { query: 'test' } },
  254. url: '',
  255. });
  256. expect(fc.getFieldByName('trace2')!.config.links![1]).toEqual({
  257. title: 'Custom Label',
  258. internal: { datasourceName: 'Loki1', datasourceUid: 'uid2', query: { query: 'test' } },
  259. url: '',
  260. });
  261. });
  262. describe('lokiPointsToTimeseriesPoints()', () => {
  263. /**
  264. * NOTE on time parameters:
  265. * - Input time series data has timestamps in sec (like Prometheus)
  266. * - Output time series has timestamps in ms (as expected for the chart lib)
  267. */
  268. const data: Array<[number, string]> = [
  269. [1, '1'],
  270. [2, '0'],
  271. [4, '1'],
  272. [7, 'NaN'],
  273. [8, '+Inf'],
  274. [9, '-Inf'],
  275. ];
  276. it('returns data as is if step, start, and end align', () => {
  277. const result = ResultTransformer.lokiPointsToTimeseriesPoints(data);
  278. expect(result).toEqual([
  279. [1, 1000],
  280. [0, 2000],
  281. [1, 4000],
  282. [NaN, 7000],
  283. [Infinity, 8000],
  284. [-Infinity, 9000],
  285. ]);
  286. });
  287. });
  288. });