datasource.js 9.0 KB

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