datasource.ts 7.7 KB

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