datasource.js 5.9 KB

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