datasource.ts 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. import _ from 'lodash';
  2. import * as dateMath from 'app/core/utils/datemath';
  3. import { getTableModelFromResult, getTimeSeriesFromResult, getValuesFromResult, parseResults } from './response_parser';
  4. import expandMacros from './metric_find_query';
  5. function serializeParams(params) {
  6. if (!params) {
  7. return '';
  8. }
  9. return _.reduce(
  10. params,
  11. (memo, value, key) => {
  12. if (value === null || value === undefined) {
  13. return memo;
  14. }
  15. memo.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
  16. return memo;
  17. },
  18. []
  19. ).join('&');
  20. }
  21. const MAX_SERIES = 20;
  22. export default class InfluxDatasource {
  23. type: string;
  24. url: string;
  25. username: string;
  26. password: string;
  27. name: string;
  28. orgName: string;
  29. database: any;
  30. basicAuth: any;
  31. withCredentials: any;
  32. interval: any;
  33. supportAnnotations: boolean;
  34. supportMetrics: boolean;
  35. /** @ngInject */
  36. constructor(instanceSettings, private backendSrv, private templateSrv) {
  37. this.type = 'influxdb-ifql';
  38. this.url = instanceSettings.url.trim();
  39. this.username = instanceSettings.username;
  40. this.password = instanceSettings.password;
  41. this.name = instanceSettings.name;
  42. this.orgName = instanceSettings.orgName || 'defaultorgname';
  43. this.database = instanceSettings.database;
  44. this.basicAuth = instanceSettings.basicAuth;
  45. this.withCredentials = instanceSettings.withCredentials;
  46. this.interval = (instanceSettings.jsonData || {}).timeInterval;
  47. this.supportAnnotations = true;
  48. this.supportMetrics = true;
  49. }
  50. prepareQueryTarget(target, options) {
  51. // Replace grafana variables
  52. const timeFilter = this.getTimeFilter(options);
  53. options.scopedVars.range = { value: timeFilter };
  54. const interpolated = this.templateSrv.replace(target.query, options.scopedVars);
  55. return {
  56. ...target,
  57. query: interpolated,
  58. };
  59. }
  60. query(options) {
  61. const queryTargets = options.targets
  62. .filter(target => target.query)
  63. .map(target => this.prepareQueryTarget(target, options));
  64. if (queryTargets.length === 0) {
  65. return Promise.resolve({ data: [] });
  66. }
  67. const queries = queryTargets.map(target => {
  68. const { query, resultFormat } = target;
  69. if (resultFormat === 'table') {
  70. return this._seriesQuery(query, options)
  71. .then(response => parseResults(response.data))
  72. .then(results => results.map(getTableModelFromResult));
  73. } else {
  74. return this._seriesQuery(query, options)
  75. .then(response => parseResults(response.data))
  76. .then(results => results.map(getTimeSeriesFromResult));
  77. }
  78. });
  79. return Promise.all(queries).then((series: any) => {
  80. let seriesList = _.flattenDeep(series).slice(0, MAX_SERIES);
  81. return { data: seriesList };
  82. });
  83. }
  84. annotationQuery(options) {
  85. if (!options.annotation.query) {
  86. return Promise.reject({
  87. message: 'Query missing in annotation definition',
  88. });
  89. }
  90. var timeFilter = this.getTimeFilter({ rangeRaw: options.rangeRaw });
  91. var query = options.annotation.query.replace('$timeFilter', timeFilter);
  92. query = this.templateSrv.replace(query, null, 'regex');
  93. return {};
  94. }
  95. metricFindQuery(query: string, options?: any) {
  96. const interpreted = expandMacros(query);
  97. // Use normal querier in silent mode
  98. const queryOptions = {
  99. rangeRaw: { to: 'now', from: 'now - 1h' },
  100. scopedVars: {},
  101. ...options,
  102. silent: true,
  103. };
  104. const target = this.prepareQueryTarget({ query: interpreted }, queryOptions);
  105. return this._seriesQuery(target.query, queryOptions).then(response => {
  106. const results = parseResults(response.data);
  107. const values = _.uniq(_.flatten(results.map(getValuesFromResult)));
  108. return values
  109. .filter(value => value && value[0] !== '_') // Ignore internal fields
  110. .map(value => ({ text: value }));
  111. });
  112. }
  113. _seriesQuery(query: string, options?: any) {
  114. if (!query) {
  115. return Promise.resolve({ data: '' });
  116. }
  117. return this._influxRequest('POST', '/v1/query', { q: query }, options);
  118. }
  119. testDatasource() {
  120. const query = `from(db:"${this.database}") |> last()`;
  121. return this._influxRequest('POST', '/v1/query', { q: query })
  122. .then(res => {
  123. if (res && res.trim()) {
  124. return { status: 'success', message: 'Data source connected and database found.' };
  125. }
  126. return {
  127. status: 'error',
  128. message:
  129. 'Data source connected, but has no data. Verify the "Database" field and make sure the database has data.',
  130. };
  131. })
  132. .catch(err => {
  133. return { status: 'error', message: err.message };
  134. });
  135. }
  136. _influxRequest(method: string, url: string, data: any, options?: any) {
  137. let params: any = {
  138. orgName: this.orgName,
  139. };
  140. if (this.username) {
  141. params.u = this.username;
  142. params.p = this.password;
  143. }
  144. // data sent as GET param
  145. _.extend(params, data);
  146. data = null;
  147. let req: any = {
  148. method: method,
  149. url: this.url + url,
  150. params: params,
  151. data: data,
  152. precision: 'ms',
  153. inspect: { type: this.type },
  154. paramSerializer: serializeParams,
  155. };
  156. req.headers = req.headers || {};
  157. if (this.basicAuth || this.withCredentials) {
  158. req.withCredentials = true;
  159. }
  160. if (this.basicAuth) {
  161. req.headers.Authorization = this.basicAuth;
  162. }
  163. return this.backendSrv.datasourceRequest(req).then(
  164. result => {
  165. return result;
  166. },
  167. function(err) {
  168. if (err.status !== 0 || err.status >= 300) {
  169. if (err.data && err.data.error) {
  170. throw {
  171. message: 'InfluxDB Error: ' + err.data.error,
  172. data: err.data,
  173. config: err.config,
  174. };
  175. } else {
  176. throw {
  177. message: 'Network Error: ' + err.statusText + '(' + err.status + ')',
  178. data: err.data,
  179. config: err.config,
  180. };
  181. }
  182. }
  183. }
  184. );
  185. }
  186. getTimeFilter(options) {
  187. const from = this.getInfluxTime(options.rangeRaw.from, false);
  188. const to = this.getInfluxTime(options.rangeRaw.to, true);
  189. if (to === 'now') {
  190. return `start: ${from}`;
  191. }
  192. return `start: ${from}, stop: ${to}`;
  193. }
  194. getInfluxTime(date, roundUp) {
  195. if (_.isString(date)) {
  196. if (date === 'now') {
  197. return date;
  198. }
  199. const parts = /^now\s*-\s*(\d+)([d|h|m|s])$/.exec(date);
  200. if (parts) {
  201. const amount = parseInt(parts[1]);
  202. const unit = parts[2];
  203. return '-' + amount + unit;
  204. }
  205. date = dateMath.parse(date, roundUp);
  206. }
  207. return date.toISOString();
  208. }
  209. }