datasource.ts 8.0 KB

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