datasource.ts 6.1 KB

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