datasource.js 6.0 KB

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