datasource.ts 6.0 KB

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