datasource.js 9.3 KB

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