datasource.js 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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. for (var i = 0; i < options.targets.length; i++) {
  141. target = options.targets[i];
  142. if (target.hide) {continue;}
  143. var queryObj = this.queryBuilder.build(target);
  144. var esQuery = angular.toJson(queryObj);
  145. var luceneQuery = angular.toJson(target.query || '*');
  146. // remove inner quotes
  147. luceneQuery = luceneQuery.substr(1, luceneQuery.length - 2);
  148. esQuery = esQuery.replace("$lucene_query", luceneQuery);
  149. var searchType = queryObj.size === 0 ? 'count' : 'query_then_fetch';
  150. var header = this.getQueryHeader(searchType, options.range.from, options.range.to);
  151. payload += header + '\n';
  152. payload += esQuery + '\n';
  153. sentTargets.push(target);
  154. }
  155. payload = payload.replace(/\$interval/g, options.interval);
  156. payload = payload.replace(/\$timeFrom/g, options.range.from.valueOf());
  157. payload = payload.replace(/\$timeTo/g, options.range.to.valueOf());
  158. payload = templateSrv.replace(payload, options.scopedVars);
  159. return this._post('/_msearch', payload).then(function(res) {
  160. return new ElasticResponse(sentTargets, res).getTimeSeries();
  161. });
  162. };
  163. ElasticDatasource.prototype.getFields = function(query) {
  164. return this._get('/_mapping').then(function(res) {
  165. var fields = {};
  166. var typeMap = {
  167. 'float': 'number',
  168. 'double': 'number',
  169. 'integer': 'number',
  170. 'long': 'number',
  171. 'date': 'date',
  172. 'string': 'string',
  173. };
  174. for (var indexName in res) {
  175. var index = res[indexName];
  176. var mappings = index.mappings;
  177. if (!mappings) { continue; }
  178. for (var typeName in mappings) {
  179. var properties = mappings[typeName].properties;
  180. for (var field in properties) {
  181. var prop = properties[field];
  182. if (query.type && typeMap[prop.type] !== query.type) {
  183. continue;
  184. }
  185. if (prop.type && field[0] !== '_') {
  186. fields[field] = {text: field, type: prop.type};
  187. }
  188. }
  189. }
  190. }
  191. // transform to array
  192. return _.map(fields, function(value) {
  193. return value;
  194. });
  195. });
  196. };
  197. ElasticDatasource.prototype.getTerms = function(queryDef) {
  198. var range = timeSrv.timeRange();
  199. var header = this.getQueryHeader('count', range.from, range.to);
  200. var esQuery = angular.toJson(this.queryBuilder.getTermsQuery(queryDef));
  201. esQuery = esQuery.replace("$lucene_query", queryDef.query || '*');
  202. esQuery = esQuery.replace(/\$timeFrom/g, range.from.valueOf());
  203. esQuery = esQuery.replace(/\$timeTo/g, range.to.valueOf());
  204. esQuery = header + '\n' + esQuery + '\n';
  205. return this._post('/_msearch?search_type=count', esQuery).then(function(res) {
  206. var buckets = res.responses[0].aggregations["1"].buckets;
  207. return _.map(buckets, function(bucket) {
  208. return {text: bucket.key, value: bucket.key};
  209. });
  210. });
  211. };
  212. ElasticDatasource.prototype.metricFindQuery = function(query) {
  213. query = templateSrv.replace(query);
  214. query = angular.fromJson(query);
  215. if (!query) {
  216. return $q.when([]);
  217. }
  218. if (query.find === 'fields') {
  219. return this.getFields(query);
  220. }
  221. if (query.find === 'terms') {
  222. return this.getTerms(query);
  223. }
  224. };
  225. ElasticDatasource.prototype.getDashboard = function(id) {
  226. return this._get('/dashboard/' + id)
  227. .then(function(result) {
  228. return angular.fromJson(result._source.dashboard);
  229. });
  230. };
  231. ElasticDatasource.prototype.searchDashboards = function() {
  232. var query = {
  233. query: { query_string: { query: '*' } },
  234. size: 10000,
  235. sort: ["_uid"],
  236. };
  237. return this._post(this.index + '/dashboard/_search', query)
  238. .then(function(results) {
  239. if(_.isUndefined(results.hits)) {
  240. return { dashboards: [], tags: [] };
  241. }
  242. var resultsHits = results.hits.hits;
  243. var displayHits = { dashboards: [] };
  244. for (var i = 0, len = resultsHits.length; i < len; i++) {
  245. var hit = resultsHits[i];
  246. displayHits.dashboards.push({
  247. id: hit._id,
  248. title: hit._source.title,
  249. tags: hit._source.tags
  250. });
  251. }
  252. return displayHits;
  253. });
  254. };
  255. return ElasticDatasource;
  256. });
  257. });