elastic_response.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. import _ from 'lodash';
  2. import flatten from 'app/core/utils/flatten';
  3. import * as queryDef from './query_def';
  4. import TableModel from 'app/core/table_model';
  5. import { DataFrame, toDataFrame, FieldType } from '@grafana/data';
  6. import { DataQueryResponse } from '@grafana/ui';
  7. export class ElasticResponse {
  8. constructor(private targets, private response) {
  9. this.targets = targets;
  10. this.response = response;
  11. }
  12. processMetrics(esAgg, target, seriesList, props) {
  13. let metric, y, i, newSeries, bucket, value;
  14. for (y = 0; y < target.metrics.length; y++) {
  15. metric = target.metrics[y];
  16. if (metric.hide) {
  17. continue;
  18. }
  19. switch (metric.type) {
  20. case 'count': {
  21. newSeries = { datapoints: [], metric: 'count', props: props };
  22. for (i = 0; i < esAgg.buckets.length; i++) {
  23. bucket = esAgg.buckets[i];
  24. value = bucket.doc_count;
  25. newSeries.datapoints.push([value, bucket.key]);
  26. }
  27. seriesList.push(newSeries);
  28. break;
  29. }
  30. case 'percentiles': {
  31. if (esAgg.buckets.length === 0) {
  32. break;
  33. }
  34. const firstBucket = esAgg.buckets[0];
  35. const percentiles = firstBucket[metric.id].values;
  36. for (const percentileName in percentiles) {
  37. newSeries = {
  38. datapoints: [],
  39. metric: 'p' + percentileName,
  40. props: props,
  41. field: metric.field,
  42. };
  43. for (i = 0; i < esAgg.buckets.length; i++) {
  44. bucket = esAgg.buckets[i];
  45. const values = bucket[metric.id].values;
  46. newSeries.datapoints.push([values[percentileName], bucket.key]);
  47. }
  48. seriesList.push(newSeries);
  49. }
  50. break;
  51. }
  52. case 'extended_stats': {
  53. for (const statName in metric.meta) {
  54. if (!metric.meta[statName]) {
  55. continue;
  56. }
  57. newSeries = {
  58. datapoints: [],
  59. metric: statName,
  60. props: props,
  61. field: metric.field,
  62. };
  63. for (i = 0; i < esAgg.buckets.length; i++) {
  64. bucket = esAgg.buckets[i];
  65. const stats = bucket[metric.id];
  66. // add stats that are in nested obj to top level obj
  67. stats.std_deviation_bounds_upper = stats.std_deviation_bounds.upper;
  68. stats.std_deviation_bounds_lower = stats.std_deviation_bounds.lower;
  69. newSeries.datapoints.push([stats[statName], bucket.key]);
  70. }
  71. seriesList.push(newSeries);
  72. }
  73. break;
  74. }
  75. default: {
  76. newSeries = {
  77. datapoints: [],
  78. metric: metric.type,
  79. field: metric.field,
  80. metricId: metric.id,
  81. props: props,
  82. };
  83. for (i = 0; i < esAgg.buckets.length; i++) {
  84. bucket = esAgg.buckets[i];
  85. value = bucket[metric.id];
  86. if (value !== undefined) {
  87. if (value.normalized_value) {
  88. newSeries.datapoints.push([value.normalized_value, bucket.key]);
  89. } else {
  90. newSeries.datapoints.push([value.value, bucket.key]);
  91. }
  92. }
  93. }
  94. seriesList.push(newSeries);
  95. break;
  96. }
  97. }
  98. }
  99. }
  100. processAggregationDocs(esAgg, aggDef, target, table, props) {
  101. // add columns
  102. if (table.columns.length === 0) {
  103. for (const propKey of _.keys(props)) {
  104. table.addColumn({ text: propKey, filterable: true });
  105. }
  106. table.addColumn({ text: aggDef.field, filterable: true });
  107. }
  108. // helper func to add values to value array
  109. const addMetricValue = (values, metricName, value) => {
  110. table.addColumn({ text: metricName });
  111. values.push(value);
  112. };
  113. for (const bucket of esAgg.buckets) {
  114. const values = [];
  115. for (const propValues of _.values(props)) {
  116. values.push(propValues);
  117. }
  118. // add bucket key (value)
  119. values.push(bucket.key);
  120. for (const metric of target.metrics) {
  121. switch (metric.type) {
  122. case 'count': {
  123. addMetricValue(values, this.getMetricName(metric.type), bucket.doc_count);
  124. break;
  125. }
  126. case 'extended_stats': {
  127. for (const statName in metric.meta) {
  128. if (!metric.meta[statName]) {
  129. continue;
  130. }
  131. const stats = bucket[metric.id];
  132. // add stats that are in nested obj to top level obj
  133. stats.std_deviation_bounds_upper = stats.std_deviation_bounds.upper;
  134. stats.std_deviation_bounds_lower = stats.std_deviation_bounds.lower;
  135. addMetricValue(values, this.getMetricName(statName), stats[statName]);
  136. }
  137. break;
  138. }
  139. case 'percentiles': {
  140. const percentiles = bucket[metric.id].values;
  141. for (const percentileName in percentiles) {
  142. addMetricValue(values, `p${percentileName} ${metric.field}`, percentiles[percentileName]);
  143. }
  144. break;
  145. }
  146. default: {
  147. let metricName = this.getMetricName(metric.type);
  148. const otherMetrics = _.filter(target.metrics, { type: metric.type });
  149. // if more of the same metric type include field field name in property
  150. if (otherMetrics.length > 1) {
  151. metricName += ' ' + metric.field;
  152. }
  153. addMetricValue(values, metricName, bucket[metric.id].value);
  154. break;
  155. }
  156. }
  157. }
  158. table.rows.push(values);
  159. }
  160. }
  161. // This is quite complex
  162. // need to recurse down the nested buckets to build series
  163. processBuckets(aggs, target, seriesList, table, props, depth) {
  164. let bucket, aggDef, esAgg, aggId;
  165. const maxDepth = target.bucketAggs.length - 1;
  166. for (aggId in aggs) {
  167. aggDef = _.find(target.bucketAggs, { id: aggId });
  168. esAgg = aggs[aggId];
  169. if (!aggDef) {
  170. continue;
  171. }
  172. if (depth === maxDepth) {
  173. if (aggDef.type === 'date_histogram') {
  174. this.processMetrics(esAgg, target, seriesList, props);
  175. } else {
  176. this.processAggregationDocs(esAgg, aggDef, target, table, props);
  177. }
  178. } else {
  179. for (const nameIndex in esAgg.buckets) {
  180. bucket = esAgg.buckets[nameIndex];
  181. props = _.clone(props);
  182. if (bucket.key !== void 0) {
  183. props[aggDef.field] = bucket.key;
  184. } else {
  185. props['filter'] = nameIndex;
  186. }
  187. if (bucket.key_as_string) {
  188. props[aggDef.field] = bucket.key_as_string;
  189. }
  190. this.processBuckets(bucket, target, seriesList, table, props, depth + 1);
  191. }
  192. }
  193. }
  194. }
  195. private getMetricName(metric) {
  196. let metricDef: any = _.find(queryDef.metricAggTypes, { value: metric });
  197. if (!metricDef) {
  198. metricDef = _.find(queryDef.extendedStats, { value: metric });
  199. }
  200. return metricDef ? metricDef.text : metric;
  201. }
  202. private getSeriesName(series, target, metricTypeCount) {
  203. let metricName = this.getMetricName(series.metric);
  204. if (target.alias) {
  205. const regex = /\{\{([\s\S]+?)\}\}/g;
  206. return target.alias.replace(regex, (match, g1, g2) => {
  207. const group = g1 || g2;
  208. if (group.indexOf('term ') === 0) {
  209. return series.props[group.substring(5)];
  210. }
  211. if (series.props[group] !== void 0) {
  212. return series.props[group];
  213. }
  214. if (group === 'metric') {
  215. return metricName;
  216. }
  217. if (group === 'field') {
  218. return series.field || '';
  219. }
  220. return match;
  221. });
  222. }
  223. if (series.field && queryDef.isPipelineAgg(series.metric)) {
  224. if (series.metric && queryDef.isPipelineAggWithMultipleBucketPaths(series.metric)) {
  225. const agg: any = _.find(target.metrics, { id: series.metricId });
  226. if (agg && agg.settings.script) {
  227. metricName = agg.settings.script;
  228. for (const pv of agg.pipelineVariables) {
  229. const appliedAgg: any = _.find(target.metrics, { id: pv.pipelineAgg });
  230. if (appliedAgg) {
  231. metricName = metricName.replace('params.' + pv.name, queryDef.describeMetric(appliedAgg));
  232. }
  233. }
  234. } else {
  235. metricName = 'Unset';
  236. }
  237. } else {
  238. const appliedAgg: any = _.find(target.metrics, { id: series.field });
  239. if (appliedAgg) {
  240. metricName += ' ' + queryDef.describeMetric(appliedAgg);
  241. } else {
  242. metricName = 'Unset';
  243. }
  244. }
  245. } else if (series.field) {
  246. metricName += ' ' + series.field;
  247. }
  248. const propKeys = _.keys(series.props);
  249. if (propKeys.length === 0) {
  250. return metricName;
  251. }
  252. let name = '';
  253. for (const propName in series.props) {
  254. name += series.props[propName] + ' ';
  255. }
  256. if (metricTypeCount === 1) {
  257. return name.trim();
  258. }
  259. return name.trim() + ' ' + metricName;
  260. }
  261. nameSeries(seriesList, target) {
  262. const metricTypeCount = _.uniq(_.map(seriesList, 'metric')).length;
  263. for (let i = 0; i < seriesList.length; i++) {
  264. const series = seriesList[i];
  265. series.target = this.getSeriesName(series, target, metricTypeCount);
  266. }
  267. }
  268. processHits(hits, seriesList) {
  269. const hitsTotal = typeof hits.total === 'number' ? hits.total : hits.total.value; // <- Works with Elasticsearch 7.0+
  270. const series = {
  271. target: 'docs',
  272. type: 'docs',
  273. datapoints: [],
  274. total: hitsTotal,
  275. filterable: true,
  276. };
  277. let propName, hit, doc, i;
  278. for (i = 0; i < hits.hits.length; i++) {
  279. hit = hits.hits[i];
  280. doc = {
  281. _id: hit._id,
  282. _type: hit._type,
  283. _index: hit._index,
  284. };
  285. if (hit._source) {
  286. for (propName in hit._source) {
  287. doc[propName] = hit._source[propName];
  288. }
  289. }
  290. for (propName in hit.fields) {
  291. doc[propName] = hit.fields[propName];
  292. }
  293. series.datapoints.push(doc);
  294. }
  295. seriesList.push(series);
  296. }
  297. trimDatapoints(aggregations, target) {
  298. const histogram: any = _.find(target.bucketAggs, { type: 'date_histogram' });
  299. const shouldDropFirstAndLast = histogram && histogram.settings && histogram.settings.trimEdges;
  300. if (shouldDropFirstAndLast) {
  301. const trim = histogram.settings.trimEdges;
  302. for (const prop in aggregations) {
  303. const points = aggregations[prop];
  304. if (points.datapoints.length > trim * 2) {
  305. points.datapoints = points.datapoints.slice(trim, points.datapoints.length - trim);
  306. }
  307. }
  308. }
  309. }
  310. getErrorFromElasticResponse(response, err) {
  311. const result: any = {};
  312. result.data = JSON.stringify(err, null, 4);
  313. if (err.root_cause && err.root_cause.length > 0 && err.root_cause[0].reason) {
  314. result.message = err.root_cause[0].reason;
  315. } else {
  316. result.message = err.reason || 'Unkown elastic error response';
  317. }
  318. if (response.$$config) {
  319. result.config = response.$$config;
  320. }
  321. return result;
  322. }
  323. getTimeSeries() {
  324. const seriesList = [];
  325. for (let i = 0; i < this.response.responses.length; i++) {
  326. const response = this.response.responses[i];
  327. if (response.error) {
  328. throw this.getErrorFromElasticResponse(this.response, response.error);
  329. }
  330. if (response.hits && response.hits.hits.length > 0) {
  331. this.processHits(response.hits, seriesList);
  332. }
  333. if (response.aggregations) {
  334. const aggregations = response.aggregations;
  335. const target = this.targets[i];
  336. const tmpSeriesList = [];
  337. const table = new TableModel();
  338. this.processBuckets(aggregations, target, tmpSeriesList, table, {}, 0);
  339. this.trimDatapoints(tmpSeriesList, target);
  340. this.nameSeries(tmpSeriesList, target);
  341. for (let y = 0; y < tmpSeriesList.length; y++) {
  342. seriesList.push(tmpSeriesList[y]);
  343. }
  344. if (table.rows.length > 0) {
  345. seriesList.push(table);
  346. }
  347. }
  348. }
  349. return { data: seriesList };
  350. }
  351. getLogs(logMessageField?: string, logLevelField?: string): DataQueryResponse {
  352. const dataFrame: DataFrame[] = [];
  353. const docs: any[] = [];
  354. for (let n = 0; n < this.response.responses.length; n++) {
  355. const response = this.response.responses[n];
  356. if (response.error) {
  357. throw this.getErrorFromElasticResponse(this.response, response.error);
  358. }
  359. const hits = response.hits;
  360. let propNames: string[] = [];
  361. let propName, hit, doc, i;
  362. for (i = 0; i < hits.hits.length; i++) {
  363. hit = hits.hits[i];
  364. const flattened = hit._source ? flatten(hit._source, null) : {};
  365. doc = {};
  366. doc[this.targets[0].timeField] = null;
  367. doc = {
  368. ...doc,
  369. _id: hit._id,
  370. _type: hit._type,
  371. _index: hit._index,
  372. ...flattened,
  373. };
  374. // Note: the order of for...in is arbitrary amd implementation dependant
  375. // and should probably not be relied upon.
  376. for (propName in hit.fields) {
  377. if (propNames.indexOf(propName) === -1) {
  378. propNames.push(propName);
  379. }
  380. doc[propName] = hit.fields[propName];
  381. }
  382. for (propName in doc) {
  383. if (propNames.indexOf(propName) === -1) {
  384. propNames.push(propName);
  385. }
  386. }
  387. doc._source = { ...flattened };
  388. docs.push(doc);
  389. }
  390. if (docs.length > 0) {
  391. propNames = propNames.sort();
  392. const series: DataFrame = {
  393. fields: [
  394. {
  395. name: this.targets[0].timeField,
  396. type: FieldType.time,
  397. },
  398. ],
  399. rows: [],
  400. };
  401. if (logMessageField) {
  402. series.fields.push({
  403. name: logMessageField,
  404. type: FieldType.string,
  405. });
  406. } else {
  407. series.fields.push({
  408. name: '_source',
  409. type: FieldType.string,
  410. });
  411. }
  412. if (logLevelField) {
  413. series.fields.push({
  414. name: 'level',
  415. type: FieldType.string,
  416. });
  417. }
  418. for (const propName of propNames) {
  419. if (propName === this.targets[0].timeField || propName === '_source') {
  420. continue;
  421. }
  422. series.fields.push({
  423. name: propName,
  424. type: FieldType.string,
  425. });
  426. }
  427. for (const doc of docs) {
  428. const row: any[] = [];
  429. row.push(doc[this.targets[0].timeField][0]);
  430. if (logMessageField) {
  431. row.push(doc[logMessageField] || '');
  432. } else {
  433. row.push(JSON.stringify(doc._source, null, 2));
  434. }
  435. if (logLevelField) {
  436. row.push(doc[logLevelField] || '');
  437. }
  438. for (const propName of propNames) {
  439. if (doc.hasOwnProperty(propName)) {
  440. row.push(doc[propName]);
  441. } else {
  442. row.push(null);
  443. }
  444. }
  445. series.rows.push(row);
  446. }
  447. dataFrame.push(series);
  448. }
  449. if (response.aggregations) {
  450. const aggregations = response.aggregations;
  451. const target = this.targets[n];
  452. const tmpSeriesList = [];
  453. const table = new TableModel();
  454. this.processBuckets(aggregations, target, tmpSeriesList, table, {}, 0);
  455. this.trimDatapoints(tmpSeriesList, target);
  456. this.nameSeries(tmpSeriesList, target);
  457. for (let y = 0; y < tmpSeriesList.length; y++) {
  458. const series = toDataFrame(tmpSeriesList[y]);
  459. series.labels = {};
  460. dataFrame.push(series);
  461. }
  462. }
  463. }
  464. return { data: dataFrame };
  465. }
  466. }