datasource.ts 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. import _ from 'lodash';
  2. import * as dateMath from 'app/core/utils/datemath';
  3. import InfluxSeries from './influx_series';
  4. import InfluxQuery from './influx_query';
  5. import ResponseParser from './response_parser';
  6. import { InfluxQueryBuilder } from './query_builder';
  7. export default class InfluxDatasource {
  8. type: string;
  9. urls: any;
  10. username: string;
  11. password: string;
  12. name: string;
  13. database: any;
  14. basicAuth: any;
  15. withCredentials: 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.withCredentials = instanceSettings.withCredentials;
  32. this.interval = (instanceSettings.jsonData || {}).timeInterval;
  33. this.supportAnnotations = true;
  34. this.supportMetrics = true;
  35. this.responseParser = new ResponseParser();
  36. }
  37. query(options) {
  38. var timeFilter = this.getTimeFilter(options);
  39. var scopedVars = options.scopedVars;
  40. var targets = _.cloneDeep(options.targets);
  41. var queryTargets = [];
  42. var queryModel;
  43. var i, y;
  44. var allQueries = _.map(targets, target => {
  45. if (target.hide) {
  46. return '';
  47. }
  48. queryTargets.push(target);
  49. // backward compatibility
  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) {
  79. continue;
  80. }
  81. var target = queryTargets[i];
  82. var alias = target.alias;
  83. if (alias) {
  84. alias = this.templateSrv.replace(target.alias, options.scopedVars);
  85. }
  86. var influxSeries = new InfluxSeries({
  87. series: data.results[i].series,
  88. alias: alias,
  89. });
  90. switch (target.resultFormat) {
  91. case 'table': {
  92. seriesList.push(influxSeries.getTable());
  93. break;
  94. }
  95. default: {
  96. var timeSeries = influxSeries.getTimeSeries();
  97. for (y = 0; y < timeSeries.length; y++) {
  98. seriesList.push(timeSeries[y]);
  99. }
  100. break;
  101. }
  102. }
  103. }
  104. return { data: seriesList };
  105. });
  106. }
  107. annotationQuery(options) {
  108. if (!options.annotation.query) {
  109. return this.$q.reject({
  110. message: 'Query missing in annotation definition',
  111. });
  112. }
  113. var timeFilter = this.getTimeFilter({ rangeRaw: options.rangeRaw });
  114. var query = options.annotation.query.replace('$timeFilter', timeFilter);
  115. query = this.templateSrv.replace(query, null, 'regex');
  116. return this._seriesQuery(query).then(data => {
  117. if (!data || !data.results || !data.results[0]) {
  118. throw { message: 'No results in response from InfluxDB' };
  119. }
  120. return new InfluxSeries({
  121. series: data.results[0].series,
  122. annotation: options.annotation,
  123. }).getAnnotations();
  124. });
  125. }
  126. targetContainsTemplate(target) {
  127. for (let group of target.groupBy) {
  128. for (let param of group.params) {
  129. if (this.templateSrv.variableExists(param)) {
  130. return true;
  131. }
  132. }
  133. }
  134. for (let i in target.tags) {
  135. if (this.templateSrv.variableExists(target.tags[i].value)) {
  136. return true;
  137. }
  138. }
  139. return false;
  140. }
  141. metricFindQuery(query) {
  142. var interpolated = this.templateSrv.replace(query, null, 'regex');
  143. return this._seriesQuery(interpolated).then(_.curry(this.responseParser.parse)(query));
  144. }
  145. getTagKeys(options) {
  146. var queryBuilder = new InfluxQueryBuilder({ measurement: '', tags: [] }, this.database);
  147. var query = queryBuilder.buildExploreQuery('TAG_KEYS');
  148. return this.metricFindQuery(query);
  149. }
  150. getTagValues(options) {
  151. var queryBuilder = new InfluxQueryBuilder({ measurement: '', tags: [] }, this.database);
  152. var query = queryBuilder.buildExploreQuery('TAG_VALUES', options.key);
  153. return this.metricFindQuery(query);
  154. }
  155. _seriesQuery(query) {
  156. if (!query) {
  157. return this.$q.when({ results: [] });
  158. }
  159. return this._influxRequest('GET', '/query', { q: query, epoch: 'ms' });
  160. }
  161. serializeParams(params) {
  162. if (!params) {
  163. return '';
  164. }
  165. return _.reduce(
  166. params,
  167. (memo, value, key) => {
  168. if (value === null || value === undefined) {
  169. return memo;
  170. }
  171. memo.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
  172. return memo;
  173. },
  174. []
  175. ).join('&');
  176. }
  177. testDatasource() {
  178. var queryBuilder = new InfluxQueryBuilder({ measurement: '', tags: [] }, this.database);
  179. var query = queryBuilder.buildExploreQuery('RETENTION POLICIES');
  180. return this._seriesQuery(query)
  181. .then(res => {
  182. let error = _.get(res, 'results[0].error');
  183. if (error) {
  184. return { status: 'error', message: error };
  185. }
  186. return { status: 'success', message: 'Data source is working' };
  187. })
  188. .catch(err => {
  189. return { status: 'error', message: err.message };
  190. });
  191. }
  192. _influxRequest(method, url, data) {
  193. var self = this;
  194. var currentUrl = self.urls.shift();
  195. self.urls.push(currentUrl);
  196. var params: any = {};
  197. if (self.username) {
  198. params.u = self.username;
  199. params.p = self.password;
  200. }
  201. if (self.database) {
  202. params.db = self.database;
  203. }
  204. if (method === 'GET') {
  205. _.extend(params, data);
  206. data = null;
  207. }
  208. var options: any = {
  209. method: method,
  210. url: currentUrl + url,
  211. params: params,
  212. data: data,
  213. precision: 'ms',
  214. inspect: { type: 'influxdb' },
  215. paramSerializer: this.serializeParams,
  216. };
  217. options.headers = options.headers || {};
  218. if (this.basicAuth || this.withCredentials) {
  219. options.withCredentials = true;
  220. }
  221. if (self.basicAuth) {
  222. options.headers.Authorization = self.basicAuth;
  223. }
  224. return this.backendSrv.datasourceRequest(options).then(
  225. result => {
  226. return result.data;
  227. },
  228. function(err) {
  229. if (err.status !== 0 || err.status >= 300) {
  230. if (err.data && err.data.error) {
  231. throw {
  232. message: 'InfluxDB Error: ' + err.data.error,
  233. data: err.data,
  234. config: err.config,
  235. };
  236. } else {
  237. throw {
  238. message: 'Network Error: ' + err.statusText + '(' + err.status + ')',
  239. data: err.data,
  240. config: err.config,
  241. };
  242. }
  243. }
  244. }
  245. );
  246. }
  247. getTimeFilter(options) {
  248. var from = this.getInfluxTime(options.rangeRaw.from, false);
  249. var until = this.getInfluxTime(options.rangeRaw.to, true);
  250. var fromIsAbsolute = from[from.length - 1] === 'ms';
  251. if (until === 'now()' && !fromIsAbsolute) {
  252. return 'time >= ' + from;
  253. }
  254. return 'time >= ' + from + ' and time <= ' + until;
  255. }
  256. getInfluxTime(date, roundUp) {
  257. if (_.isString(date)) {
  258. if (date === 'now') {
  259. return 'now()';
  260. }
  261. var parts = /^now-(\d+)([d|h|m|s])$/.exec(date);
  262. if (parts) {
  263. var amount = parseInt(parts[1]);
  264. var unit = parts[2];
  265. return 'now() - ' + amount + unit;
  266. }
  267. date = dateMath.parse(date, roundUp);
  268. }
  269. return date.valueOf() + 'ms';
  270. }
  271. }