datasource.ts 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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. import InfluxQueryBuilder from './query_builder';
  9. export default class InfluxDatasource {
  10. type: string;
  11. urls: any;
  12. username: string;
  13. password: string;
  14. name: string;
  15. database: any;
  16. basicAuth: any;
  17. withCredentials: any;
  18. interval: any;
  19. supportAnnotations: boolean;
  20. supportMetrics: boolean;
  21. responseParser: any;
  22. /** @ngInject */
  23. constructor(instanceSettings, private $q, private backendSrv, private templateSrv) {
  24. this.type = 'influxdb';
  25. this.urls = _.map(instanceSettings.url.split(','), function(url) {
  26. return url.trim();
  27. });
  28. this.username = instanceSettings.username;
  29. this.password = instanceSettings.password;
  30. this.name = instanceSettings.name;
  31. this.database = instanceSettings.database;
  32. this.basicAuth = instanceSettings.basicAuth;
  33. this.withCredentials = instanceSettings.withCredentials;
  34. this.interval = (instanceSettings.jsonData || {}).timeInterval;
  35. this.supportAnnotations = true;
  36. this.supportMetrics = true;
  37. this.responseParser = new ResponseParser();
  38. }
  39. query(options) {
  40. var timeFilter = this.getTimeFilter(options);
  41. var scopedVars = options.scopedVars ? _.cloneDeep(options.scopedVars) : {};
  42. var targets = _.cloneDeep(options.targets);
  43. var queryTargets = [];
  44. var queryModel;
  45. var i, y;
  46. var allQueries = _.map(targets, target => {
  47. if (target.hide) { return ""; }
  48. queryTargets.push(target);
  49. // build query
  50. scopedVars.interval = {value: target.interval || options.interval};
  51. queryModel = new InfluxQuery(target, this.templateSrv, scopedVars);
  52. return queryModel.render(true);
  53. }).reduce((acc, current) => {
  54. if (current !== "") {
  55. acc += ";" + current;
  56. }
  57. return acc;
  58. });
  59. if (allQueries === '') {
  60. return this.$q.when({data: []});
  61. }
  62. // add global adhoc filters to timeFilter
  63. var adhocFilters = this.templateSrv.getAdhocFilters(this.name);
  64. if (adhocFilters.length > 0 ) {
  65. timeFilter += ' AND ' + queryModel.renderAdhocFilters(adhocFilters);
  66. }
  67. // replace grafana variables
  68. scopedVars.timeFilter = {value: timeFilter};
  69. // replace templated variables
  70. allQueries = this.templateSrv.replace(allQueries, scopedVars);
  71. return this._seriesQuery(allQueries).then((data): any => {
  72. if (!data || !data.results) {
  73. return [];
  74. }
  75. var seriesList = [];
  76. for (i = 0; i < data.results.length; i++) {
  77. var result = data.results[i];
  78. if (!result || !result.series) { continue; }
  79. var target = queryTargets[i];
  80. var alias = target.alias;
  81. if (alias) {
  82. alias = this.templateSrv.replace(target.alias, options.scopedVars);
  83. }
  84. var influxSeries = new InfluxSeries({ series: data.results[i].series, alias: alias });
  85. switch (target.resultFormat) {
  86. case 'table': {
  87. seriesList.push(influxSeries.getTable());
  88. break;
  89. }
  90. default: {
  91. var timeSeries = influxSeries.getTimeSeries();
  92. for (y = 0; y < timeSeries.length; y++) {
  93. seriesList.push(timeSeries[y]);
  94. }
  95. break;
  96. }
  97. }
  98. }
  99. return {data: seriesList};
  100. });
  101. };
  102. annotationQuery(options) {
  103. if (!options.annotation.query) {
  104. return this.$q.reject({message: 'Query missing in annotation definition'});
  105. }
  106. var timeFilter = this.getTimeFilter({rangeRaw: options.rangeRaw});
  107. var query = options.annotation.query.replace('$timeFilter', timeFilter);
  108. query = this.templateSrv.replace(query, null, 'regex');
  109. return this._seriesQuery(query).then(data => {
  110. if (!data || !data.results || !data.results[0]) {
  111. throw { message: 'No results in response from InfluxDB' };
  112. }
  113. return new InfluxSeries({series: data.results[0].series, annotation: options.annotation}).getAnnotations();
  114. });
  115. };
  116. metricFindQuery(query) {
  117. var interpolated = this.templateSrv.replace(query, null, 'regex');
  118. return this._seriesQuery(interpolated)
  119. .then(_.curry(this.responseParser.parse)(query));
  120. }
  121. getTagKeys(options) {
  122. var queryBuilder = new InfluxQueryBuilder({measurement: '', tags: []}, this.database);
  123. var query = queryBuilder.buildExploreQuery('TAG_KEYS');
  124. return this.metricFindQuery(query);
  125. }
  126. getTagValues(options) {
  127. var queryBuilder = new InfluxQueryBuilder({measurement: '', tags: []}, this.database);
  128. var query = queryBuilder.buildExploreQuery('TAG_VALUES', options.key);
  129. return this.metricFindQuery(query);
  130. }
  131. _seriesQuery(query) {
  132. if (!query) { return this.$q.when({results: []}); }
  133. return this._influxRequest('GET', '/query', {q: query, epoch: 'ms'});
  134. }
  135. serializeParams(params) {
  136. if (!params) { return '';}
  137. return _.reduce(params, (memo, value, key) => {
  138. if (value === null || value === undefined) { return memo; }
  139. memo.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
  140. return memo;
  141. }, []).join("&");
  142. }
  143. testDatasource() {
  144. return this.metricFindQuery('SHOW MEASUREMENTS LIMIT 1').then(() => {
  145. return { status: "success", message: "Data source is working", title: "Success" };
  146. });
  147. }
  148. _influxRequest(method, url, data) {
  149. var self = this;
  150. var currentUrl = self.urls.shift();
  151. self.urls.push(currentUrl);
  152. var params: any = {
  153. u: self.username,
  154. p: self.password,
  155. };
  156. if (self.database) {
  157. params.db = self.database;
  158. }
  159. if (method === 'GET') {
  160. _.extend(params, data);
  161. data = null;
  162. }
  163. var options: any = {
  164. method: method,
  165. url: currentUrl + url,
  166. params: params,
  167. data: data,
  168. precision: "ms",
  169. inspect: { type: 'influxdb' },
  170. paramSerializer: this.serializeParams,
  171. };
  172. options.headers = options.headers || {};
  173. if (this.basicAuth || this.withCredentials) {
  174. options.withCredentials = true;
  175. }
  176. if (self.basicAuth) {
  177. options.headers.Authorization = self.basicAuth;
  178. }
  179. return this.backendSrv.datasourceRequest(options).then(result => {
  180. return result.data;
  181. }, function(err) {
  182. if (err.status !== 0 || err.status >= 300) {
  183. if (err.data && err.data.error) {
  184. throw { message: 'InfluxDB Error Response: ' + err.data.error, data: err.data, config: err.config };
  185. } else {
  186. throw { message: 'InfluxDB Error: ' + err.message, data: err.data, config: err.config };
  187. }
  188. }
  189. });
  190. };
  191. getTimeFilter(options) {
  192. var from = this.getInfluxTime(options.rangeRaw.from, false);
  193. var until = this.getInfluxTime(options.rangeRaw.to, true);
  194. var fromIsAbsolute = from[from.length-1] === 's';
  195. if (until === 'now()' && !fromIsAbsolute) {
  196. return 'time > ' + from;
  197. }
  198. return 'time > ' + from + ' and time < ' + until;
  199. }
  200. getInfluxTime(date, roundUp) {
  201. if (_.isString(date)) {
  202. if (date === 'now') {
  203. return 'now()';
  204. }
  205. var parts = /^now-(\d+)([d|h|m|s])$/.exec(date);
  206. if (parts) {
  207. var amount = parseInt(parts[1]);
  208. var unit = parts[2];
  209. return 'now() - ' + amount + unit;
  210. }
  211. date = dateMath.parse(date, roundUp);
  212. }
  213. return (date.valueOf() / 1000).toFixed(0) + 's';
  214. }
  215. }