datasource.ts 8.0 KB

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