datasource.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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(
  68. (data): any => {
  69. if (!data || !data.results) {
  70. return [];
  71. }
  72. const seriesList = [];
  73. for (i = 0; i < data.results.length; i++) {
  74. const result = data.results[i];
  75. if (!result || !result.series) {
  76. continue;
  77. }
  78. const target = queryTargets[i];
  79. let alias = target.alias;
  80. if (alias) {
  81. alias = this.templateSrv.replace(target.alias, options.scopedVars);
  82. }
  83. const influxSeries = new InfluxSeries({
  84. series: data.results[i].series,
  85. alias: alias,
  86. });
  87. switch (target.resultFormat) {
  88. case 'table': {
  89. seriesList.push(influxSeries.getTable());
  90. break;
  91. }
  92. default: {
  93. const timeSeries = influxSeries.getTimeSeries();
  94. for (y = 0; y < timeSeries.length; y++) {
  95. seriesList.push(timeSeries[y]);
  96. }
  97. break;
  98. }
  99. }
  100. }
  101. return { data: seriesList };
  102. }
  103. );
  104. }
  105. annotationQuery(options) {
  106. if (!options.annotation.query) {
  107. return this.$q.reject({
  108. message: 'Query missing in annotation definition',
  109. });
  110. }
  111. const timeFilter = this.getTimeFilter({ rangeRaw: options.rangeRaw, timezone: options.timezone });
  112. let query = options.annotation.query.replace('$timeFilter', timeFilter);
  113. query = this.templateSrv.replace(query, null, 'regex');
  114. return this._seriesQuery(query, options).then(data => {
  115. if (!data || !data.results || !data.results[0]) {
  116. throw { message: 'No results in response from InfluxDB' };
  117. }
  118. return new InfluxSeries({
  119. series: data.results[0].series,
  120. annotation: options.annotation,
  121. }).getAnnotations();
  122. });
  123. }
  124. targetContainsTemplate(target) {
  125. for (const group of target.groupBy) {
  126. for (const param of group.params) {
  127. if (this.templateSrv.variableExists(param)) {
  128. return true;
  129. }
  130. }
  131. }
  132. for (const i in target.tags) {
  133. if (this.templateSrv.variableExists(target.tags[i].value)) {
  134. return true;
  135. }
  136. }
  137. return false;
  138. }
  139. metricFindQuery(query: string, options?: any) {
  140. const interpolated = this.templateSrv.replace(query, null, 'regex');
  141. return this._seriesQuery(interpolated, options).then(_.curry(this.responseParser.parse)(query));
  142. }
  143. getTagKeys(options) {
  144. const queryBuilder = new InfluxQueryBuilder({ measurement: '', tags: [] }, this.database);
  145. const query = queryBuilder.buildExploreQuery('TAG_KEYS');
  146. return this.metricFindQuery(query, options);
  147. }
  148. getTagValues(options) {
  149. const queryBuilder = new InfluxQueryBuilder({ measurement: '', tags: [] }, this.database);
  150. const query = queryBuilder.buildExploreQuery('TAG_VALUES', options.key);
  151. return this.metricFindQuery(query, options);
  152. }
  153. _seriesQuery(query: string, options?: any) {
  154. if (!query) {
  155. return this.$q.when({ results: [] });
  156. }
  157. if (options && options.range) {
  158. const timeFilter = this.getTimeFilter({ rangeRaw: options.range, timezone: options.timezone });
  159. query = query.replace('$timeFilter', timeFilter);
  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. const queryBuilder = new InfluxQueryBuilder({ measurement: '', tags: [] }, this.database);
  181. const query = queryBuilder.buildExploreQuery('RETENTION POLICIES');
  182. return this._seriesQuery(query)
  183. .then(res => {
  184. const 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. const currentUrl = this.urls.shift();
  196. this.urls.push(currentUrl);
  197. const 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. } else if (this.database) {
  205. params.db = this.database;
  206. }
  207. if (method === 'GET') {
  208. _.extend(params, data);
  209. data = null;
  210. }
  211. const req: any = {
  212. method: method,
  213. url: currentUrl + url,
  214. params: params,
  215. data: data,
  216. precision: 'ms',
  217. inspect: { type: 'influxdb' },
  218. paramSerializer: this.serializeParams,
  219. };
  220. req.headers = req.headers || {};
  221. if (this.basicAuth || this.withCredentials) {
  222. req.withCredentials = true;
  223. }
  224. if (this.basicAuth) {
  225. req.headers.Authorization = this.basicAuth;
  226. }
  227. return this.backendSrv.datasourceRequest(req).then(
  228. result => {
  229. return result.data;
  230. },
  231. err => {
  232. if (err.status !== 0 || err.status >= 300) {
  233. if (err.data && err.data.error) {
  234. throw {
  235. message: 'InfluxDB Error: ' + err.data.error,
  236. data: err.data,
  237. config: err.config,
  238. };
  239. } else {
  240. throw {
  241. message: 'Network Error: ' + err.statusText + '(' + err.status + ')',
  242. data: err.data,
  243. config: err.config,
  244. };
  245. }
  246. }
  247. }
  248. );
  249. }
  250. getTimeFilter(options) {
  251. const from = this.getInfluxTime(options.rangeRaw.from, false, options.timezone);
  252. const until = this.getInfluxTime(options.rangeRaw.to, true, options.timezone);
  253. const fromIsAbsolute = from[from.length - 1] === 'ms';
  254. if (until === 'now()' && !fromIsAbsolute) {
  255. return 'time >= ' + from;
  256. }
  257. return 'time >= ' + from + ' and time <= ' + until;
  258. }
  259. getInfluxTime(date, roundUp, timezone) {
  260. if (_.isString(date)) {
  261. if (date === 'now') {
  262. return 'now()';
  263. }
  264. const parts = /^now-(\d+)([dhms])$/.exec(date);
  265. if (parts) {
  266. const amount = parseInt(parts[1], 10);
  267. const unit = parts[2];
  268. return 'now() - ' + amount + unit;
  269. }
  270. date = dateMath.parse(date, roundUp, timezone);
  271. }
  272. return date.valueOf() + 'ms';
  273. }
  274. }