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