datasource.js 9.9 KB

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