datasource.ts 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. ///<reference path="../../../headers/common.d.ts" />
  2. import angular from 'angular';
  3. import _ from 'lodash';
  4. import moment from 'moment';
  5. import * as dateMath from 'app/core/utils/datemath';
  6. /** @ngInject */
  7. export function GraphiteDatasource(instanceSettings, $q, backendSrv, templateSrv) {
  8. this.basicAuth = instanceSettings.basicAuth;
  9. this.url = instanceSettings.url;
  10. this.name = instanceSettings.name;
  11. this.cacheTimeout = instanceSettings.cacheTimeout;
  12. this.withCredentials = instanceSettings.withCredentials;
  13. this.render_method = instanceSettings.render_method || 'POST';
  14. this.query = function(options) {
  15. var graphOptions = {
  16. from: this.translateTime(options.rangeRaw.from, false),
  17. until: this.translateTime(options.rangeRaw.to, true),
  18. targets: options.targets,
  19. format: options.format,
  20. cacheTimeout: options.cacheTimeout || this.cacheTimeout,
  21. maxDataPoints: options.maxDataPoints,
  22. };
  23. var params = this.buildGraphiteParams(graphOptions, options.scopedVars);
  24. if (params.length === 0) {
  25. return $q.when({data: []});
  26. }
  27. var httpOptions: any = {
  28. method: 'POST',
  29. url: '/render',
  30. data: params.join('&'),
  31. headers: {
  32. 'Content-Type': 'application/x-www-form-urlencoded'
  33. },
  34. };
  35. if (options.panelId) {
  36. httpOptions.requestId = this.name + '.panelId.' + options.panelId;
  37. }
  38. return this.doGraphiteRequest(httpOptions).then(this.convertDataPointsToMs);
  39. };
  40. this.convertDataPointsToMs = function(result) {
  41. if (!result || !result.data) { return []; }
  42. for (var i = 0; i < result.data.length; i++) {
  43. var series = result.data[i];
  44. for (var y = 0; y < series.datapoints.length; y++) {
  45. series.datapoints[y][1] *= 1000;
  46. }
  47. }
  48. return result;
  49. };
  50. this.annotationQuery = function(options) {
  51. // Graphite metric as annotation
  52. if (options.annotation.target) {
  53. var target = templateSrv.replace(options.annotation.target, {}, 'glob');
  54. var graphiteQuery = {
  55. rangeRaw: options.rangeRaw,
  56. targets: [{ target: target }],
  57. format: 'json',
  58. maxDataPoints: 100
  59. };
  60. return this.query(graphiteQuery).then(function(result) {
  61. var list = [];
  62. for (var i = 0; i < result.data.length; i++) {
  63. var target = result.data[i];
  64. for (var y = 0; y < target.datapoints.length; y++) {
  65. var datapoint = target.datapoints[y];
  66. if (!datapoint[0]) { continue; }
  67. list.push({
  68. annotation: options.annotation,
  69. time: datapoint[1],
  70. title: target.target
  71. });
  72. }
  73. }
  74. return list;
  75. });
  76. } else {
  77. // Graphite event as annotation
  78. var tags = templateSrv.replace(options.annotation.tags);
  79. return this.events({range: options.rangeRaw, tags: tags}).then(function(results) {
  80. var list = [];
  81. for (var i = 0; i < results.data.length; i++) {
  82. var e = results.data[i];
  83. list.push({
  84. annotation: options.annotation,
  85. time: e.when * 1000,
  86. title: e.what,
  87. tags: e.tags,
  88. text: e.data
  89. });
  90. }
  91. return list;
  92. });
  93. }
  94. };
  95. this.events = function(options) {
  96. try {
  97. var tags = '';
  98. if (options.tags) {
  99. tags = '&tags=' + options.tags;
  100. }
  101. return this.doGraphiteRequest({
  102. method: 'GET',
  103. url: '/events/get_data?from=' + this.translateTime(options.range.from, false) +
  104. '&until=' + this.translateTime(options.range.to, true) + tags,
  105. });
  106. } catch (err) {
  107. return $q.reject(err);
  108. }
  109. };
  110. this.targetContainsTemplate = function(target) {
  111. return templateSrv.variableExists(target.target);
  112. };
  113. this.translateTime = function(date, roundUp) {
  114. if (_.isString(date)) {
  115. if (date === 'now') {
  116. return 'now';
  117. } else if (date.indexOf('now-') >= 0 && date.indexOf('/') === -1) {
  118. date = date.substring(3);
  119. date = date.replace('m', 'min');
  120. date = date.replace('M', 'mon');
  121. return date;
  122. }
  123. date = dateMath.parse(date, roundUp);
  124. }
  125. // graphite' s from filter is exclusive
  126. // here we step back one minute in order
  127. // to guarantee that we get all the data that
  128. // exists for the specified range
  129. if (roundUp) {
  130. if (date.get('s')) {
  131. date.add(1, 'm');
  132. }
  133. } else if (roundUp === false) {
  134. if (date.get('s')) {
  135. date.subtract(1, 'm');
  136. }
  137. }
  138. return date.unix();
  139. };
  140. this.metricFindQuery = function(query, options) {
  141. let interpolatedQuery = templateSrv.replace(query);
  142. let httpOptions: any = {
  143. method: 'GET',
  144. url: '/metrics/find',
  145. params: {
  146. query: interpolatedQuery
  147. },
  148. // for cancellations
  149. requestId: options.requestId,
  150. };
  151. if (options && options.range) {
  152. httpOptions.params.from = this.translateTime(options.range.raw.from, false);
  153. httpOptions.params.until = this.translateTime(options.range.raw.to, true);
  154. }
  155. return this.doGraphiteRequest(httpOptions).then(results => {
  156. return _.map(results.data, metric => {
  157. return {
  158. text: metric.text,
  159. expandable: metric.expandable ? true : false
  160. };
  161. });
  162. });
  163. };
  164. this.testDatasource = function() {
  165. return this.metricFindQuery('*').then(function () {
  166. return { status: "success", message: "Data source is working", title: "Success" };
  167. });
  168. };
  169. this.doGraphiteRequest = function(options) {
  170. if (this.basicAuth || this.withCredentials) {
  171. options.withCredentials = true;
  172. }
  173. if (this.basicAuth) {
  174. options.headers = options.headers || {};
  175. options.headers.Authorization = this.basicAuth;
  176. }
  177. options.url = this.url + options.url;
  178. options.inspect = {type: 'graphite'};
  179. return backendSrv.datasourceRequest(options);
  180. };
  181. this._seriesRefLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  182. this.buildGraphiteParams = function(options, scopedVars) {
  183. var graphite_options = ['from', 'until', 'rawData', 'format', 'maxDataPoints', 'cacheTimeout'];
  184. var clean_options = [], targets = {};
  185. var target, targetValue, i;
  186. var regex = /\#([A-Z])/g;
  187. var intervalFormatFixRegex = /'(\d+)m'/gi;
  188. var hasTargets = false;
  189. options['format'] = 'json';
  190. function fixIntervalFormat(match) {
  191. return match.replace('m', 'min').replace('M', 'mon');
  192. }
  193. for (i = 0; i < options.targets.length; i++) {
  194. target = options.targets[i];
  195. if (!target.target) {
  196. continue;
  197. }
  198. if (!target.refId) {
  199. target.refId = this._seriesRefLetters[i];
  200. }
  201. targetValue = templateSrv.replace(target.target, scopedVars);
  202. targetValue = targetValue.replace(intervalFormatFixRegex, fixIntervalFormat);
  203. targets[target.refId] = targetValue;
  204. }
  205. function nestedSeriesRegexReplacer(match, g1) {
  206. return targets[g1] || match;
  207. }
  208. for (i = 0; i < options.targets.length; i++) {
  209. target = options.targets[i];
  210. if (!target.target) {
  211. continue;
  212. }
  213. targetValue = targets[target.refId];
  214. targetValue = targetValue.replace(regex, nestedSeriesRegexReplacer);
  215. targets[target.refId] = targetValue;
  216. if (!target.hide) {
  217. hasTargets = true;
  218. clean_options.push("target=" + encodeURIComponent(targetValue));
  219. }
  220. }
  221. _.each(options, function (value, key) {
  222. if (_.indexOf(graphite_options, key) === -1) { return; }
  223. if (value) {
  224. clean_options.push(key + "=" + encodeURIComponent(value));
  225. }
  226. });
  227. if (!hasTargets) {
  228. return [];
  229. }
  230. return clean_options;
  231. };
  232. }