datasource.js 9.7 KB

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