datasource.ts 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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. urls: any;
  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.urls = instanceSettings.url.split(',').map(url => 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. targetContainsTemplate(target) {
  101. for (let group of target.groupBy) {
  102. for (let param of group.params) {
  103. if (this.templateSrv.variableExists(param)) {
  104. return true;
  105. }
  106. }
  107. }
  108. for (let i in target.tags) {
  109. if (this.templateSrv.variableExists(target.tags[i].value)) {
  110. return true;
  111. }
  112. }
  113. return false;
  114. }
  115. metricFindQuery(query: string, options?: any) {
  116. var interpolated = this.templateSrv.replace(query, null, 'regex');
  117. return this._seriesQuery(interpolated, options).then(_.curry(parseResults)(query));
  118. }
  119. _seriesQuery(query: string, options?: any) {
  120. if (!query) {
  121. return Promise.resolve({ data: '' });
  122. }
  123. return this._influxRequest('POST', '/v1/query', { q: query }, options);
  124. }
  125. testDatasource() {
  126. const query = `from(db:"${this.database}") |> last()`;
  127. return this._influxRequest('POST', '/v1/query', { q: query })
  128. .then(res => {
  129. if (res && res.trim()) {
  130. return { status: 'success', message: 'Data source connected and database found.' };
  131. }
  132. return {
  133. status: 'error',
  134. message:
  135. 'Data source connected, but has no data. Verify the "Database" field and make sure the database has data.',
  136. };
  137. })
  138. .catch(err => {
  139. return { status: 'error', message: err.message };
  140. });
  141. }
  142. _influxRequest(method: string, url: string, data: any, options?: any) {
  143. // TODO reinstante Round-robin
  144. // const currentUrl = this.urls.shift();
  145. // this.urls.push(currentUrl);
  146. const currentUrl = this.urls[0];
  147. let params: any = {
  148. orgName: this.orgName,
  149. };
  150. if (this.username) {
  151. params.u = this.username;
  152. params.p = this.password;
  153. }
  154. if (options && options.database) {
  155. params.db = options.database;
  156. } else if (this.database) {
  157. params.db = this.database;
  158. }
  159. // data sent as GET param
  160. _.extend(params, data);
  161. data = null;
  162. let req: any = {
  163. method: method,
  164. url: currentUrl + url,
  165. params: params,
  166. data: data,
  167. precision: 'ms',
  168. inspect: { type: this.type },
  169. paramSerializer: serializeParams,
  170. };
  171. req.headers = req.headers || {};
  172. if (this.basicAuth || this.withCredentials) {
  173. req.withCredentials = true;
  174. }
  175. if (this.basicAuth) {
  176. req.headers.Authorization = this.basicAuth;
  177. }
  178. return this.backendSrv.datasourceRequest(req).then(
  179. result => {
  180. return result;
  181. },
  182. function(err) {
  183. if (err.status !== 0 || err.status >= 300) {
  184. if (err.data && err.data.error) {
  185. throw {
  186. message: 'InfluxDB Error: ' + err.data.error,
  187. data: err.data,
  188. config: err.config,
  189. };
  190. } else {
  191. throw {
  192. message: 'Network Error: ' + err.statusText + '(' + err.status + ')',
  193. data: err.data,
  194. config: err.config,
  195. };
  196. }
  197. }
  198. }
  199. );
  200. }
  201. getTimeFilter(options) {
  202. const from = this.getInfluxTime(options.rangeRaw.from, false);
  203. const to = this.getInfluxTime(options.rangeRaw.to, true);
  204. if (to === 'now') {
  205. return `start: ${from}`;
  206. }
  207. return `start: ${from}, stop: ${to}`;
  208. }
  209. getInfluxTime(date, roundUp) {
  210. if (_.isString(date)) {
  211. if (date === 'now') {
  212. return date;
  213. }
  214. const parts = /^now\s*-\s*(\d+)([d|h|m|s])$/.exec(date);
  215. if (parts) {
  216. const amount = parseInt(parts[1]);
  217. const unit = parts[2];
  218. return '-' + amount + unit;
  219. }
  220. date = dateMath.parse(date, roundUp);
  221. }
  222. return date.toISOString();
  223. }
  224. }