datasource.js 6.5 KB

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