datasource.ts 8.8 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. 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(','), 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. let timeFilter = this.getTimeFilter(options);
  39. const scopedVars = options.scopedVars;
  40. const targets = _.cloneDeep(options.targets);
  41. const queryTargets = [];
  42. let queryModel;
  43. let i, y;
  44. let 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. const 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, options).then((data): any => {
  72. if (!data || !data.results) {
  73. return [];
  74. }
  75. const seriesList = [];
  76. for (i = 0; i < data.results.length; i++) {
  77. const result = data.results[i];
  78. if (!result || !result.series) {
  79. continue;
  80. }
  81. const target = queryTargets[i];
  82. let alias = target.alias;
  83. if (alias) {
  84. alias = this.templateSrv.replace(target.alias, options.scopedVars);
  85. }
  86. const 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. const 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. const timeFilter = this.getTimeFilter({ rangeRaw: options.rangeRaw });
  114. let query = options.annotation.query.replace('$timeFilter', timeFilter);
  115. query = this.templateSrv.replace(query, null, 'regex');
  116. return this._seriesQuery(query, options).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 (const group of target.groupBy) {
  128. for (const param of group.params) {
  129. if (this.templateSrv.variableExists(param)) {
  130. return true;
  131. }
  132. }
  133. }
  134. for (const 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: string, options?: any) {
  142. const interpolated = this.templateSrv.replace(query, null, 'regex');
  143. return this._seriesQuery(interpolated, options).then(_.curry(this.responseParser.parse)(query));
  144. }
  145. getTagKeys(options) {
  146. const queryBuilder = new InfluxQueryBuilder({ measurement: '', tags: [] }, this.database);
  147. const query = queryBuilder.buildExploreQuery('TAG_KEYS');
  148. return this.metricFindQuery(query, options);
  149. }
  150. getTagValues(options) {
  151. const queryBuilder = new InfluxQueryBuilder({ measurement: '', tags: [] }, this.database);
  152. const query = queryBuilder.buildExploreQuery('TAG_VALUES', options.key);
  153. return this.metricFindQuery(query, options);
  154. }
  155. _seriesQuery(query: string, options?: any) {
  156. if (!query) {
  157. return this.$q.when({ results: [] });
  158. }
  159. if (options && options.range) {
  160. const timeFilter = this.getTimeFilter({ rangeRaw: options.range });
  161. query = query.replace('$timeFilter', timeFilter);
  162. }
  163. return this._influxRequest('GET', '/query', { q: query, epoch: 'ms' }, options);
  164. }
  165. serializeParams(params) {
  166. if (!params) {
  167. return '';
  168. }
  169. return _.reduce(
  170. params,
  171. (memo, value, key) => {
  172. if (value === null || value === undefined) {
  173. return memo;
  174. }
  175. memo.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
  176. return memo;
  177. },
  178. []
  179. ).join('&');
  180. }
  181. testDatasource() {
  182. const queryBuilder = new InfluxQueryBuilder({ measurement: '', tags: [] }, this.database);
  183. const query = queryBuilder.buildExploreQuery('RETENTION POLICIES');
  184. return this._seriesQuery(query)
  185. .then(res => {
  186. const error = _.get(res, 'results[0].error');
  187. if (error) {
  188. return { status: 'error', message: error };
  189. }
  190. return { status: 'success', message: 'Data source is working' };
  191. })
  192. .catch(err => {
  193. return { status: 'error', message: err.message };
  194. });
  195. }
  196. _influxRequest(method: string, url: string, data: any, options?: any) {
  197. const currentUrl = this.urls.shift();
  198. this.urls.push(currentUrl);
  199. const params: any = {};
  200. if (this.username) {
  201. params.u = this.username;
  202. params.p = this.password;
  203. }
  204. if (options && options.database) {
  205. params.db = options.database;
  206. } else if (this.database) {
  207. params.db = this.database;
  208. }
  209. if (method === 'GET') {
  210. _.extend(params, data);
  211. data = null;
  212. }
  213. const req: any = {
  214. method: method,
  215. url: currentUrl + url,
  216. params: params,
  217. data: data,
  218. precision: 'ms',
  219. inspect: { type: 'influxdb' },
  220. paramSerializer: this.serializeParams,
  221. };
  222. req.headers = req.headers || {};
  223. if (this.basicAuth || this.withCredentials) {
  224. req.withCredentials = true;
  225. }
  226. if (this.basicAuth) {
  227. req.headers.Authorization = this.basicAuth;
  228. }
  229. return this.backendSrv.datasourceRequest(req).then(
  230. result => {
  231. return result.data;
  232. },
  233. err => {
  234. if (err.status !== 0 || err.status >= 300) {
  235. if (err.data && err.data.error) {
  236. throw {
  237. message: 'InfluxDB Error: ' + err.data.error,
  238. data: err.data,
  239. config: err.config,
  240. };
  241. } else {
  242. throw {
  243. message: 'Network Error: ' + err.statusText + '(' + err.status + ')',
  244. data: err.data,
  245. config: err.config,
  246. };
  247. }
  248. }
  249. }
  250. );
  251. }
  252. getTimeFilter(options) {
  253. const from = this.getInfluxTime(options.rangeRaw.from, false);
  254. const until = this.getInfluxTime(options.rangeRaw.to, true);
  255. const fromIsAbsolute = from[from.length - 1] === 'ms';
  256. if (until === 'now()' && !fromIsAbsolute) {
  257. return 'time >= ' + from;
  258. }
  259. return 'time >= ' + from + ' and time <= ' + until;
  260. }
  261. getInfluxTime(date, roundUp) {
  262. if (_.isString(date)) {
  263. if (date === 'now') {
  264. return 'now()';
  265. }
  266. const parts = /^now-(\d+)([d|h|m|s])$/.exec(date);
  267. if (parts) {
  268. const amount = parseInt(parts[1]);
  269. const unit = parts[2];
  270. return 'now() - ' + amount + unit;
  271. }
  272. date = dateMath.parse(date, roundUp);
  273. }
  274. return date.valueOf() + 'ms';
  275. }
  276. }