datasource.ts 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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. responseParser: any;
  18. /** @ngInject */
  19. constructor(instanceSettings, private $q, private backendSrv, private templateSrv) {
  20. this.type = 'influxdb';
  21. this.urls = _.map(instanceSettings.url.split(','), url => {
  22. return url.trim();
  23. });
  24. this.username = instanceSettings.username;
  25. this.password = instanceSettings.password;
  26. this.name = instanceSettings.name;
  27. this.database = instanceSettings.database;
  28. this.basicAuth = instanceSettings.basicAuth;
  29. this.withCredentials = instanceSettings.withCredentials;
  30. this.interval = (instanceSettings.jsonData || {}).timeInterval;
  31. this.responseParser = new ResponseParser();
  32. }
  33. query(options) {
  34. let timeFilter = this.getTimeFilter(options);
  35. const scopedVars = options.scopedVars;
  36. const targets = _.cloneDeep(options.targets);
  37. const queryTargets = [];
  38. let queryModel;
  39. let i, y;
  40. let allQueries = _.map(targets, target => {
  41. if (target.hide) {
  42. return '';
  43. }
  44. queryTargets.push(target);
  45. // backward compatibility
  46. scopedVars.interval = scopedVars.__interval;
  47. queryModel = new InfluxQuery(target, this.templateSrv, scopedVars);
  48. return queryModel.render(true);
  49. }).reduce((acc, current) => {
  50. if (current !== '') {
  51. acc += ';' + current;
  52. }
  53. return acc;
  54. });
  55. if (allQueries === '') {
  56. return this.$q.when({ data: [] });
  57. }
  58. // add global adhoc filters to timeFilter
  59. const adhocFilters = this.templateSrv.getAdhocFilters(this.name);
  60. if (adhocFilters.length > 0) {
  61. timeFilter += ' AND ' + queryModel.renderAdhocFilters(adhocFilters);
  62. }
  63. // replace grafana variables
  64. scopedVars.timeFilter = { value: timeFilter };
  65. // replace templated variables
  66. allQueries = this.templateSrv.replace(allQueries, scopedVars);
  67. return this._seriesQuery(allQueries, options).then((data): any => {
  68. if (!data || !data.results) {
  69. return [];
  70. }
  71. const seriesList = [];
  72. for (i = 0; i < data.results.length; i++) {
  73. const result = data.results[i];
  74. if (!result || !result.series) {
  75. continue;
  76. }
  77. const target = queryTargets[i];
  78. let alias = target.alias;
  79. if (alias) {
  80. alias = this.templateSrv.replace(target.alias, options.scopedVars);
  81. }
  82. const influxSeries = new InfluxSeries({
  83. series: data.results[i].series,
  84. alias: alias,
  85. });
  86. switch (target.resultFormat) {
  87. case 'table': {
  88. seriesList.push(influxSeries.getTable());
  89. break;
  90. }
  91. default: {
  92. const timeSeries = influxSeries.getTimeSeries();
  93. for (y = 0; y < timeSeries.length; y++) {
  94. seriesList.push(timeSeries[y]);
  95. }
  96. break;
  97. }
  98. }
  99. }
  100. return { data: seriesList };
  101. });
  102. }
  103. annotationQuery(options) {
  104. if (!options.annotation.query) {
  105. return this.$q.reject({
  106. message: 'Query missing in annotation definition',
  107. });
  108. }
  109. const timeFilter = this.getTimeFilter({ rangeRaw: options.rangeRaw });
  110. let query = options.annotation.query.replace('$timeFilter', timeFilter);
  111. query = this.templateSrv.replace(query, null, 'regex');
  112. return this._seriesQuery(query, options).then(data => {
  113. if (!data || !data.results || !data.results[0]) {
  114. throw { message: 'No results in response from InfluxDB' };
  115. }
  116. return new InfluxSeries({
  117. series: data.results[0].series,
  118. annotation: options.annotation,
  119. }).getAnnotations();
  120. });
  121. }
  122. targetContainsTemplate(target) {
  123. for (const group of target.groupBy) {
  124. for (const param of group.params) {
  125. if (this.templateSrv.variableExists(param)) {
  126. return true;
  127. }
  128. }
  129. }
  130. for (const i in target.tags) {
  131. if (this.templateSrv.variableExists(target.tags[i].value)) {
  132. return true;
  133. }
  134. }
  135. return false;
  136. }
  137. metricFindQuery(query: string, options?: any) {
  138. const interpolated = this.templateSrv.replace(query, null, 'regex');
  139. return this._seriesQuery(interpolated, options).then(_.curry(this.responseParser.parse)(query));
  140. }
  141. getTagKeys(options) {
  142. const queryBuilder = new InfluxQueryBuilder({ measurement: '', tags: [] }, this.database);
  143. const query = queryBuilder.buildExploreQuery('TAG_KEYS');
  144. return this.metricFindQuery(query, options);
  145. }
  146. getTagValues(options) {
  147. const queryBuilder = new InfluxQueryBuilder({ measurement: '', tags: [] }, this.database);
  148. const query = queryBuilder.buildExploreQuery('TAG_VALUES', options.key);
  149. return this.metricFindQuery(query, options);
  150. }
  151. _seriesQuery(query: string, options?: any) {
  152. if (!query) {
  153. return this.$q.when({ results: [] });
  154. }
  155. if (options && options.range) {
  156. const timeFilter = this.getTimeFilter({ rangeRaw: options.range });
  157. query = query.replace('$timeFilter', timeFilter);
  158. }
  159. return this._influxRequest('GET', '/query', { q: query, epoch: 'ms' }, options);
  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. const queryBuilder = new InfluxQueryBuilder({ measurement: '', tags: [] }, this.database);
  179. const query = queryBuilder.buildExploreQuery('RETENTION POLICIES');
  180. return this._seriesQuery(query)
  181. .then(res => {
  182. const 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: string, url: string, data: any, options?: any) {
  193. const currentUrl = this.urls.shift();
  194. this.urls.push(currentUrl);
  195. const params: any = {};
  196. if (this.username) {
  197. params.u = this.username;
  198. params.p = this.password;
  199. }
  200. if (options && options.database) {
  201. params.db = options.database;
  202. } else if (this.database) {
  203. params.db = this.database;
  204. }
  205. if (method === 'GET') {
  206. _.extend(params, data);
  207. data = null;
  208. }
  209. const req: any = {
  210. method: method,
  211. url: currentUrl + url,
  212. params: params,
  213. data: data,
  214. precision: 'ms',
  215. inspect: { type: 'influxdb' },
  216. paramSerializer: this.serializeParams,
  217. };
  218. req.headers = req.headers || {};
  219. if (this.basicAuth || this.withCredentials) {
  220. req.withCredentials = true;
  221. }
  222. if (this.basicAuth) {
  223. req.headers.Authorization = this.basicAuth;
  224. }
  225. return this.backendSrv.datasourceRequest(req).then(
  226. result => {
  227. return result.data;
  228. },
  229. err => {
  230. if (err.status !== 0 || err.status >= 300) {
  231. if (err.data && err.data.error) {
  232. throw {
  233. message: 'InfluxDB Error: ' + err.data.error,
  234. data: err.data,
  235. config: err.config,
  236. };
  237. } else {
  238. throw {
  239. message: 'Network Error: ' + err.statusText + '(' + err.status + ')',
  240. data: err.data,
  241. config: err.config,
  242. };
  243. }
  244. }
  245. }
  246. );
  247. }
  248. getTimeFilter(options) {
  249. const from = this.getInfluxTime(options.rangeRaw.from, false);
  250. const until = this.getInfluxTime(options.rangeRaw.to, true);
  251. const fromIsAbsolute = from[from.length - 1] === 'ms';
  252. if (until === 'now()' && !fromIsAbsolute) {
  253. return 'time >= ' + from;
  254. }
  255. return 'time >= ' + from + ' and time <= ' + until;
  256. }
  257. getInfluxTime(date, roundUp) {
  258. if (_.isString(date)) {
  259. if (date === 'now') {
  260. return 'now()';
  261. }
  262. const parts = /^now-(\d+)([d|h|m|s])$/.exec(date);
  263. if (parts) {
  264. const amount = parseInt(parts[1], 10);
  265. const unit = parts[2];
  266. return 'now() - ' + amount + unit;
  267. }
  268. date = dateMath.parse(date, roundUp);
  269. }
  270. return date.valueOf() + 'ms';
  271. }
  272. }