datasource.js 6.0 KB

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