datasource.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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.interval = datasource.jsonData.timeInterval;
  25. this.queryBuilder = new ElasticQueryBuilder({
  26. timeField: this.timeField
  27. });
  28. }
  29. ElasticDatasource.prototype._request = function(method, url, data) {
  30. var options = {
  31. url: this.url + "/" + url,
  32. method: method,
  33. data: data
  34. };
  35. if (this.basicAuth) {
  36. options.withCredentials = true;
  37. options.headers = {
  38. "Authorization": this.basicAuth
  39. };
  40. }
  41. return backendSrv.datasourceRequest(options);
  42. };
  43. ElasticDatasource.prototype._get = function(url) {
  44. return this._request('GET', this.indexPattern.getIndexForToday() + url)
  45. .then(function(results) {
  46. return results.data;
  47. });
  48. };
  49. ElasticDatasource.prototype._post = function(url, data) {
  50. return this._request('POST', url, data)
  51. .then(function(results) {
  52. return results.data;
  53. });
  54. };
  55. ElasticDatasource.prototype.annotationQuery = function(annotation, rangeUnparsed) {
  56. var range = {};
  57. var timeField = annotation.timeField || '@timestamp';
  58. var queryString = annotation.query || '*';
  59. var tagsField = annotation.tagsField || 'tags';
  60. var titleField = annotation.titleField || 'desc';
  61. var textField = annotation.textField || null;
  62. range[timeField]= {
  63. from: rangeUnparsed.from,
  64. to: rangeUnparsed.to,
  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. return this._request('POST', annotation.index + '/_search', data).then(function(results) {
  75. var list = [];
  76. var hits = results.data.hits.hits;
  77. var getFieldFromSource = function(source, fieldName) {
  78. if (!fieldName) { return; }
  79. var fieldNames = fieldName.split('.');
  80. var fieldValue = source;
  81. for (var i = 0; i < fieldNames.length; i++) {
  82. fieldValue = fieldValue[fieldNames[i]];
  83. if (!fieldValue) {
  84. console.log('could not find field in annotatation: ', fieldName);
  85. return '';
  86. }
  87. }
  88. if (_.isArray(fieldValue)) {
  89. fieldValue = fieldValue.join(', ');
  90. }
  91. return fieldValue;
  92. };
  93. for (var i = 0; i < hits.length; i++) {
  94. var source = hits[i]._source;
  95. var fields = hits[i].fields;
  96. var time = source[timeField];
  97. if (_.isString(fields[timeField]) || _.isNumber(fields[timeField])) {
  98. time = fields[timeField];
  99. }
  100. var event = {
  101. annotation: annotation,
  102. time: moment.utc(time).valueOf(),
  103. title: getFieldFromSource(source, titleField),
  104. tags: getFieldFromSource(source, tagsField),
  105. text: getFieldFromSource(source, textField)
  106. };
  107. list.push(event);
  108. }
  109. return list;
  110. });
  111. };
  112. ElasticDatasource.prototype.testDatasource = function() {
  113. return this._get('/_stats').then(function() {
  114. return { status: "success", message: "Data source is working", title: "Success" };
  115. }, function(err) {
  116. if (err.data && err.data.error) {
  117. return { status: "error", message: err.data.error, title: "Error" };
  118. } else {
  119. return { status: "error", message: err.status, title: "Error" };
  120. }
  121. });
  122. };
  123. ElasticDatasource.prototype.getQueryHeader = function(timeFrom, timeTo) {
  124. var header = {search_type: "count", "ignore_unavailable": true};
  125. header.index = this.indexPattern.getIndexList(timeFrom, timeTo);
  126. return angular.toJson(header);
  127. };
  128. ElasticDatasource.prototype.query = function(options) {
  129. var payload = "";
  130. var target;
  131. var sentTargets = [];
  132. var header = this.getQueryHeader(options.range.from, options.range.to);
  133. for (var i = 0; i < options.targets.length; i++) {
  134. target = options.targets[i];
  135. if (target.hide) {return;}
  136. var esQuery = angular.toJson(this.queryBuilder.build(target));
  137. var luceneQuery = angular.toJson(target.query || '*');
  138. // remove inner quotes
  139. luceneQuery = luceneQuery.substr(1, luceneQuery.length - 2);
  140. esQuery = esQuery.replace("$lucene_query", luceneQuery);
  141. payload += header + '\n' + esQuery + '\n';
  142. sentTargets.push(target);
  143. }
  144. payload = payload.replace(/\$interval/g, options.interval);
  145. payload = payload.replace(/\$timeFrom/g, options.range.from.valueOf());
  146. payload = payload.replace(/\$timeTo/g, options.range.to.valueOf());
  147. payload = templateSrv.replace(payload, options.scopedVars);
  148. return this._post('/_msearch?search_type=count', payload).then(function(res) {
  149. return new ElasticResponse(sentTargets, res).getTimeSeries();
  150. });
  151. };
  152. ElasticDatasource.prototype.getFields = function(query) {
  153. return this._get('/_mapping').then(function(res) {
  154. var fields = {};
  155. var typeMap = {
  156. 'float': 'number',
  157. 'double': 'number',
  158. 'integer': 'number',
  159. 'long': 'number',
  160. 'date': 'date',
  161. 'string': 'string',
  162. };
  163. for (var indexName in res) {
  164. var index = res[indexName];
  165. var mappings = index.mappings;
  166. if (!mappings) { continue; }
  167. for (var typeName in mappings) {
  168. var properties = mappings[typeName].properties;
  169. for (var field in properties) {
  170. var prop = properties[field];
  171. if (query.type && typeMap[prop.type] !== query.type) {
  172. continue;
  173. }
  174. if (prop.type && field[0] !== '_') {
  175. fields[field] = {text: field, type: prop.type};
  176. }
  177. }
  178. }
  179. }
  180. // transform to array
  181. return _.map(fields, function(value) {
  182. return value;
  183. });
  184. });
  185. };
  186. ElasticDatasource.prototype.getTerms = function(queryDef) {
  187. var range = timeSrv.timeRange();
  188. var header = this.getQueryHeader(range.from, range.to);
  189. var esQuery = angular.toJson(this.queryBuilder.getTermsQuery(queryDef));
  190. esQuery = esQuery.replace("$lucene_query", queryDef.query || '*');
  191. esQuery = esQuery.replace(/\$timeFrom/g, range.from.valueOf());
  192. esQuery = esQuery.replace(/\$timeTo/g, range.to.valueOf());
  193. esQuery = header + '\n' + esQuery + '\n';
  194. return this._post('/_msearch?search_type=count', esQuery).then(function(res) {
  195. var buckets = res.responses[0].aggregations["1"].buckets;
  196. return _.map(buckets, function(bucket) {
  197. return {text: bucket.key, value: bucket.key};
  198. });
  199. });
  200. };
  201. ElasticDatasource.prototype.metricFindQuery = function(query) {
  202. query = templateSrv.replace(query);
  203. query = angular.fromJson(query);
  204. if (!query) {
  205. return $q.when([]);
  206. }
  207. if (query.find === 'fields') {
  208. return this.getFields(query);
  209. }
  210. if (query.find === 'terms') {
  211. return this.getTerms(query);
  212. }
  213. };
  214. ElasticDatasource.prototype.getDashboard = function(id) {
  215. return this._get('/dashboard/' + id)
  216. .then(function(result) {
  217. return angular.fromJson(result._source.dashboard);
  218. });
  219. };
  220. ElasticDatasource.prototype.searchDashboards = function() {
  221. var query = {
  222. query: { query_string: { query: '*' } },
  223. size: 10000,
  224. sort: ["_uid"],
  225. };
  226. return this._post(this.index + '/dashboard/_search', query)
  227. .then(function(results) {
  228. if(_.isUndefined(results.hits)) {
  229. return { dashboards: [], tags: [] };
  230. }
  231. var resultsHits = results.hits.hits;
  232. var displayHits = { dashboards: [] };
  233. for (var i = 0, len = resultsHits.length; i < len; i++) {
  234. var hit = resultsHits[i];
  235. displayHits.dashboards.push({
  236. id: hit._id,
  237. title: hit._source.title,
  238. tags: hit._source.tags
  239. });
  240. }
  241. return displayHits;
  242. });
  243. };
  244. return ElasticDatasource;
  245. });
  246. });