datasource.ts 7.7 KB

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