datasource.ts 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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. query(options) {
  50. const targets = _.cloneDeep(options.targets);
  51. const queryTargets = targets.filter(t => t.query);
  52. if (queryTargets.length === 0) {
  53. return Promise.resolve({ data: [] });
  54. }
  55. // replace grafana variables
  56. const timeFilter = this.getTimeFilter(options);
  57. options.scopedVars.timeFilter = { value: timeFilter };
  58. const queries = queryTargets.map(target => {
  59. const { query, resultFormat } = target;
  60. // TODO replace templated variables
  61. // allQueries = this.templateSrv.replace(allQueries, scopedVars);
  62. if (resultFormat === 'table') {
  63. return (
  64. this._seriesQuery(query, options)
  65. .then(response => parseResults(response.data))
  66. // Keep only first result from each request
  67. .then(results => results[0])
  68. .then(getTableModelFromResult)
  69. );
  70. } else {
  71. return this._seriesQuery(query, options)
  72. .then(response => parseResults(response.data))
  73. .then(results => results.map(getTimeSeriesFromResult));
  74. }
  75. });
  76. return Promise.all(queries).then((series: any) => {
  77. let seriesList = _.flattenDeep(series).slice(0, MAX_SERIES);
  78. return { data: seriesList };
  79. });
  80. }
  81. annotationQuery(options) {
  82. if (!options.annotation.query) {
  83. return Promise.reject({
  84. message: 'Query missing in annotation definition',
  85. });
  86. }
  87. var timeFilter = this.getTimeFilter({ rangeRaw: options.rangeRaw });
  88. var query = options.annotation.query.replace('$timeFilter', timeFilter);
  89. query = this.templateSrv.replace(query, null, 'regex');
  90. return {};
  91. }
  92. targetContainsTemplate(target) {
  93. for (let group of target.groupBy) {
  94. for (let param of group.params) {
  95. if (this.templateSrv.variableExists(param)) {
  96. return true;
  97. }
  98. }
  99. }
  100. for (let i in target.tags) {
  101. if (this.templateSrv.variableExists(target.tags[i].value)) {
  102. return true;
  103. }
  104. }
  105. return false;
  106. }
  107. metricFindQuery(query: string, options?: any) {
  108. var interpolated = this.templateSrv.replace(query, null, 'regex');
  109. return this._seriesQuery(interpolated, options).then(_.curry(parseResults)(query));
  110. }
  111. _seriesQuery(query: string, options?: any) {
  112. if (!query) {
  113. return Promise.resolve({ data: '' });
  114. }
  115. return this._influxRequest('POST', '/v1/query', { q: query }, options);
  116. }
  117. testDatasource() {
  118. const query = `from(db:"${this.database}") |> last()`;
  119. return this._influxRequest('POST', '/v1/query', { q: query })
  120. .then(res => {
  121. if (res && res.trim()) {
  122. return { status: 'success', message: 'Data source connected and database found.' };
  123. }
  124. return {
  125. status: 'error',
  126. message:
  127. 'Data source connected, but has no data. Verify the "Database" field and make sure the database has data.',
  128. };
  129. })
  130. .catch(err => {
  131. return { status: 'error', message: err.message };
  132. });
  133. }
  134. _influxRequest(method: string, url: string, data: any, options?: any) {
  135. // TODO reinstante Round-robin
  136. // const currentUrl = this.urls.shift();
  137. // this.urls.push(currentUrl);
  138. const currentUrl = this.urls[0];
  139. let params: any = {
  140. orgName: this.orgName,
  141. };
  142. if (this.username) {
  143. params.u = this.username;
  144. params.p = this.password;
  145. }
  146. if (options && options.database) {
  147. params.db = options.database;
  148. } else if (this.database) {
  149. params.db = this.database;
  150. }
  151. // data sent as GET param
  152. _.extend(params, data);
  153. data = null;
  154. let req: any = {
  155. method: method,
  156. url: currentUrl + url,
  157. params: params,
  158. data: data,
  159. precision: 'ms',
  160. inspect: { type: this.type },
  161. paramSerializer: serializeParams,
  162. };
  163. req.headers = req.headers || {};
  164. if (this.basicAuth || this.withCredentials) {
  165. req.withCredentials = true;
  166. }
  167. if (this.basicAuth) {
  168. req.headers.Authorization = this.basicAuth;
  169. }
  170. return this.backendSrv.datasourceRequest(req).then(
  171. result => {
  172. return result;
  173. },
  174. function(err) {
  175. if (err.status !== 0 || err.status >= 300) {
  176. if (err.data && err.data.error) {
  177. throw {
  178. message: 'InfluxDB Error: ' + err.data.error,
  179. data: err.data,
  180. config: err.config,
  181. };
  182. } else {
  183. throw {
  184. message: 'Network Error: ' + err.statusText + '(' + err.status + ')',
  185. data: err.data,
  186. config: err.config,
  187. };
  188. }
  189. }
  190. }
  191. );
  192. }
  193. getTimeFilter(options) {
  194. var from = this.getInfluxTime(options.rangeRaw.from, false);
  195. var until = this.getInfluxTime(options.rangeRaw.to, true);
  196. var fromIsAbsolute = from[from.length - 1] === 'ms';
  197. if (until === 'now()' && !fromIsAbsolute) {
  198. return 'time >= ' + from;
  199. }
  200. return 'time >= ' + from + ' and time <= ' + until;
  201. }
  202. getInfluxTime(date, roundUp) {
  203. if (_.isString(date)) {
  204. if (date === 'now') {
  205. return 'now()';
  206. }
  207. var parts = /^now-(\d+)([d|h|m|s])$/.exec(date);
  208. if (parts) {
  209. var amount = parseInt(parts[1]);
  210. var unit = parts[2];
  211. return 'now() - ' + amount + unit;
  212. }
  213. date = dateMath.parse(date, roundUp);
  214. }
  215. return date.valueOf() + 'ms';
  216. }
  217. }