datasource.js 9.9 KB

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