datasource.ts 6.3 KB

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