datasource.js 6.5 KB

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