datasource.js 9.3 KB

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