datasource.js 5.8 KB

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