datasource.ts 6.5 KB

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