datasource.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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. }, function(err) {
  109. var message, title;
  110. if (err.statusText) {
  111. message = err.statusText;
  112. title = "HTTP Error";
  113. } else {
  114. message = err;
  115. title = "Unknown error";
  116. }
  117. return { status: "error", message: message, title: title };
  118. });
  119. };
  120. InfluxDatasource.prototype._influxRequest = function(method, url, data) {
  121. var self = this;
  122. var deferred = $q.defer();
  123. retry(deferred, function() {
  124. var currentUrl = self.urls.shift();
  125. self.urls.push(currentUrl);
  126. var params = {
  127. u: self.username,
  128. p: self.password,
  129. };
  130. if (self.database) {
  131. params.db = self.database;
  132. }
  133. if (method === 'GET') {
  134. _.extend(params, data);
  135. data = null;
  136. }
  137. var options = {
  138. method: method,
  139. url: currentUrl + url,
  140. params: params,
  141. data: data,
  142. precision: "ms",
  143. inspect: { type: 'influxdb' },
  144. };
  145. options.headers = options.headers || {};
  146. if (self.basicAuth) {
  147. options.headers.Authorization = self.basicAuth;
  148. }
  149. return $http(options).success(function (data) {
  150. deferred.resolve(data);
  151. });
  152. }, 10);
  153. return deferred.promise;
  154. };
  155. function handleInfluxQueryResponse(alias, data) {
  156. if (!data || !data.results || !data.results[0].series) {
  157. return [];
  158. }
  159. return new InfluxSeries({ series: data.results[0].series, alias: alias }).getTimeSeries();
  160. }
  161. function getTimeFilter(options) {
  162. var from = getInfluxTime(options.range.from);
  163. var until = getInfluxTime(options.range.to);
  164. var fromIsAbsolute = from[from.length-1] === 's';
  165. if (until === 'now()' && !fromIsAbsolute) {
  166. return 'time > ' + from;
  167. }
  168. return 'time > ' + from + ' and time < ' + until;
  169. }
  170. function getInfluxTime(date) {
  171. if (_.isString(date)) {
  172. return date.replace('now', 'now()').replace('-', ' - ');
  173. }
  174. return to_utc_epoch_seconds(date);
  175. }
  176. function to_utc_epoch_seconds(date) {
  177. return (date.getTime() / 1000).toFixed(0) + 's';
  178. }
  179. return InfluxDatasource;
  180. });
  181. });