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