datasource.ts 7.9 KB

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