datasource.js 6.1 KB

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