datasource.ts 7.9 KB

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