datasource.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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. allowDatabaseQuery: boolean;
  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.allowDatabaseQuery = (instanceSettings.jsonData || {}).allowDatabaseQuery === true;
  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) {
  48. return '';
  49. }
  50. queryTargets.push(target);
  51. // backward compatability
  52. scopedVars.interval = scopedVars.__interval;
  53. queryModel = new InfluxQuery(target, this.templateSrv, scopedVars);
  54. return queryModel.render(true);
  55. }).reduce((acc, current) => {
  56. if (current !== '') {
  57. acc += ';' + current;
  58. }
  59. return acc;
  60. });
  61. if (allQueries === '') {
  62. return this.$q.when({ data: [] });
  63. }
  64. // add global adhoc filters to timeFilter
  65. var adhocFilters = this.templateSrv.getAdhocFilters(this.name);
  66. if (adhocFilters.length > 0) {
  67. timeFilter += ' AND ' + queryModel.renderAdhocFilters(adhocFilters);
  68. }
  69. // replace grafana variables
  70. scopedVars.timeFilter = { value: timeFilter };
  71. // replace templated variables
  72. allQueries = this.templateSrv.replace(allQueries, scopedVars);
  73. return this._seriesQuery(allQueries, options).then((data): any => {
  74. if (!data || !data.results) {
  75. return [];
  76. }
  77. var seriesList = [];
  78. for (i = 0; i < data.results.length; i++) {
  79. var result = data.results[i];
  80. if (!result || !result.series) {
  81. continue;
  82. }
  83. var target = queryTargets[i];
  84. var alias = target.alias;
  85. if (alias) {
  86. alias = this.templateSrv.replace(target.alias, options.scopedVars);
  87. }
  88. var influxSeries = new InfluxSeries({
  89. series: data.results[i].series,
  90. alias: alias,
  91. });
  92. switch (target.resultFormat) {
  93. case 'table': {
  94. seriesList.push(influxSeries.getTable());
  95. break;
  96. }
  97. default: {
  98. var timeSeries = influxSeries.getTimeSeries();
  99. for (y = 0; y < timeSeries.length; y++) {
  100. seriesList.push(timeSeries[y]);
  101. }
  102. break;
  103. }
  104. }
  105. }
  106. return { data: seriesList };
  107. });
  108. }
  109. annotationQuery(options) {
  110. if (!options.annotation.query) {
  111. return this.$q.reject({
  112. message: 'Query missing in annotation definition',
  113. });
  114. }
  115. var timeFilter = this.getTimeFilter({ rangeRaw: options.rangeRaw });
  116. var query = options.annotation.query.replace('$timeFilter', timeFilter);
  117. query = this.templateSrv.replace(query, null, 'regex');
  118. return this._seriesQuery(query, options).then(data => {
  119. if (!data || !data.results || !data.results[0]) {
  120. throw { message: 'No results in response from InfluxDB' };
  121. }
  122. return new InfluxSeries({
  123. series: data.results[0].series,
  124. annotation: options.annotation,
  125. }).getAnnotations();
  126. });
  127. }
  128. targetContainsTemplate(target) {
  129. for (let group of target.groupBy) {
  130. for (let param of group.params) {
  131. if (this.templateSrv.variableExists(param)) {
  132. return true;
  133. }
  134. }
  135. }
  136. for (let i in target.tags) {
  137. if (this.templateSrv.variableExists(target.tags[i].value)) {
  138. return true;
  139. }
  140. }
  141. return false;
  142. }
  143. metricFindQuery(query: string, options?: any) {
  144. var interpolated = this.templateSrv.replace(query, null, 'regex');
  145. return this._seriesQuery(interpolated, options).then(_.curry(this.responseParser.parse)(query));
  146. }
  147. getTagKeys(options) {
  148. var queryBuilder = new InfluxQueryBuilder({ measurement: '', tags: [] }, this.database);
  149. var query = queryBuilder.buildExploreQuery('TAG_KEYS');
  150. return this.metricFindQuery(query, options);
  151. }
  152. getTagValues(options) {
  153. var queryBuilder = new InfluxQueryBuilder({ measurement: '', tags: [] }, this.database);
  154. var query = queryBuilder.buildExploreQuery('TAG_VALUES', options.key);
  155. return this.metricFindQuery(query, options);
  156. }
  157. _seriesQuery(query: string, options?: any) {
  158. if (!query) {
  159. return this.$q.when({ results: [] });
  160. }
  161. return this._influxRequest('GET', '/query', { q: query, epoch: 'ms' }, options);
  162. }
  163. serializeParams(params) {
  164. if (!params) {
  165. return '';
  166. }
  167. return _.reduce(
  168. params,
  169. (memo, value, key) => {
  170. if (value === null || value === undefined) {
  171. return memo;
  172. }
  173. memo.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
  174. return memo;
  175. },
  176. []
  177. ).join('&');
  178. }
  179. testDatasource() {
  180. var queryBuilder = new InfluxQueryBuilder({ measurement: '', tags: [] }, this.database);
  181. var query = queryBuilder.buildExploreQuery('RETENTION POLICIES');
  182. return this._seriesQuery(query)
  183. .then(res => {
  184. let error = _.get(res, 'results[0].error');
  185. if (error) {
  186. return { status: 'error', message: error };
  187. }
  188. return { status: 'success', message: 'Data source is working' };
  189. })
  190. .catch(err => {
  191. return { status: 'error', message: err.message };
  192. });
  193. }
  194. _influxRequest(method: string, url: string, data: any, options?: any) {
  195. var currentUrl = this.urls.shift();
  196. this.urls.push(currentUrl);
  197. var params: any = {};
  198. if (this.username) {
  199. params.u = this.username;
  200. params.p = this.password;
  201. }
  202. if (options && options.database) {
  203. params.db = options.database;
  204. if (params.db !== this.database && !this.allowDatabaseQuery) {
  205. return this.$q.reject({ message: 'This datasource does not allow changing database' });
  206. }
  207. } else if (this.database) {
  208. params.db = this.database;
  209. }
  210. if (method === 'GET') {
  211. _.extend(params, data);
  212. data = null;
  213. }
  214. var req: any = {
  215. method: method,
  216. url: currentUrl + url,
  217. params: params,
  218. data: data,
  219. precision: 'ms',
  220. inspect: { type: 'influxdb' },
  221. paramSerializer: this.serializeParams,
  222. };
  223. req.headers = req.headers || {};
  224. if (this.basicAuth || this.withCredentials) {
  225. req.withCredentials = true;
  226. }
  227. if (this.basicAuth) {
  228. req.headers.Authorization = this.basicAuth;
  229. }
  230. return this.backendSrv.datasourceRequest(options).then(
  231. result => {
  232. return result.data;
  233. },
  234. function(err) {
  235. if (err.status !== 0 || err.status >= 300) {
  236. if (err.data && err.data.error) {
  237. throw {
  238. message: 'InfluxDB Error: ' + err.data.error,
  239. data: err.data,
  240. config: err.config,
  241. };
  242. } else {
  243. throw {
  244. message: 'Network Error: ' + err.statusText + '(' + err.status + ')',
  245. data: err.data,
  246. config: err.config,
  247. };
  248. }
  249. }
  250. }
  251. );
  252. }
  253. getTimeFilter(options) {
  254. var from = this.getInfluxTime(options.rangeRaw.from, false);
  255. var until = this.getInfluxTime(options.rangeRaw.to, true);
  256. var fromIsAbsolute = from[from.length - 1] === 'ms';
  257. if (until === 'now()' && !fromIsAbsolute) {
  258. return 'time >= ' + from;
  259. }
  260. return 'time >= ' + from + ' and time <= ' + until;
  261. }
  262. getInfluxTime(date, roundUp) {
  263. if (_.isString(date)) {
  264. if (date === 'now') {
  265. return 'now()';
  266. }
  267. var parts = /^now-(\d+)([d|h|m|s])$/.exec(date);
  268. if (parts) {
  269. var amount = parseInt(parts[1]);
  270. var unit = parts[2];
  271. return 'now() - ' + amount + unit;
  272. }
  273. date = dateMath.parse(date, roundUp);
  274. }
  275. return date.valueOf() + 'ms';
  276. }
  277. }