datasource.ts 8.0 KB

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