datasource.ts 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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(";");
  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, null, 'regex');
  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. serializeParams(params) {
  112. if (!params) { return '';}
  113. return _.reduce(params, (memo, value, key) => {
  114. if (value === null || value === undefined) { return memo; }
  115. memo.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
  116. return memo;
  117. }, []).join("&");
  118. }
  119. testDatasource() {
  120. return this.metricFindQuery('SHOW MEASUREMENTS LIMIT 1').then(() => {
  121. return { status: "success", message: "Data source is working", title: "Success" };
  122. });
  123. }
  124. _influxRequest(method, url, data) {
  125. var self = this;
  126. var currentUrl = self.urls.shift();
  127. self.urls.push(currentUrl);
  128. var params: any = {
  129. u: self.username,
  130. p: self.password,
  131. };
  132. if (self.database) {
  133. params.db = self.database;
  134. }
  135. if (method === 'GET') {
  136. _.extend(params, data);
  137. data = null;
  138. }
  139. var options: any = {
  140. method: method,
  141. url: currentUrl + url,
  142. params: params,
  143. data: data,
  144. precision: "ms",
  145. inspect: { type: 'influxdb' },
  146. paramSerializer: this.serializeParams,
  147. };
  148. options.headers = options.headers || {};
  149. if (self.basicAuth) {
  150. options.headers.Authorization = self.basicAuth;
  151. }
  152. return this.backendSrv.datasourceRequest(options).then(result => {
  153. return result.data;
  154. }, function(err) {
  155. if (err.status !== 0 || err.status >= 300) {
  156. if (err.data && err.data.error) {
  157. throw { message: 'InfluxDB Error Response: ' + err.data.error, data: err.data, config: err.config };
  158. } else {
  159. throw { message: 'InfluxDB Error: ' + err.message, data: err.data, config: err.config };
  160. }
  161. }
  162. });
  163. };
  164. getTimeFilter(options) {
  165. var from = this.getInfluxTime(options.rangeRaw.from, false);
  166. var until = this.getInfluxTime(options.rangeRaw.to, true);
  167. var fromIsAbsolute = from[from.length-1] === 's';
  168. if (until === 'now()' && !fromIsAbsolute) {
  169. return 'time > ' + from;
  170. }
  171. return 'time > ' + from + ' and time < ' + until;
  172. }
  173. getInfluxTime(date, roundUp) {
  174. if (_.isString(date)) {
  175. if (date === 'now') {
  176. return 'now()';
  177. }
  178. var parts = /^now-(\d+)([d|h|m|s])$/.exec(date);
  179. if (parts) {
  180. var amount = parseInt(parts[1]);
  181. var unit = parts[2];
  182. return 'now() - ' + amount + unit;
  183. }
  184. date = dateMath.parse(date, roundUp);
  185. }
  186. return (date.valueOf() / 1000).toFixed(0) + 's';
  187. }
  188. }