datasource.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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.testDatasource = function() {
  106. return this.metricFindQuery('SHOW MEASUREMENTS LIMIT 1').then(function () {
  107. return { status: "success", message: "Data source is working", title: "Success" };
  108. });
  109. };
  110. InfluxDatasource.prototype._influxRequest = function(method, url, data) {
  111. var self = this;
  112. var deferred = $q.defer();
  113. retry(deferred, function() {
  114. var currentUrl = self.urls.shift();
  115. self.urls.push(currentUrl);
  116. var params = {
  117. u: self.username,
  118. p: self.password,
  119. };
  120. if (self.database) {
  121. params.db = self.database;
  122. }
  123. if (method === 'GET') {
  124. _.extend(params, data);
  125. data = null;
  126. }
  127. var options = {
  128. method: method,
  129. url: currentUrl + url,
  130. params: params,
  131. data: data,
  132. precision: "ms",
  133. inspect: { type: 'influxdb' },
  134. };
  135. options.headers = options.headers || {};
  136. if (self.basicAuth) {
  137. options.headers.Authorization = self.basicAuth;
  138. }
  139. return $http(options).success(function (data) {
  140. deferred.resolve(data);
  141. });
  142. }, 10);
  143. return deferred.promise;
  144. };
  145. function handleInfluxQueryResponse(alias, data) {
  146. if (!data || !data.results || !data.results[0].series) {
  147. return [];
  148. }
  149. return new InfluxSeries({ series: data.results[0].series, alias: alias }).getTimeSeries();
  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. });