datasource.js 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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 result = data.results[i];
  49. if (!result || !result.series) { continue; }
  50. var alias = (options.targets[i] || {}).alias;
  51. if (alias) {
  52. alias = templateSrv.replace(alias, options.scopedVars);
  53. }
  54. var targetSeries = new InfluxSeries({ series: data.results[i].series, alias: alias }).getTimeSeries();
  55. for (y = 0; y < targetSeries.length; y++) {
  56. seriesList.push(targetSeries[y]);
  57. }
  58. }
  59. return { data: seriesList };
  60. });
  61. };
  62. InfluxDatasource.prototype.annotationQuery = function(annotation, rangeUnparsed) {
  63. var timeFilter = getTimeFilter({ range: rangeUnparsed });
  64. var query = annotation.query.replace('$timeFilter', timeFilter);
  65. query = templateSrv.replace(query);
  66. return this._seriesQuery(query).then(function(data) {
  67. if (!data || !data.results || !data.results[0]) {
  68. throw { message: 'No results in response from InfluxDB' };
  69. }
  70. return new InfluxSeries({ series: data.results[0].series, annotation: annotation }).getAnnotations();
  71. });
  72. };
  73. InfluxDatasource.prototype.metricFindQuery = function (query) {
  74. var interpolated;
  75. try {
  76. interpolated = templateSrv.replace(query);
  77. }
  78. catch (err) {
  79. return $q.reject(err);
  80. }
  81. return this._seriesQuery(interpolated).then(function (results) {
  82. if (!results || results.results.length === 0) { return []; }
  83. var influxResults = results.results[0];
  84. if (!influxResults.series) {
  85. return [];
  86. }
  87. var series = influxResults.series[0];
  88. if (query.indexOf('SHOW MEASUREMENTS') === 0) {
  89. return _.map(series.values, function(value) { return { text: value[0], expandable: true }; });
  90. }
  91. var flattenedValues = _.flatten(series.values);
  92. return _.map(flattenedValues, function(value) { return { text: value, expandable: true }; });
  93. });
  94. };
  95. function retry(deferred, callback, delay) {
  96. return callback().then(undefined, function(reason) {
  97. if (reason.status !== 0 || reason.status >= 300) {
  98. if (reason.data && reason.data.error) {
  99. reason.message = 'InfluxDB Error Response: ' + reason.data.error;
  100. }
  101. else {
  102. reason.message = 'InfluxDB Error: ' + reason.message;
  103. }
  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', '/query', {q: query, epoch: 'ms'});
  115. };
  116. InfluxDatasource.prototype.testDatasource = function() {
  117. return this.metricFindQuery('SHOW MEASUREMENTS LIMIT 1').then(function () {
  118. return { status: "success", message: "Data source is working", title: "Success" };
  119. });
  120. };
  121. InfluxDatasource.prototype._influxRequest = function(method, url, data) {
  122. var self = this;
  123. var deferred = $q.defer();
  124. retry(deferred, function() {
  125. var currentUrl = self.urls.shift();
  126. self.urls.push(currentUrl);
  127. var params = {
  128. u: self.username,
  129. p: self.password,
  130. };
  131. if (self.database) {
  132. params.db = self.database;
  133. }
  134. if (method === 'GET') {
  135. _.extend(params, data);
  136. data = null;
  137. }
  138. var options = {
  139. method: method,
  140. url: currentUrl + url,
  141. params: params,
  142. data: data,
  143. precision: "ms",
  144. inspect: { type: 'influxdb' },
  145. };
  146. options.headers = options.headers || {};
  147. if (self.basicAuth) {
  148. options.headers.Authorization = self.basicAuth;
  149. }
  150. return $http(options).success(function (data) {
  151. deferred.resolve(data);
  152. });
  153. }, 10);
  154. return deferred.promise;
  155. };
  156. function getTimeFilter(options) {
  157. var from = getInfluxTime(options.range.from);
  158. var until = getInfluxTime(options.range.to);
  159. var fromIsAbsolute = from[from.length-1] === 's';
  160. if (until === 'now()' && !fromIsAbsolute) {
  161. return 'time > ' + from;
  162. }
  163. return 'time > ' + from + ' and time < ' + until;
  164. }
  165. function getInfluxTime(date) {
  166. if (_.isString(date)) {
  167. return date.replace('now', 'now()').replace('-', ' - ');
  168. }
  169. return to_utc_epoch_seconds(date);
  170. }
  171. function to_utc_epoch_seconds(date) {
  172. return (date.getTime() / 1000).toFixed(0) + 's';
  173. }
  174. return InfluxDatasource;
  175. });
  176. });