datasource.js 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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', function($q, $http, templateSrv) {
  14. function InfluxDatasource(datasource) {
  15. this.type = 'influxdb';
  16. this.urls = _.map(datasource.url.split(','), function(url) {
  17. return url.trim();
  18. });
  19. this.username = datasource.username;
  20. this.password = datasource.password;
  21. this.name = datasource.name;
  22. this.database = datasource.database;
  23. this.basicAuth = datasource.basicAuth;
  24. this.supportAnnotations = true;
  25. this.supportMetrics = true;
  26. }
  27. InfluxDatasource.prototype.query = function(options) {
  28. var timeFilter = getTimeFilter(options);
  29. var i, y;
  30. var allQueries = _.map(options.targets, function(target) {
  31. if (target.hide) { return []; }
  32. // build query
  33. var queryBuilder = new InfluxQueryBuilder(target);
  34. var query = queryBuilder.build();
  35. query = query.replace(/\$interval/g, (target.interval || options.interval));
  36. return query;
  37. }).join("\n");
  38. // replace grafana variables
  39. allQueries = allQueries.replace(/\$timeFilter/g, timeFilter);
  40. // replace templated variables
  41. allQueries = templateSrv.replace(allQueries, options.scopedVars);
  42. return this._seriesQuery(allQueries).then(function(data) {
  43. if (!data || !data.results || !data.results[0].series) {
  44. return [];
  45. }
  46. var seriesList = [];
  47. for (i = 0; i < data.results.length; i++) {
  48. var alias = (options.targets[i] || {}).alias;
  49. var targetSeries = new InfluxSeries({ series: data.results[i].series, alias: alias }).getTimeSeries();
  50. for (y = 0; y < targetSeries.length; y++) {
  51. seriesList.push(targetSeries[y]);
  52. }
  53. }
  54. return { data: seriesList };
  55. });
  56. };
  57. InfluxDatasource.prototype.annotationQuery = function(annotation, rangeUnparsed) {
  58. var timeFilter = getTimeFilter({ range: rangeUnparsed });
  59. var query = annotation.query.replace('$timeFilter', timeFilter);
  60. query = templateSrv.replace(query);
  61. return this._seriesQuery(query).then(function(data) {
  62. if (!data || !data.results || !data.results[0]) {
  63. throw { message: 'No results in response from InfluxDB' };
  64. }
  65. return new InfluxSeries({ series: data.results[0].series, annotation: annotation }).getAnnotations();
  66. });
  67. };
  68. InfluxDatasource.prototype.metricFindQuery = function (query) {
  69. var interpolated;
  70. try {
  71. interpolated = templateSrv.replace(query);
  72. }
  73. catch (err) {
  74. return $q.reject(err);
  75. }
  76. return this._seriesQuery(interpolated).then(function (results) {
  77. if (!results || results.results.length === 0) { return []; }
  78. var influxResults = results.results[0];
  79. if (!influxResults.series) {
  80. return [];
  81. }
  82. var series = influxResults.series[0];
  83. if (query.indexOf('SHOW MEASUREMENTS') === 0) {
  84. return _.map(series.values, function(value) { return { text: value[0], expandable: true }; });
  85. }
  86. var flattenedValues = _.flatten(series.values);
  87. return _.map(flattenedValues, function(value) { return { text: value, expandable: true }; });
  88. });
  89. };
  90. function retry(deferred, callback, delay) {
  91. return callback().then(undefined, function(reason) {
  92. if (reason.status !== 0 || reason.status >= 300) {
  93. if (reason.data && reason.data.error) {
  94. reason.message = 'InfluxDB Error Response: ' + reason.data.error;
  95. }
  96. else {
  97. reason.message = 'InfluxDB Error: ' + reason.message;
  98. }
  99. deferred.reject(reason);
  100. }
  101. else {
  102. setTimeout(function() {
  103. return retry(deferred, callback, Math.min(delay * 2, 30000));
  104. }, delay);
  105. }
  106. });
  107. }
  108. InfluxDatasource.prototype._seriesQuery = function(query) {
  109. return this._influxRequest('GET', '/query', {q: query, epoch: 'ms'});
  110. };
  111. InfluxDatasource.prototype.testDatasource = function() {
  112. return this.metricFindQuery('SHOW MEASUREMENTS LIMIT 1').then(function () {
  113. return { status: "success", message: "Data source is working", title: "Success" };
  114. });
  115. };
  116. InfluxDatasource.prototype._influxRequest = function(method, url, data) {
  117. var self = this;
  118. var deferred = $q.defer();
  119. retry(deferred, function() {
  120. var currentUrl = self.urls.shift();
  121. self.urls.push(currentUrl);
  122. var params = {
  123. u: self.username,
  124. p: self.password,
  125. };
  126. if (self.database) {
  127. params.db = self.database;
  128. }
  129. if (method === 'GET') {
  130. _.extend(params, data);
  131. data = null;
  132. }
  133. var options = {
  134. method: method,
  135. url: currentUrl + url,
  136. params: params,
  137. data: data,
  138. precision: "ms",
  139. inspect: { type: 'influxdb' },
  140. };
  141. options.headers = options.headers || {};
  142. if (self.basicAuth) {
  143. options.headers.Authorization = self.basicAuth;
  144. }
  145. return $http(options).success(function (data) {
  146. deferred.resolve(data);
  147. });
  148. }, 10);
  149. return deferred.promise;
  150. };
  151. function getTimeFilter(options) {
  152. var from = getInfluxTime(options.range.from);
  153. var until = getInfluxTime(options.range.to);
  154. var fromIsAbsolute = from[from.length-1] === 's';
  155. if (until === 'now()' && !fromIsAbsolute) {
  156. return 'time > ' + from;
  157. }
  158. return 'time > ' + from + ' and time < ' + until;
  159. }
  160. function getInfluxTime(date) {
  161. if (_.isString(date)) {
  162. return date.replace('now', 'now()').replace('-', ' - ');
  163. }
  164. return to_utc_epoch_seconds(date);
  165. }
  166. function to_utc_epoch_seconds(date) {
  167. return (date.getTime() / 1000).toFixed(0) + 's';
  168. }
  169. return InfluxDatasource;
  170. });
  171. });