datasource.js 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. define([
  2. 'angular',
  3. 'lodash',
  4. 'moment',
  5. 'app/core/utils/kbn',
  6. './query_builder',
  7. './index_pattern',
  8. './elastic_response',
  9. './query_ctrl',
  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, timeSrv) {
  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(options) {
  55. var annotation = options.annotation;
  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. var range = {};
  62. range[timeField]= {
  63. from: options.range.from.valueOf(),
  64. to: options.range.to.valueOf(),
  65. };
  66. var queryInterpolated = templateSrv.replace(queryString);
  67. var filter = { "bool": { "must": [{ "range": range }] } };
  68. var query = { "bool": { "should": [{ "query_string": { "query": queryInterpolated } }] } };
  69. var data = {
  70. "fields": [timeField, "_source"],
  71. "query" : { "filtered": { "query" : query, "filter": filter } },
  72. "size": 10000
  73. };
  74. var header = {search_type: "query_then_fetch", "ignore_unavailable": true};
  75. // old elastic annotations had index specified on them
  76. if (annotation.index) {
  77. header.index = annotation.index;
  78. } else {
  79. header.index = this.indexPattern.getIndexList(options.range.from, options.range.to);
  80. }
  81. var payload = angular.toJson(header) + '\n' + angular.toJson(data) + '\n';
  82. return this._post('/_msearch', payload).then(function(res) {
  83. var list = [];
  84. var hits = res.responses[0].hits.hits;
  85. var getFieldFromSource = function(source, fieldName) {
  86. if (!fieldName) { return; }
  87. var fieldNames = fieldName.split('.');
  88. var fieldValue = source;
  89. for (var i = 0; i < fieldNames.length; i++) {
  90. fieldValue = fieldValue[fieldNames[i]];
  91. if (!fieldValue) {
  92. console.log('could not find field in annotatation: ', fieldName);
  93. return '';
  94. }
  95. }
  96. if (_.isArray(fieldValue)) {
  97. fieldValue = fieldValue.join(', ');
  98. }
  99. return fieldValue;
  100. };
  101. for (var i = 0; i < hits.length; i++) {
  102. var source = hits[i]._source;
  103. var fields = hits[i].fields;
  104. var time = source[timeField];
  105. if (_.isString(fields[timeField]) || _.isNumber(fields[timeField])) {
  106. time = fields[timeField];
  107. }
  108. var event = {
  109. annotation: annotation,
  110. time: moment.utc(time).valueOf(),
  111. title: getFieldFromSource(source, titleField),
  112. tags: getFieldFromSource(source, tagsField),
  113. text: getFieldFromSource(source, textField)
  114. };
  115. list.push(event);
  116. }
  117. return list;
  118. });
  119. };
  120. ElasticDatasource.prototype.testDatasource = function() {
  121. return this._get('/_stats').then(function() {
  122. return { status: "success", message: "Data source is working", title: "Success" };
  123. }, function(err) {
  124. if (err.data && err.data.error) {
  125. return { status: "error", message: err.data.error, title: "Error" };
  126. } else {
  127. return { status: "error", message: err.status, title: "Error" };
  128. }
  129. });
  130. };
  131. ElasticDatasource.prototype.getQueryHeader = function(searchType, timeFrom, timeTo) {
  132. var header = {search_type: searchType, "ignore_unavailable": true};
  133. header.index = this.indexPattern.getIndexList(timeFrom, timeTo);
  134. return angular.toJson(header);
  135. };
  136. ElasticDatasource.prototype.query = function(options) {
  137. var payload = "";
  138. var target;
  139. var sentTargets = [];
  140. var headerAdded = false;
  141. for (var i = 0; i < options.targets.length; i++) {
  142. target = options.targets[i];
  143. if (target.hide) {return;}
  144. var queryObj = this.queryBuilder.build(target);
  145. var esQuery = angular.toJson(queryObj);
  146. var luceneQuery = angular.toJson(target.query || '*');
  147. // remove inner quotes
  148. luceneQuery = luceneQuery.substr(1, luceneQuery.length - 2);
  149. esQuery = esQuery.replace("$lucene_query", luceneQuery);
  150. if (!headerAdded) {
  151. var searchType = queryObj.size === 0 ? 'count' : 'query_then_fetch';
  152. var header = this.getQueryHeader(searchType, options.range.from, options.range.to);
  153. payload += header + '\n';
  154. headerAdded = true;
  155. }
  156. payload += esQuery + '\n';
  157. sentTargets.push(target);
  158. }
  159. payload = payload.replace(/\$interval/g, options.interval);
  160. payload = payload.replace(/\$timeFrom/g, options.range.from.valueOf());
  161. payload = payload.replace(/\$timeTo/g, options.range.to.valueOf());
  162. payload = templateSrv.replace(payload, options.scopedVars);
  163. return this._post('/_msearch', payload).then(function(res) {
  164. return new ElasticResponse(sentTargets, res).getTimeSeries();
  165. });
  166. };
  167. ElasticDatasource.prototype.getFields = function(query) {
  168. return this._get('/_mapping').then(function(res) {
  169. var fields = {};
  170. var typeMap = {
  171. 'float': 'number',
  172. 'double': 'number',
  173. 'integer': 'number',
  174. 'long': 'number',
  175. 'date': 'date',
  176. 'string': 'string',
  177. };
  178. for (var indexName in res) {
  179. var index = res[indexName];
  180. var mappings = index.mappings;
  181. if (!mappings) { continue; }
  182. for (var typeName in mappings) {
  183. var properties = mappings[typeName].properties;
  184. for (var field in properties) {
  185. var prop = properties[field];
  186. if (query.type && typeMap[prop.type] !== query.type) {
  187. continue;
  188. }
  189. if (prop.type && field[0] !== '_') {
  190. fields[field] = {text: field, type: prop.type};
  191. }
  192. }
  193. }
  194. }
  195. // transform to array
  196. return _.map(fields, function(value) {
  197. return value;
  198. });
  199. });
  200. };
  201. ElasticDatasource.prototype.getTerms = function(queryDef) {
  202. var range = timeSrv.timeRange();
  203. var header = this.getQueryHeader('count', range.from, range.to);
  204. var esQuery = angular.toJson(this.queryBuilder.getTermsQuery(queryDef));
  205. esQuery = esQuery.replace("$lucene_query", queryDef.query || '*');
  206. esQuery = esQuery.replace(/\$timeFrom/g, range.from.valueOf());
  207. esQuery = esQuery.replace(/\$timeTo/g, range.to.valueOf());
  208. esQuery = header + '\n' + esQuery + '\n';
  209. return this._post('/_msearch?search_type=count', esQuery).then(function(res) {
  210. var buckets = res.responses[0].aggregations["1"].buckets;
  211. return _.map(buckets, function(bucket) {
  212. return {text: bucket.key, value: bucket.key};
  213. });
  214. });
  215. };
  216. ElasticDatasource.prototype.metricFindQuery = function(query) {
  217. query = templateSrv.replace(query);
  218. query = angular.fromJson(query);
  219. if (!query) {
  220. return $q.when([]);
  221. }
  222. if (query.find === 'fields') {
  223. return this.getFields(query);
  224. }
  225. if (query.find === 'terms') {
  226. return this.getTerms(query);
  227. }
  228. };
  229. ElasticDatasource.prototype.getDashboard = function(id) {
  230. return this._get('/dashboard/' + id)
  231. .then(function(result) {
  232. return angular.fromJson(result._source.dashboard);
  233. });
  234. };
  235. ElasticDatasource.prototype.searchDashboards = function() {
  236. var query = {
  237. query: { query_string: { query: '*' } },
  238. size: 10000,
  239. sort: ["_uid"],
  240. };
  241. return this._post(this.index + '/dashboard/_search', query)
  242. .then(function(results) {
  243. if(_.isUndefined(results.hits)) {
  244. return { dashboards: [], tags: [] };
  245. }
  246. var resultsHits = results.hits.hits;
  247. var displayHits = { dashboards: [] };
  248. for (var i = 0, len = resultsHits.length; i < len; i++) {
  249. var hit = resultsHits[i];
  250. displayHits.dashboards.push({
  251. id: hit._id,
  252. title: hit._source.title,
  253. tags: hit._source.tags
  254. });
  255. }
  256. return displayHits;
  257. });
  258. };
  259. return ElasticDatasource;
  260. });
  261. });