elastic_response.ts 16 KB

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