datasource.js 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. define([
  2. 'angular',
  3. 'lodash',
  4. 'moment',
  5. 'kbn',
  6. './queryBuilder',
  7. './indexPattern',
  8. './elasticResponse',
  9. './queryCtrl',
  10. './directives'
  11. ],
  12. function (angular, _, moment, kbn, ElasticQueryBuilder, IndexPattern, ElasticResponse) {
  13. 'use strict';
  14. var module = angular.module('grafana.services');
  15. module.factory('ElasticDatasource', function($q, backendSrv, templateSrv) {
  16. function ElasticDatasource(datasource) {
  17. this.type = 'elasticsearch';
  18. this.basicAuth = datasource.basicAuth;
  19. this.url = datasource.url;
  20. this.name = datasource.name;
  21. this.index = datasource.index;
  22. this.timeField = datasource.jsonData.timeField;
  23. this.indexPattern = new IndexPattern(datasource.index, datasource.jsonData.interval);
  24. this.queryBuilder = new ElasticQueryBuilder({
  25. timeField: this.timeField
  26. });
  27. }
  28. ElasticDatasource.prototype._request = function(method, url, data) {
  29. var options = {
  30. url: this.url + "/" + url,
  31. method: method,
  32. data: data
  33. };
  34. if (this.basicAuth) {
  35. options.withCredentials = true;
  36. options.headers = {
  37. "Authorization": this.basicAuth
  38. };
  39. }
  40. return backendSrv.datasourceRequest(options);
  41. };
  42. ElasticDatasource.prototype._get = function(url) {
  43. return this._request('GET', this.indexPattern.getIndexForToday() + url)
  44. .then(function(results) {
  45. return results.data;
  46. });
  47. };
  48. ElasticDatasource.prototype._post = function(url, data) {
  49. return this._request('POST', url, data)
  50. .then(function(results) {
  51. return results.data;
  52. });
  53. };
  54. ElasticDatasource.prototype.annotationQuery = function(annotation, rangeUnparsed) {
  55. var range = {};
  56. var timeField = annotation.timeField || '@timestamp';
  57. var queryString = annotation.query || '*';
  58. var tagsField = annotation.tagsField || 'tags';
  59. var titleField = annotation.titleField || 'desc';
  60. var textField = annotation.textField || null;
  61. range[timeField]= {
  62. from: rangeUnparsed.from,
  63. to: rangeUnparsed.to,
  64. };
  65. var queryInterpolated = templateSrv.replace(queryString);
  66. var filter = { "bool": { "must": [{ "range": range }] } };
  67. var query = { "bool": { "should": [{ "query_string": { "query": queryInterpolated } }] } };
  68. var data = {
  69. "fields": [timeField, "_source"],
  70. "query" : { "filtered": { "query" : query, "filter": filter } },
  71. "size": 10000
  72. };
  73. return this._request('POST', annotation.index + '/_search', data).then(function(results) {
  74. var list = [];
  75. var hits = results.data.hits.hits;
  76. var getFieldFromSource = function(source, fieldName) {
  77. if (!fieldName) { return; }
  78. var fieldNames = fieldName.split('.');
  79. var fieldValue = source;
  80. for (var i = 0; i < fieldNames.length; i++) {
  81. fieldValue = fieldValue[fieldNames[i]];
  82. if (!fieldValue) {
  83. console.log('could not find field in annotatation: ', fieldName);
  84. return '';
  85. }
  86. }
  87. if (_.isArray(fieldValue)) {
  88. fieldValue = fieldValue.join(', ');
  89. }
  90. return fieldValue;
  91. };
  92. for (var i = 0; i < hits.length; i++) {
  93. var source = hits[i]._source;
  94. var fields = hits[i].fields;
  95. var time = source[timeField];
  96. if (_.isString(fields[timeField]) || _.isNumber(fields[timeField])) {
  97. time = fields[timeField];
  98. }
  99. var event = {
  100. annotation: annotation,
  101. time: moment.utc(time).valueOf(),
  102. title: getFieldFromSource(source, titleField),
  103. tags: getFieldFromSource(source, tagsField),
  104. text: getFieldFromSource(source, textField)
  105. };
  106. list.push(event);
  107. }
  108. return list;
  109. });
  110. };
  111. ElasticDatasource.prototype.testDatasource = function() {
  112. return this._get('/_stats').then(function() {
  113. return { status: "success", message: "Data source is working", title: "Success" };
  114. }, function(err) {
  115. if (err.data && err.data.error) {
  116. return { status: "error", message: err.data.error, title: "Error" };
  117. } else {
  118. return { status: "error", message: err.status, title: "Error" };
  119. }
  120. });
  121. };
  122. ElasticDatasource.prototype.getQueryHeader = function(timeRange) {
  123. var header = {search_type: "count", "ignore_unavailable": true};
  124. var from = kbn.parseDate(timeRange.from);
  125. var to = kbn.parseDate(timeRange.to);
  126. header.index = this.indexPattern.getIndexList(from, to);
  127. return angular.toJson(header);
  128. };
  129. ElasticDatasource.prototype.query = function(options) {
  130. var payload = "";
  131. var target;
  132. var sentTargets = [];
  133. var header = this.getQueryHeader(options.range);
  134. var timeFrom = this.translateTime(options.range.from);
  135. var timeTo = this.translateTime(options.range.to);
  136. for (var i = 0; i < options.targets.length; i++) {
  137. target = options.targets[i];
  138. if (target.hide) {return;}
  139. var esQuery = this.queryBuilder.build(target, timeFrom, timeTo);
  140. payload += header + '\n';
  141. payload += angular.toJson(esQuery) + '\n';
  142. sentTargets.push(target);
  143. }
  144. payload = payload.replace(/\$interval/g, options.interval);
  145. payload = payload.replace(/\$timeFrom/g, this.translateTime(options.range.from));
  146. payload = payload.replace(/\$timeTo/g, this.translateTime(options.range.to));
  147. payload = payload.replace(/\$maxDataPoints/g, options.maxDataPoints);
  148. payload = templateSrv.replace(payload, options.scopedVars);
  149. return this._post('/_msearch?search_type=count', payload).then(function(res) {
  150. return new ElasticResponse(sentTargets, res).getTimeSeries();
  151. });
  152. };
  153. ElasticDatasource.prototype.translateTime = function(date) {
  154. if (_.isString(date)) {
  155. return date;
  156. }
  157. return date.getTime();
  158. };
  159. ElasticDatasource.prototype.metricFindQuery = function() {
  160. return this._get('/_mapping').then(function(res) {
  161. var fields = {};
  162. for (var indexName in res) {
  163. var index = res[indexName];
  164. var mappings = index.mappings;
  165. if (!mappings) { continue; }
  166. for (var typeName in mappings) {
  167. var properties = mappings[typeName].properties;
  168. for (var field in properties) {
  169. var prop = properties[field];
  170. if (prop.type && field[0] !== '_') {
  171. fields[field] = prop;
  172. }
  173. }
  174. }
  175. }
  176. fields = _.map(_.keys(fields), function(field) {
  177. return {text: field};
  178. });
  179. return fields;
  180. });
  181. };
  182. return ElasticDatasource;
  183. });
  184. });