es-datasource.js 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. define([
  2. 'angular',
  3. 'lodash',
  4. 'config',
  5. 'kbn',
  6. 'moment'
  7. ],
  8. function (angular, _, config, kbn, moment) {
  9. 'use strict';
  10. var module = angular.module('grafana.services');
  11. module.factory('ElasticDatasource', function($q, $http, templateSrv) {
  12. function ElasticDatasource(datasource) {
  13. this.type = 'elastic';
  14. this.basicAuth = datasource.basicAuth;
  15. this.url = datasource.url;
  16. this.name = datasource.name;
  17. this.index = datasource.index;
  18. this.grafanaDB = datasource.grafanaDB;
  19. this.searchMaxResults = config.search.max_results || 20;
  20. this.saveTemp = _.isUndefined(datasource.save_temp) ? true : datasource.save_temp;
  21. this.saveTempTTL = _.isUndefined(datasource.save_temp_ttl) ? '30d' : datasource.save_temp_ttl;
  22. this.annotationEditorSrc = 'app/partials/elasticsearch/annotation_editor.html';
  23. this.supportAnnotations = true;
  24. this.supportMetrics = false;
  25. }
  26. ElasticDatasource.prototype._request = function(method, url, index, data) {
  27. var options = {
  28. url: this.url + "/" + index + url,
  29. method: method,
  30. data: data
  31. };
  32. if (this.basicAuth) {
  33. options.headers = {
  34. "Authorization": "Basic " + this.basicAuth
  35. };
  36. }
  37. return $http(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[annotation.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": 100
  69. };
  70. return this._request('POST', '/_search', annotation.index, data).then(function(results) {
  71. var list = [];
  72. var hits = results.data.hits.hits;
  73. for (var i = 0; i < hits.length; i++) {
  74. var source = hits[i]._source;
  75. var fields = hits[i].fields;
  76. var time = source[timeField];
  77. if (_.isString(fields[timeField]) || _.isNumber(fields[timeField])) {
  78. time = fields[timeField];
  79. }
  80. var event = {
  81. annotation: annotation,
  82. time: moment.utc(time).valueOf(),
  83. title: source[titleField],
  84. };
  85. if (source[tagsField]) {
  86. if (_.isArray(source[tagsField])) {
  87. event.tags = source[tagsField].join(', ');
  88. }
  89. else {
  90. event.tags = source[tagsField];
  91. }
  92. }
  93. if (textField && source[textField]) {
  94. event.text = source[textField];
  95. }
  96. list.push(event);
  97. }
  98. return list;
  99. });
  100. };
  101. ElasticDatasource.prototype._getDashboardWithSlug = function(id) {
  102. return this._get('/dashboard/' + kbn.slugifyForUrl(id))
  103. .then(function(result) {
  104. return angular.fromJson(result._source.dashboard);
  105. }, function() {
  106. throw "Dashboard not found";
  107. });
  108. };
  109. ElasticDatasource.prototype.getDashboard = function(id, isTemp) {
  110. var url = '/dashboard/' + id;
  111. if (isTemp) { url = '/temp/' + id; }
  112. var self = this;
  113. return this._get(url)
  114. .then(function(result) {
  115. return angular.fromJson(result._source.dashboard);
  116. }, function(data) {
  117. if(data.status === 0) {
  118. throw "Could not contact Elasticsearch. Please ensure that Elasticsearch is reachable from your browser.";
  119. } else {
  120. // backward compatible fallback
  121. return self._getDashboardWithSlug(id);
  122. }
  123. });
  124. };
  125. ElasticDatasource.prototype.saveDashboard = function(dashboard) {
  126. var title = dashboard.title;
  127. var temp = dashboard.temp;
  128. if (temp) { delete dashboard.temp; }
  129. var data = {
  130. user: 'guest',
  131. group: 'guest',
  132. title: title,
  133. tags: dashboard.tags,
  134. dashboard: angular.toJson(dashboard)
  135. };
  136. if (temp) {
  137. return this._saveTempDashboard(data);
  138. }
  139. else {
  140. var id = encodeURIComponent(kbn.slugifyForUrl(title));
  141. var self = this;
  142. return this._request('PUT', '/dashboard/' + id, this.index, data)
  143. .then(function(results) {
  144. self._removeUnslugifiedDashboard(results, title);
  145. return { title: title, url: '/dashboard/db/' + id };
  146. }, function(err) {
  147. throw 'Failed to save to elasticsearch ' + err.data;
  148. });
  149. }
  150. };
  151. ElasticDatasource.prototype._removeUnslugifiedDashboard = function(saveResult, title) {
  152. if (saveResult.statusText !== 'Created') { return; }
  153. var self = this;
  154. this._get('/dashboard/' + title).then(function() {
  155. self.deleteDashboard(title);
  156. });
  157. };
  158. ElasticDatasource.prototype._saveTempDashboard = function(data) {
  159. return this._request('POST', '/temp/?ttl=' + this.saveTempTTL, this.index, data)
  160. .then(function(result) {
  161. var baseUrl = window.location.href.replace(window.location.hash,'');
  162. var url = baseUrl + "#dashboard/temp/" + result.data._id;
  163. return { title: data.title, url: url };
  164. }, function(err) {
  165. throw "Failed to save to temp dashboard to elasticsearch " + err.data;
  166. });
  167. };
  168. ElasticDatasource.prototype.deleteDashboard = function(id) {
  169. return this._request('DELETE', '/dashboard/' + id, this.index)
  170. .then(function(result) {
  171. return result.data._id;
  172. }, function(err) {
  173. throw err.data;
  174. });
  175. };
  176. ElasticDatasource.prototype.searchDashboards = function(queryString) {
  177. var endsInOpen = function(string, opener, closer) {
  178. var character;
  179. var count = 0;
  180. for (var i=0; i<string.length; i++) {
  181. character = string[i];
  182. if (character == opener) {
  183. count++;
  184. } else if (character == closer) {
  185. count--;
  186. }
  187. }
  188. return count > 0;
  189. }
  190. var tagsOnly = queryString.indexOf('tags!:') === 0;
  191. if (tagsOnly) {
  192. var tagsQuery = queryString.substring(6, queryString.length);
  193. queryString = 'tags:' + tagsQuery + '*';
  194. }
  195. else {
  196. if (queryString.length === 0) {
  197. queryString = 'title:';
  198. }
  199. // make this a partial search if we're not in some reserved portion of the language, comments on conditionals, in order:
  200. // 1. ends in reserved character, boosting, boolean operator ( -foo)
  201. // 2. typing a reserved word like AND, OR, NOT
  202. // 3. open parens (groupiing)
  203. // 4. open " (term phrase)
  204. // 5. open [ (range)
  205. // 6. open { (range)
  206. // see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html#query-string-syntax
  207. if (!queryString.match(/(\*|\]|}|~|\)|"|^\d+|\s[\-+]\w+)$/) &&
  208. !queryString.match(/[A-Z]$/) &&
  209. !endsInOpen(queryString, '(', ')') &&
  210. !endsInOpen(queryString, '"', '"') &&
  211. !endsInOpen(queryString, '[', ']') && !endsInOpen(queryString, '[', '}') &&
  212. !endsInOpen(queryString, '{', ']') && !endsInOpen(queryString, '{', '}')
  213. ){
  214. queryString += '*';
  215. }
  216. }
  217. var query = {
  218. query: { query_string: { query: queryString } },
  219. facets: { tags: { terms: { field: "tags", order: "term", size: 50 } } },
  220. size: this.searchMaxResults,
  221. sort: ["_uid"]
  222. };
  223. return this._post('/dashboard/_search', query)
  224. .then(function(results) {
  225. if(_.isUndefined(results.hits)) {
  226. return { dashboards: [], tags: [] };
  227. }
  228. var hits = { dashboards: [], tags: results.facets.tags.terms || [] };
  229. for (var i = 0; i < results.hits.hits.length; i++) {
  230. hits.dashboards.push({
  231. id: results.hits.hits[i]._id,
  232. title: results.hits.hits[i]._source.title,
  233. tags: results.hits.hits[i]._source.tags
  234. });
  235. }
  236. hits.tagsOnly = tagsOnly;
  237. return hits;
  238. });
  239. };
  240. return ElasticDatasource;
  241. });
  242. });