es-datasource.js 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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.withCredentials = true;
  34. options.headers = {
  35. "Authorization": "Basic " + this.basicAuth
  36. };
  37. }
  38. return $http(options);
  39. };
  40. ElasticDatasource.prototype._get = function(url) {
  41. return this._request('GET', url, this.index)
  42. .then(function(results) {
  43. return results.data;
  44. });
  45. };
  46. ElasticDatasource.prototype._post = function(url, data) {
  47. return this._request('POST', url, this.index, data)
  48. .then(function(results) {
  49. return results.data;
  50. });
  51. };
  52. ElasticDatasource.prototype.annotationQuery = function(annotation, rangeUnparsed) {
  53. var range = {};
  54. var timeField = annotation.timeField || '@timestamp';
  55. var queryString = annotation.query || '*';
  56. var tagsField = annotation.tagsField || 'tags';
  57. var titleField = annotation.titleField || 'desc';
  58. var textField = annotation.textField || null;
  59. range[annotation.timeField]= {
  60. from: rangeUnparsed.from,
  61. to: rangeUnparsed.to,
  62. };
  63. var queryInterpolated = templateSrv.replace(queryString);
  64. var filter = { "bool": { "must": [{ "range": range }] } };
  65. var query = { "bool": { "should": [{ "query_string": { "query": queryInterpolated } }] } };
  66. var data = {
  67. "fields": [timeField, "_source"],
  68. "query" : { "filtered": { "query" : query, "filter": filter } },
  69. "size": 100
  70. };
  71. return this._request('POST', '/_search', annotation.index, data).then(function(results) {
  72. var list = [];
  73. var hits = results.data.hits.hits;
  74. var getFieldFromSource = function(source, fieldName) {
  75. if (!fieldName) { return; }
  76. var fieldNames = fieldName.split('.');
  77. var fieldValue = source;
  78. for (var i = 0; i < fieldNames.length; i++) {
  79. fieldValue = fieldValue[fieldNames[i]];
  80. if (!fieldValue) {
  81. console.log('could not find field in annotatation: ', fieldName);
  82. return '';
  83. }
  84. }
  85. if (_.isArray(fieldValue)) {
  86. fieldValue = fieldValue.join(', ');
  87. }
  88. return fieldValue;
  89. };
  90. for (var i = 0; i < hits.length; i++) {
  91. var source = hits[i]._source;
  92. var fields = hits[i].fields;
  93. var time = source[timeField];
  94. if (_.isString(fields[timeField]) || _.isNumber(fields[timeField])) {
  95. time = fields[timeField];
  96. }
  97. var event = {
  98. annotation: annotation,
  99. time: moment.utc(time).valueOf(),
  100. title: getFieldFromSource(source, titleField),
  101. tags: getFieldFromSource(source, tagsField),
  102. text: getFieldFromSource(source, textField)
  103. };
  104. list.push(event);
  105. }
  106. return list;
  107. });
  108. };
  109. ElasticDatasource.prototype._getDashboardWithSlug = function(id) {
  110. return this._get('/dashboard/' + kbn.slugifyForUrl(id))
  111. .then(function(result) {
  112. return angular.fromJson(result._source.dashboard);
  113. }, function() {
  114. throw "Dashboard not found";
  115. });
  116. };
  117. ElasticDatasource.prototype.getDashboard = function(id, isTemp) {
  118. var url = '/dashboard/' + id;
  119. if (isTemp) { url = '/temp/' + id; }
  120. var self = this;
  121. return this._get(url)
  122. .then(function(result) {
  123. return angular.fromJson(result._source.dashboard);
  124. }, function(data) {
  125. if(data.status === 0) {
  126. throw "Could not contact Elasticsearch. Please ensure that Elasticsearch is reachable from your browser.";
  127. } else {
  128. // backward compatible fallback
  129. return self._getDashboardWithSlug(id);
  130. }
  131. });
  132. };
  133. ElasticDatasource.prototype.saveDashboard = function(dashboard) {
  134. var title = dashboard.title;
  135. var temp = dashboard.temp;
  136. if (temp) { delete dashboard.temp; }
  137. var data = {
  138. user: 'guest',
  139. group: 'guest',
  140. title: title,
  141. tags: dashboard.tags,
  142. dashboard: angular.toJson(dashboard)
  143. };
  144. if (temp) {
  145. return this._saveTempDashboard(data);
  146. }
  147. else {
  148. var id = encodeURIComponent(kbn.slugifyForUrl(title));
  149. var self = this;
  150. return this._request('PUT', '/dashboard/' + id, this.index, data)
  151. .then(function(results) {
  152. self._removeUnslugifiedDashboard(results, title, id);
  153. return { title: title, url: '/dashboard/db/' + id };
  154. }, function() {
  155. throw 'Failed to save to elasticsearch';
  156. });
  157. }
  158. };
  159. ElasticDatasource.prototype._removeUnslugifiedDashboard = function(saveResult, title, id) {
  160. if (saveResult.statusText !== 'Created') { return; }
  161. if (title === id) { return; }
  162. var self = this;
  163. this._get('/dashboard/' + title).then(function() {
  164. self.deleteDashboard(title);
  165. });
  166. };
  167. ElasticDatasource.prototype._saveTempDashboard = function(data) {
  168. return this._request('POST', '/temp/?ttl=' + this.saveTempTTL, this.index, data)
  169. .then(function(result) {
  170. var baseUrl = window.location.href.replace(window.location.hash,'');
  171. var url = baseUrl + "#dashboard/temp/" + result.data._id;
  172. return { title: data.title, url: url };
  173. }, function(err) {
  174. throw "Failed to save to temp dashboard to elasticsearch " + err.data;
  175. });
  176. };
  177. ElasticDatasource.prototype.deleteDashboard = function(id) {
  178. return this._request('DELETE', '/dashboard/' + id, this.index)
  179. .then(function(result) {
  180. return result.data._id;
  181. }, function(err) {
  182. throw err.data;
  183. });
  184. };
  185. ElasticDatasource.prototype.searchDashboards = function(queryString) {
  186. var endsInOpen = function(string, opener, closer) {
  187. var character;
  188. var count = 0;
  189. for (var i=0; i<string.length; i++) {
  190. character = string[i];
  191. if (character === opener) {
  192. count++;
  193. } else if (character === closer) {
  194. count--;
  195. }
  196. }
  197. return count > 0;
  198. };
  199. var tagsOnly = queryString.indexOf('tags!:') === 0;
  200. if (tagsOnly) {
  201. var tagsQuery = queryString.substring(6, queryString.length);
  202. queryString = 'tags:' + tagsQuery + '*';
  203. }
  204. else {
  205. if (queryString.length === 0) {
  206. queryString = 'title:';
  207. }
  208. // make this a partial search if we're not in some reserved portion of the language, comments on conditionals, in order:
  209. // 1. ends in reserved character, boosting, boolean operator ( -foo)
  210. // 2. typing a reserved word like AND, OR, NOT
  211. // 3. open parens (groupiing)
  212. // 4. open " (term phrase)
  213. // 5. open [ (range)
  214. // 6. open { (range)
  215. // see http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html#query-string-syntax
  216. if (!queryString.match(/(\*|\]|}|~|\)|"|^\d+|\s[\-+]\w+)$/) &&
  217. !queryString.match(/[A-Z]$/) &&
  218. !endsInOpen(queryString, '(', ')') &&
  219. !endsInOpen(queryString, '"', '"') &&
  220. !endsInOpen(queryString, '[', ']') && !endsInOpen(queryString, '[', '}') &&
  221. !endsInOpen(queryString, '{', ']') && !endsInOpen(queryString, '{', '}')
  222. ){
  223. queryString += '*';
  224. }
  225. }
  226. var query = {
  227. query: { query_string: { query: queryString } },
  228. facets: { tags: { terms: { field: "tags", order: "term", size: 50 } } },
  229. size: this.searchMaxResults,
  230. sort: ["_uid"]
  231. };
  232. return this._post('/dashboard/_search', query)
  233. .then(function(results) {
  234. if(_.isUndefined(results.hits)) {
  235. return { dashboards: [], tags: [] };
  236. }
  237. var hits = { dashboards: [], tags: results.facets.tags.terms || [] };
  238. for (var i = 0; i < results.hits.hits.length; i++) {
  239. hits.dashboards.push({
  240. id: results.hits.hits[i]._id,
  241. title: results.hits.hits[i]._source.title,
  242. tags: results.hits.hits[i]._source.tags
  243. });
  244. }
  245. hits.tagsOnly = tagsOnly;
  246. return hits;
  247. });
  248. };
  249. return ElasticDatasource;
  250. });
  251. });