datasource.ts 7.9 KB

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