datasource.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. define([
  2. 'angular',
  3. 'lodash',
  4. 'config',
  5. 'kbn',
  6. 'moment',
  7. './queryBuilder',
  8. './queryCtrl',
  9. './directives'
  10. ],
  11. function (angular, _, config, kbn, moment, ElasticQueryBuilder) {
  12. 'use strict';
  13. var module = angular.module('grafana.services');
  14. module.factory('ElasticDatasource', function($q, backendSrv, templateSrv) {
  15. function ElasticDatasource(datasource) {
  16. this.type = 'elasticsearch';
  17. this.basicAuth = datasource.basicAuth;
  18. this.url = datasource.url;
  19. this.name = datasource.name;
  20. this.index = datasource.index;
  21. this.searchMaxResults = config.search.max_results || 20;
  22. this.saveTemp = _.isUndefined(datasource.save_temp) ? true : datasource.save_temp;
  23. this.saveTempTTL = _.isUndefined(datasource.save_temp_ttl) ? '30d' : datasource.save_temp_ttl;
  24. }
  25. ElasticDatasource.prototype._request = function(method, url, index, data) {
  26. var options = {
  27. url: this.url + "/" + index + url,
  28. method: method,
  29. data: data
  30. };
  31. if (this.basicAuth) {
  32. options.withCredentials = true;
  33. options.headers = {
  34. "Authorization": this.basicAuth
  35. };
  36. }
  37. return backendSrv.datasourceRequest(options);
  38. };
  39. ElasticDatasource.prototype._get = function(url) {
  40. return this._request('GET', url, this.index)
  41. .then(function(results) {
  42. return results.data;
  43. });
  44. };
  45. ElasticDatasource.prototype._post = function(url, data) {
  46. return this._request('POST', url, this.index, data)
  47. .then(function(results) {
  48. return results.data;
  49. });
  50. };
  51. ElasticDatasource.prototype.annotationQuery = function(annotation, rangeUnparsed) {
  52. var range = {};
  53. var timeField = annotation.timeField || '@timestamp';
  54. var queryString = annotation.query || '*';
  55. var tagsField = annotation.tagsField || 'tags';
  56. var titleField = annotation.titleField || 'desc';
  57. var textField = annotation.textField || null;
  58. range[timeField]= {
  59. from: rangeUnparsed.from,
  60. to: rangeUnparsed.to,
  61. };
  62. var queryInterpolated = templateSrv.replace(queryString);
  63. var filter = { "bool": { "must": [{ "range": range }] } };
  64. var query = { "bool": { "should": [{ "query_string": { "query": queryInterpolated } }] } };
  65. var data = {
  66. "fields": [timeField, "_source"],
  67. "query" : { "filtered": { "query" : query, "filter": filter } },
  68. "size": 10000
  69. };
  70. return this._request('POST', '/_search', annotation.index, data).then(function(results) {
  71. var list = [];
  72. var hits = results.data.hits.hits;
  73. var getFieldFromSource = function(source, fieldName) {
  74. if (!fieldName) { return; }
  75. var fieldNames = fieldName.split('.');
  76. var fieldValue = source;
  77. for (var i = 0; i < fieldNames.length; i++) {
  78. fieldValue = fieldValue[fieldNames[i]];
  79. if (!fieldValue) {
  80. console.log('could not find field in annotatation: ', fieldName);
  81. return '';
  82. }
  83. }
  84. if (_.isArray(fieldValue)) {
  85. fieldValue = fieldValue.join(', ');
  86. }
  87. return fieldValue;
  88. };
  89. for (var i = 0; i < hits.length; i++) {
  90. var source = hits[i]._source;
  91. var fields = hits[i].fields;
  92. var time = source[timeField];
  93. if (_.isString(fields[timeField]) || _.isNumber(fields[timeField])) {
  94. time = fields[timeField];
  95. }
  96. var event = {
  97. annotation: annotation,
  98. time: moment.utc(time).valueOf(),
  99. title: getFieldFromSource(source, titleField),
  100. tags: getFieldFromSource(source, tagsField),
  101. text: getFieldFromSource(source, textField)
  102. };
  103. list.push(event);
  104. }
  105. return list;
  106. });
  107. };
  108. ElasticDatasource.prototype._getDashboardWithSlug = function(id) {
  109. return this._get('/dashboard/' + kbn.slugifyForUrl(id))
  110. .then(function(result) {
  111. return angular.fromJson(result._source.dashboard);
  112. }, function() {
  113. throw "Dashboard not found";
  114. });
  115. };
  116. ElasticDatasource.prototype.getDashboard = function(id, isTemp) {
  117. var url = '/dashboard/' + id;
  118. if (isTemp) { url = '/temp/' + id; }
  119. var self = this;
  120. return this._get(url)
  121. .then(function(result) {
  122. return angular.fromJson(result._source.dashboard);
  123. }, function(data) {
  124. if(data.status === 0) {
  125. throw "Could not contact Elasticsearch. Please ensure that Elasticsearch is reachable from your browser.";
  126. } else {
  127. // backward compatible fallback
  128. return self._getDashboardWithSlug(id);
  129. }
  130. });
  131. };
  132. ElasticDatasource.prototype.saveDashboard = function(dashboard) {
  133. var title = dashboard.title;
  134. var temp = dashboard.temp;
  135. if (temp) { delete dashboard.temp; }
  136. var data = {
  137. user: 'guest',
  138. group: 'guest',
  139. title: title,
  140. tags: dashboard.tags,
  141. dashboard: angular.toJson(dashboard)
  142. };
  143. if (temp) {
  144. return this._saveTempDashboard(data);
  145. }
  146. else {
  147. var id = encodeURIComponent(kbn.slugifyForUrl(title));
  148. var self = this;
  149. return this._request('PUT', '/dashboard/' + id, this.index, data)
  150. .then(function(results) {
  151. self._removeUnslugifiedDashboard(results, title, id);
  152. return { title: title, url: '/dashboard/db/' + id };
  153. }, function() {
  154. throw 'Failed to save to elasticsearch';
  155. });
  156. }
  157. };
  158. ElasticDatasource.prototype._removeUnslugifiedDashboard = function(saveResult, title, id) {
  159. if (saveResult.statusText !== 'Created') { return; }
  160. if (title === id) { return; }
  161. var self = this;
  162. this._get('/dashboard/' + title).then(function() {
  163. self.deleteDashboard(title);
  164. });
  165. };
  166. ElasticDatasource.prototype._saveTempDashboard = function(data) {
  167. return this._request('POST', '/temp/?ttl=' + this.saveTempTTL, this.index, data)
  168. .then(function(result) {
  169. var baseUrl = window.location.href.replace(window.location.hash,'');
  170. var url = baseUrl + "#dashboard/temp/" + result.data._id;
  171. return { title: data.title, url: url };
  172. }, function(err) {
  173. throw "Failed to save to temp dashboard to elasticsearch " + err.data;
  174. });
  175. };
  176. ElasticDatasource.prototype.deleteDashboard = function(id) {
  177. return this._request('DELETE', '/dashboard/' + id, this.index)
  178. .then(function(result) {
  179. return result.data._id;
  180. }, function(err) {
  181. throw err.data;
  182. });
  183. };
  184. ElasticDatasource.prototype.searchDashboards = function(queryString) {
  185. var endsInOpen = function(string, opener, closer) {
  186. var character;
  187. var count = 0;
  188. for (var i = 0, len = string.length; i < len; i++) {
  189. character = string[i];
  190. if (character === opener) {
  191. count++;
  192. } else if (character === closer) {
  193. count--;
  194. }
  195. }
  196. return count > 0;
  197. };
  198. var tagsOnly = queryString.indexOf('tags!:') === 0;
  199. if (tagsOnly) {
  200. var tagsQuery = queryString.substring(6, queryString.length);
  201. queryString = 'tags:' + tagsQuery + '*';
  202. }
  203. else {
  204. if (queryString.length === 0) {
  205. queryString = 'title:';
  206. }
  207. // make this a partial search if we're not in some reserved portion of the language, comments on conditionals, in order:
  208. // 1. ends in reserved character, boosting, boolean operator ( -foo)
  209. // 2. typing a reserved word like AND, OR, NOT
  210. // 3. open parens (groupiing)
  211. // 4. open " (term phrase)
  212. // 5. open [ (range)
  213. // 6. open { (range)
  214. // see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html#query-string-syntax
  215. if (!queryString.match(/(\*|\]|}|~|\)|"|^\d+|\s[\-+]\w+)$/) &&
  216. !queryString.match(/[A-Z]$/) &&
  217. !endsInOpen(queryString, '(', ')') &&
  218. !endsInOpen(queryString, '"', '"') &&
  219. !endsInOpen(queryString, '[', ']') && !endsInOpen(queryString, '[', '}') &&
  220. !endsInOpen(queryString, '{', ']') && !endsInOpen(queryString, '{', '}')
  221. ){
  222. queryString += '*';
  223. }
  224. }
  225. var query = {
  226. query: { query_string: { query: queryString } },
  227. facets: { tags: { terms: { field: "tags", order: "term", size: 50 } } },
  228. size: 10000,
  229. sort: ["_uid"],
  230. };
  231. return this._post('/dashboard/_search', query)
  232. .then(function(results) {
  233. if(_.isUndefined(results.hits)) {
  234. return { dashboards: [], tags: [] };
  235. }
  236. var resultsHits = results.hits.hits;
  237. var displayHits = { dashboards: [], tags: results.facets.tags.terms || [] };
  238. for (var i = 0, len = resultsHits.length; i < len; i++) {
  239. var hit = resultsHits[i];
  240. displayHits.dashboards.push({
  241. id: hit._id,
  242. title: hit._source.title,
  243. tags: hit._source.tags
  244. });
  245. }
  246. displayHits.tagsOnly = tagsOnly;
  247. return displayHits;
  248. });
  249. };
  250. ElasticDatasource.prototype.testDatasource = function() {
  251. var query = JSON.stringify();
  252. return this._post('/_search?search_type=count', query).then(function() {
  253. return { status: "success", message: "Data source is working", title: "Success" };
  254. });
  255. };
  256. ElasticDatasource.prototype.query = function(options) {
  257. var queryBuilder = new ElasticQueryBuilder;
  258. var query = queryBuilder.build(options.targets);
  259. query = query.replace(/\$interval/g, options.interval);
  260. query = query.replace(/\$rangeFrom/g, options.range.from);
  261. query = query.replace(/\$rangeTo/g, options.range.to);
  262. query = query.replace(/\$maxDataPoints/g, options.maxDataPoints);
  263. query = templateSrv.replace(query, options.scopedVars);
  264. return this._post('/_search?search_type=count', query).then(this._getTimeSeries);
  265. };
  266. ElasticDatasource.prototype._getTimeSeries = function(results) {
  267. var _aggregation2timeSeries = function(aggregation) {
  268. var datapoints = aggregation.date_histogram.buckets.map(function(entry) {
  269. return [entry.stats.avg, entry.key];
  270. });
  271. return { target: aggregation.key, datapoints: datapoints };
  272. };
  273. var data = [];
  274. if (results && results.aggregations) {
  275. for (var target in results.aggregations) {
  276. if (!results.aggregations.hasOwnProperty(target)) {
  277. continue;
  278. }
  279. if (results.aggregations[target].date_histogram && results.aggregations[target].date_histogram.buckets) {
  280. data.push(_aggregation2timeSeries(results.aggregations[target]));
  281. } else if (results.aggregations[target].terms && results.aggregations[target].terms.buckets) {
  282. [].push.apply(data, results.aggregations[target].terms.buckets.map(_aggregation2timeSeries));
  283. }
  284. }
  285. }
  286. return { data: data };
  287. };
  288. return ElasticDatasource;
  289. });
  290. });