datasource.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. define([
  2. 'angular',
  3. 'lodash',
  4. 'kbn',
  5. './influxSeries',
  6. './queryBuilder',
  7. './queryCtrl',
  8. './funcEditor',
  9. ],
  10. function (angular, _, kbn, InfluxSeries, InfluxQueryBuilder) {
  11. 'use strict';
  12. var module = angular.module('grafana.services');
  13. module.factory('InfluxDatasource_08', function($q, backendSrv, templateSrv) {
  14. function InfluxDatasource(datasource) {
  15. this.urls = _.map(datasource.url.split(','), function(url) {
  16. return url.trim();
  17. });
  18. this.username = datasource.username;
  19. this.password = datasource.password;
  20. this.name = datasource.name;
  21. this.basicAuth = datasource.basicAuth;
  22. }
  23. InfluxDatasource.prototype.query = function(options) {
  24. var timeFilter = getTimeFilter(options);
  25. var promises = _.map(options.targets, function(target) {
  26. if (target.hide || !((target.series && target.column) || target.query)) {
  27. return [];
  28. }
  29. // build query
  30. var queryBuilder = new InfluxQueryBuilder(target);
  31. var query = queryBuilder.build();
  32. // replace grafana variables
  33. query = query.replace('$timeFilter', timeFilter);
  34. query = query.replace(/\$interval/g, (target.interval || options.interval));
  35. // replace templated variables
  36. query = templateSrv.replace(query);
  37. var alias = target.alias ? templateSrv.replace(target.alias) : '';
  38. var handleResponse = _.partial(handleInfluxQueryResponse, alias, queryBuilder.groupByField);
  39. return this._seriesQuery(query).then(handleResponse);
  40. }, this);
  41. return $q.all(promises).then(function(results) {
  42. return { data: _.flatten(results) };
  43. });
  44. };
  45. InfluxDatasource.prototype.annotationQuery = function(annotation, rangeUnparsed) {
  46. var timeFilter = getTimeFilter({ range: rangeUnparsed });
  47. var query = annotation.query.replace('$timeFilter', timeFilter);
  48. query = templateSrv.replace(query);
  49. return this._seriesQuery(query).then(function(results) {
  50. return new InfluxSeries({ seriesList: results, annotation: annotation }).getAnnotations();
  51. });
  52. };
  53. InfluxDatasource.prototype.listColumns = function(seriesName) {
  54. seriesName = templateSrv.replace(seriesName);
  55. if(!seriesName.match('^/.*/') && !seriesName.match(/^merge\(.*\)/)) {
  56. seriesName = '"' + seriesName+ '"';
  57. }
  58. return this._seriesQuery('select * from ' + seriesName + ' limit 1').then(function(data) {
  59. if (!data) {
  60. return [];
  61. }
  62. return data[0].columns.map(function(item) {
  63. return /^\w+$/.test(item) ? item : ('"' + item + '"');
  64. });
  65. });
  66. };
  67. InfluxDatasource.prototype.listSeries = function(query) {
  68. // wrap in regex
  69. if (query && query.length > 0 && query[0] !== '/') {
  70. query = '/' + query + '/';
  71. }
  72. return this._seriesQuery('list series ' + query).then(function(data) {
  73. if (!data || data.length === 0) {
  74. return [];
  75. }
  76. return _.map(data[0].points, function(point) {
  77. return point[1];
  78. });
  79. });
  80. };
  81. InfluxDatasource.prototype.metricFindQuery = function (query) {
  82. var interpolated;
  83. try {
  84. interpolated = templateSrv.replace(query);
  85. }
  86. catch (err) {
  87. return $q.reject(err);
  88. }
  89. return this._seriesQuery(interpolated)
  90. .then(function (results) {
  91. if (!results || results.length === 0) { return []; }
  92. return _.map(results[0].points, function (metric) {
  93. return {
  94. text: metric[1],
  95. expandable: false
  96. };
  97. });
  98. });
  99. };
  100. function retry(deferred, callback, delay) {
  101. return callback().then(undefined, function(reason) {
  102. if (reason.status !== 0 || reason.status >= 300) {
  103. reason.message = 'InfluxDB Error: <br/>' + reason.data;
  104. deferred.reject(reason);
  105. }
  106. else {
  107. setTimeout(function() {
  108. return retry(deferred, callback, Math.min(delay * 2, 30000));
  109. }, delay);
  110. }
  111. });
  112. }
  113. InfluxDatasource.prototype._seriesQuery = function(query) {
  114. return this._influxRequest('GET', '/series', {
  115. q: query,
  116. });
  117. };
  118. InfluxDatasource.prototype._influxRequest = function(method, url, data) {
  119. var _this = this;
  120. var deferred = $q.defer();
  121. retry(deferred, function() {
  122. var currentUrl = _this.urls.shift();
  123. _this.urls.push(currentUrl);
  124. var params = {
  125. u: _this.username,
  126. p: _this.password,
  127. };
  128. if (method === 'GET') {
  129. _.extend(params, data);
  130. data = null;
  131. }
  132. var options = {
  133. method: method,
  134. url: currentUrl + url,
  135. params: params,
  136. data: data,
  137. inspect: { type: 'influxdb' },
  138. };
  139. options.headers = options.headers || {};
  140. if (_this.basicAuth) {
  141. options.headers.Authorization = 'Basic ' + _this.basicAuth;
  142. }
  143. return backendSrv.datasourceRequest(options).then(function(response) {
  144. deferred.resolve(response.data);
  145. });
  146. }, 10);
  147. return deferred.promise;
  148. };
  149. InfluxDatasource.prototype._getDashboardInternal = function(id, isTemp) {
  150. var queryString = 'select dashboard from "grafana.dashboard_' + btoa(id) + '"';
  151. if (isTemp) {
  152. queryString = 'select dashboard from "grafana.temp_dashboard_' + btoa(id) + '"';
  153. }
  154. return this._seriesQuery(queryString).then(function(results) {
  155. if (!results || !results.length) {
  156. return null;
  157. }
  158. var dashCol = _.indexOf(results[0].columns, 'dashboard');
  159. var dashJson = results[0].points[0][dashCol];
  160. return angular.fromJson(dashJson);
  161. }, function() {
  162. return null;
  163. });
  164. };
  165. InfluxDatasource.prototype.getDashboard = function(id, isTemp) {
  166. var self = this;
  167. return this._getDashboardInternal(id, isTemp).then(function(dashboard) {
  168. if (dashboard !== null) {
  169. return dashboard;
  170. }
  171. // backward compatible load for unslugified ids
  172. var slug = kbn.slugifyForUrl(id);
  173. if (slug !== id) {
  174. return self.getDashboard(slug, isTemp);
  175. }
  176. throw "Dashboard not found";
  177. }, function(err) {
  178. throw "Could not load dashboard, " + err.data;
  179. });
  180. };
  181. InfluxDatasource.prototype.deleteDashboard = function(id) {
  182. return this._seriesQuery('drop series "grafana.dashboard_' + btoa(id) + '"').then(function(results) {
  183. if (!results) {
  184. throw "Could not delete dashboard";
  185. }
  186. return id;
  187. }, function(err) {
  188. throw "Could not delete dashboard, " + err.data;
  189. });
  190. };
  191. InfluxDatasource.prototype.searchDashboards = function(queryString) {
  192. var influxQuery = 'select * from /grafana.dashboard_.*/ where ';
  193. var tagsOnly = queryString.indexOf('tags!:') === 0;
  194. if (tagsOnly) {
  195. var tagsQuery = queryString.substring(6, queryString.length);
  196. influxQuery = influxQuery + 'tags =~ /.*' + tagsQuery + '.*/i';
  197. }
  198. else {
  199. var titleOnly = queryString.indexOf('title:') === 0;
  200. if (titleOnly) {
  201. var titleQuery = queryString.substring(6, queryString.length);
  202. influxQuery = influxQuery + ' title =~ /.*' + titleQuery + '.*/i';
  203. }
  204. else {
  205. influxQuery = influxQuery + '(tags =~ /.*' + queryString + '.*/i or title =~ /.*' + queryString + '.*/i)';
  206. }
  207. }
  208. return this._seriesQuery(influxQuery).then(function(results) {
  209. var hits = { dashboards: [], tags: [], tagsOnly: false };
  210. if (!results || !results.length) {
  211. return hits;
  212. }
  213. for (var i = 0; i < results.length; i++) {
  214. var dashCol = _.indexOf(results[i].columns, 'title');
  215. var tagsCol = _.indexOf(results[i].columns, 'tags');
  216. var idCol = _.indexOf(results[i].columns, 'id');
  217. var hit = {
  218. id: results[i].points[0][dashCol],
  219. title: results[i].points[0][dashCol],
  220. tags: results[i].points[0][tagsCol].split(",")
  221. };
  222. if (idCol !== -1) {
  223. hit.id = results[i].points[0][idCol];
  224. }
  225. hit.tags = hit.tags[0] ? hit.tags : [];
  226. hits.dashboards.push(hit);
  227. }
  228. return hits;
  229. });
  230. };
  231. function handleInfluxQueryResponse(alias, groupByField, seriesList) {
  232. var influxSeries = new InfluxSeries({
  233. seriesList: seriesList,
  234. alias: alias,
  235. groupByField: groupByField
  236. });
  237. return influxSeries.getTimeSeries();
  238. }
  239. function getTimeFilter(options) {
  240. var from = getInfluxTime(options.range.from);
  241. var until = getInfluxTime(options.range.to);
  242. var fromIsAbsolute = from[from.length-1] === 's';
  243. if (until === 'now()' && !fromIsAbsolute) {
  244. return 'time > ' + from;
  245. }
  246. return 'time > ' + from + ' and time < ' + until;
  247. }
  248. function getInfluxTime(date) {
  249. if (_.isString(date)) {
  250. return date.replace('now', 'now()');
  251. }
  252. return to_utc_epoch_seconds(date);
  253. }
  254. function to_utc_epoch_seconds(date) {
  255. return (date.getTime() / 1000).toFixed(0) + 's';
  256. }
  257. return InfluxDatasource;
  258. });
  259. });