datasource.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. define([
  2. 'angular',
  3. 'lodash',
  4. 'app/core/utils/datemath',
  5. './influx_series',
  6. './influx_query',
  7. './directives',
  8. './query_ctrl',
  9. ],
  10. function (angular, _, dateMath, InfluxSeries, InfluxQuery) {
  11. 'use strict';
  12. var module = angular.module('grafana.services');
  13. module.factory('InfluxDatasource', function($q, backendSrv, 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 queryTargets = [];
  30. var i, y;
  31. var allQueries = _.map(options.targets, function(target) {
  32. if (target.hide) { return []; }
  33. queryTargets.push(target);
  34. // build query
  35. var queryModel = new InfluxQuery(target);
  36. var query = queryModel.render();
  37. console.log(query);
  38. query = query.replace(/\$interval/g, (target.interval || options.interval));
  39. return query;
  40. }).join("\n");
  41. // replace grafana variables
  42. allQueries = allQueries.replace(/\$timeFilter/g, timeFilter);
  43. // replace templated variables
  44. allQueries = templateSrv.replace(allQueries, options.scopedVars);
  45. return this._seriesQuery(allQueries).then(function(data) {
  46. if (!data || !data.results) {
  47. return [];
  48. }
  49. var seriesList = [];
  50. for (i = 0; i < data.results.length; i++) {
  51. var result = data.results[i];
  52. if (!result || !result.series) { continue; }
  53. var alias = (queryTargets[i] || {}).alias;
  54. if (alias) {
  55. alias = templateSrv.replace(alias, options.scopedVars);
  56. }
  57. var targetSeries = new InfluxSeries({ series: data.results[i].series, alias: alias }).getTimeSeries();
  58. for (y = 0; y < targetSeries.length; y++) {
  59. seriesList.push(targetSeries[y]);
  60. }
  61. }
  62. return { data: seriesList };
  63. });
  64. };
  65. InfluxDatasource.prototype.annotationQuery = function(options) {
  66. var timeFilter = getTimeFilter({rangeRaw: options.rangeRaw});
  67. var query = options.annotation.query.replace('$timeFilter', timeFilter);
  68. query = templateSrv.replace(query);
  69. return this._seriesQuery(query).then(function(data) {
  70. if (!data || !data.results || !data.results[0]) {
  71. throw { message: 'No results in response from InfluxDB' };
  72. }
  73. return new InfluxSeries({series: data.results[0].series, annotation: options.annotation}).getAnnotations();
  74. });
  75. };
  76. InfluxDatasource.prototype.metricFindQuery = function (query) {
  77. var interpolated;
  78. try {
  79. interpolated = templateSrv.replace(query);
  80. }
  81. catch (err) {
  82. return $q.reject(err);
  83. }
  84. return this._seriesQuery(interpolated).then(function (results) {
  85. if (!results || results.results.length === 0) { return []; }
  86. var influxResults = results.results[0];
  87. if (!influxResults.series) {
  88. return [];
  89. }
  90. var series = influxResults.series[0];
  91. if (query.indexOf('SHOW MEASUREMENTS') === 0) {
  92. return _.map(series.values, function(value) { return { text: value[0], expandable: true }; });
  93. }
  94. var flattenedValues = _.flatten(series.values);
  95. return _.map(flattenedValues, function(value) { return { text: value, expandable: true }; });
  96. });
  97. };
  98. InfluxDatasource.prototype._seriesQuery = function(query) {
  99. return this._influxRequest('GET', '/query', {q: query, epoch: 'ms'});
  100. };
  101. InfluxDatasource.prototype.testDatasource = function() {
  102. return this.metricFindQuery('SHOW MEASUREMENTS LIMIT 1').then(function () {
  103. return { status: "success", message: "Data source is working", title: "Success" };
  104. });
  105. };
  106. InfluxDatasource.prototype._influxRequest = function(method, url, data) {
  107. var self = this;
  108. var currentUrl = self.urls.shift();
  109. self.urls.push(currentUrl);
  110. var params = {
  111. u: self.username,
  112. p: self.password,
  113. };
  114. if (self.database) {
  115. params.db = self.database;
  116. }
  117. if (method === 'GET') {
  118. _.extend(params, data);
  119. data = null;
  120. }
  121. var options = {
  122. method: method,
  123. url: currentUrl + url,
  124. params: params,
  125. data: data,
  126. precision: "ms",
  127. inspect: { type: 'influxdb' },
  128. };
  129. options.headers = options.headers || {};
  130. if (self.basicAuth) {
  131. options.headers.Authorization = self.basicAuth;
  132. }
  133. return backendSrv.datasourceRequest(options).then(function(result) {
  134. return result.data;
  135. }, function(err) {
  136. if (err.status !== 0 || err.status >= 300) {
  137. if (err.data && err.data.error) {
  138. throw { message: 'InfluxDB Error Response: ' + err.data.error, data: err.data, config: err.config };
  139. }
  140. else {
  141. throw { message: 'InfluxDB Error: ' + err.message, data: err.data, config: err.config };
  142. }
  143. }
  144. });
  145. };
  146. function getTimeFilter(options) {
  147. var from = getInfluxTime(options.rangeRaw.from, false);
  148. var until = getInfluxTime(options.rangeRaw.to, true);
  149. var fromIsAbsolute = from[from.length-1] === 's';
  150. if (until === 'now()' && !fromIsAbsolute) {
  151. return 'time > ' + from;
  152. }
  153. return 'time > ' + from + ' and time < ' + until;
  154. }
  155. function getInfluxTime(date, roundUp) {
  156. if (_.isString(date)) {
  157. if (date === 'now') {
  158. return 'now()';
  159. }
  160. var parts = /^now-(\d+)([d|h|m|s])$/.exec(date);
  161. if (parts) {
  162. var amount = parseInt(parts[1]);
  163. var unit = parts[2];
  164. return 'now() - ' + amount + unit;
  165. }
  166. date = dateMath.parse(date, roundUp);
  167. }
  168. return (date.valueOf() / 1000).toFixed(0) + 's';
  169. }
  170. return InfluxDatasource;
  171. });
  172. });