datasource.ts 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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;
  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. // backward compatability
  50. scopedVars.interval = scopedVars.__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. targetContainsTemplate(target) {
  117. for (let group of target.groupBy) {
  118. for (let param of group.params) {
  119. if (this.templateSrv.variableExists(param)) {
  120. return true;
  121. }
  122. }
  123. }
  124. for (let i in target.tags) {
  125. if (this.templateSrv.variableExists(target.tags[i].value)) {
  126. return true;
  127. }
  128. }
  129. return false;
  130. }
  131. metricFindQuery(query) {
  132. var interpolated = this.templateSrv.replace(query, null, 'regex');
  133. return this._seriesQuery(interpolated)
  134. .then(_.curry(this.responseParser.parse)(query));
  135. }
  136. getTagKeys(options) {
  137. var queryBuilder = new InfluxQueryBuilder({measurement: '', tags: []}, this.database);
  138. var query = queryBuilder.buildExploreQuery('TAG_KEYS');
  139. return this.metricFindQuery(query);
  140. }
  141. getTagValues(options) {
  142. var queryBuilder = new InfluxQueryBuilder({measurement: '', tags: []}, this.database);
  143. var query = queryBuilder.buildExploreQuery('TAG_VALUES', options.key);
  144. return this.metricFindQuery(query);
  145. }
  146. _seriesQuery(query) {
  147. if (!query) { return this.$q.when({results: []}); }
  148. return this._influxRequest('GET', '/query', {q: query, epoch: 'ms'});
  149. }
  150. serializeParams(params) {
  151. if (!params) { return '';}
  152. return _.reduce(params, (memo, value, key) => {
  153. if (value === null || value === undefined) { return memo; }
  154. memo.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
  155. return memo;
  156. }, []).join("&");
  157. }
  158. testDatasource() {
  159. return this.metricFindQuery('SHOW DATABASES').then(res => {
  160. let found = _.find(res, {text: this.database});
  161. if (!found) {
  162. return { status: "error", message: "Could not find the specified database name.", title: "DB Not found" };
  163. }
  164. return { status: "success", message: "Data source is working", title: "Success" };
  165. }).catch(err => {
  166. return { status: "error", message: err.message, title: "Test Failed" };
  167. });
  168. }
  169. _influxRequest(method, url, data) {
  170. var self = this;
  171. var currentUrl = self.urls.shift();
  172. self.urls.push(currentUrl);
  173. var params: any = {};
  174. if (self.username) {
  175. params.username = self.username;
  176. params.password = self.password;
  177. }
  178. if (self.database) {
  179. params.db = self.database;
  180. }
  181. if (method === 'GET') {
  182. _.extend(params, data);
  183. data = null;
  184. }
  185. var options: any = {
  186. method: method,
  187. url: currentUrl + url,
  188. params: params,
  189. data: data,
  190. precision: "ms",
  191. inspect: { type: 'influxdb' },
  192. paramSerializer: this.serializeParams,
  193. };
  194. options.headers = options.headers || {};
  195. if (this.basicAuth || this.withCredentials) {
  196. options.withCredentials = true;
  197. }
  198. if (self.basicAuth) {
  199. options.headers.Authorization = self.basicAuth;
  200. }
  201. return this.backendSrv.datasourceRequest(options).then(result => {
  202. return result.data;
  203. }, function(err) {
  204. if (err.status !== 0 || err.status >= 300) {
  205. if (err.data && err.data.error) {
  206. throw { message: 'InfluxDB Error: ' + err.data.error, data: err.data, config: err.config };
  207. } else {
  208. throw { message: 'Network Error: ' + err.statusText + '(' + err.status + ')', data: err.data, config: err.config };
  209. }
  210. }
  211. });
  212. }
  213. getTimeFilter(options) {
  214. var from = this.getInfluxTime(options.rangeRaw.from, false);
  215. var until = this.getInfluxTime(options.rangeRaw.to, true);
  216. var fromIsAbsolute = from[from.length-1] === 'ms';
  217. if (until === 'now()' && !fromIsAbsolute) {
  218. return 'time > ' + from;
  219. }
  220. return 'time > ' + from + ' and time < ' + until;
  221. }
  222. getInfluxTime(date, roundUp) {
  223. if (_.isString(date)) {
  224. if (date === 'now') {
  225. return 'now()';
  226. }
  227. var parts = /^now-(\d+)([d|h|m|s])$/.exec(date);
  228. if (parts) {
  229. var amount = parseInt(parts[1]);
  230. var unit = parts[2];
  231. return 'now() - ' + amount + unit;
  232. }
  233. date = dateMath.parse(date, roundUp);
  234. }
  235. return date.valueOf() + 'ms';
  236. }
  237. }