datasource.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. define([
  2. 'angular',
  3. 'lodash',
  4. 'jquery',
  5. 'config',
  6. 'kbn',
  7. 'moment',
  8. './queryCtrl',
  9. './funcEditor',
  10. './addGraphiteFunc',
  11. ],
  12. function (angular, _, $, config, kbn, moment) {
  13. 'use strict';
  14. var module = angular.module('grafana.services');
  15. module.factory('GraphiteDatasource', function($q, backendSrv, templateSrv) {
  16. function GraphiteDatasource(datasource) {
  17. this.basicAuth = datasource.basicAuth;
  18. this.url = datasource.url;
  19. this.name = datasource.name;
  20. this.cacheTimeout = datasource.cacheTimeout;
  21. this.withCredentials = datasource.withCredentials;
  22. this.render_method = datasource.render_method || 'POST';
  23. }
  24. GraphiteDatasource.prototype.query = function(options) {
  25. try {
  26. var graphOptions = {
  27. from: this.translateTime(options.range.from, 'round-down'),
  28. until: this.translateTime(options.range.to, 'round-up'),
  29. targets: options.targets,
  30. format: options.format,
  31. cacheTimeout: options.cacheTimeout || this.cacheTimeout,
  32. maxDataPoints: options.maxDataPoints,
  33. };
  34. var params = this.buildGraphiteParams(graphOptions, options.scopedVars);
  35. if (options.format === 'png') {
  36. return $q.when(this.url + '/render' + '?' + params.join('&'));
  37. }
  38. var httpOptions = { method: this.render_method, url: '/render' };
  39. if (httpOptions.method === 'GET') {
  40. httpOptions.url = httpOptions.url + '?' + params.join('&');
  41. }
  42. else {
  43. httpOptions.data = params.join('&');
  44. httpOptions.headers = { 'Content-Type': 'application/x-www-form-urlencoded' };
  45. }
  46. return this.doGraphiteRequest(httpOptions).then(this.convertDataPointsToMs);
  47. }
  48. catch(err) {
  49. return $q.reject(err);
  50. }
  51. };
  52. GraphiteDatasource.prototype.convertDataPointsToMs = function(result) {
  53. if (!result || !result.data) { return []; }
  54. for (var i = 0; i < result.data.length; i++) {
  55. var series = result.data[i];
  56. for (var y = 0; y < series.datapoints.length; y++) {
  57. series.datapoints[y][1] *= 1000;
  58. }
  59. }
  60. return result;
  61. };
  62. GraphiteDatasource.prototype.annotationQuery = function(annotation, rangeUnparsed) {
  63. // Graphite metric as annotation
  64. if (annotation.target) {
  65. var target = templateSrv.replace(annotation.target);
  66. var graphiteQuery = {
  67. range: rangeUnparsed,
  68. targets: [{ target: target }],
  69. format: 'json',
  70. maxDataPoints: 100
  71. };
  72. return this.query(graphiteQuery)
  73. .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: annotation,
  82. time: datapoint[1],
  83. title: target.target
  84. });
  85. }
  86. }
  87. return list;
  88. });
  89. }
  90. // Graphite event as annotation
  91. else {
  92. var tags = templateSrv.replace(annotation.tags);
  93. return this.events({ range: rangeUnparsed, tags: tags })
  94. .then(function(results) {
  95. var list = [];
  96. for (var i = 0; i < results.data.length; i++) {
  97. var e = results.data[i];
  98. list.push({
  99. annotation: annotation,
  100. time: e.when * 1000,
  101. title: e.what,
  102. tags: e.tags,
  103. text: e.data
  104. });
  105. }
  106. return list;
  107. });
  108. }
  109. };
  110. GraphiteDatasource.prototype.events = function(options) {
  111. try {
  112. var tags = '';
  113. if (options.tags) {
  114. tags = '&tags=' + options.tags;
  115. }
  116. return this.doGraphiteRequest({
  117. method: 'GET',
  118. url: '/events/get_data?from=' + this.translateTime(options.range.from) + '&until=' + this.translateTime(options.range.to) + tags,
  119. });
  120. }
  121. catch(err) {
  122. return $q.reject(err);
  123. }
  124. };
  125. GraphiteDatasource.prototype.translateTime = function(date, rounding) {
  126. if (_.isString(date)) {
  127. if (date === 'now') {
  128. return 'now';
  129. }
  130. else if (date.indexOf('now') >= 0) {
  131. date = date.substring(3);
  132. date = date.replace('m', 'min');
  133. date = date.replace('M', 'mon');
  134. return date;
  135. }
  136. date = kbn.parseDate(date);
  137. }
  138. date = moment.utc(date);
  139. if (rounding === 'round-up') {
  140. if (date.get('s')) {
  141. date.add(1, 'm');
  142. }
  143. }
  144. else if (rounding === 'round-down') {
  145. // graphite' s from filter is exclusive
  146. // here we step back one minute in order
  147. // to guarantee that we get all the data that
  148. // exists for the specified range
  149. if (date.get('s')) {
  150. date.subtract(1, 'm');
  151. }
  152. }
  153. return date.unix();
  154. };
  155. GraphiteDatasource.prototype.metricFindQuery = function(query) {
  156. var interpolated;
  157. try {
  158. interpolated = encodeURIComponent(templateSrv.replace(query));
  159. }
  160. catch(err) {
  161. return $q.reject(err);
  162. }
  163. return this.doGraphiteRequest({method: 'GET', url: '/metrics/find/?query=' + interpolated })
  164. .then(function(results) {
  165. return _.map(results.data, function(metric) {
  166. return {
  167. text: metric.text,
  168. expandable: metric.expandable ? true : false
  169. };
  170. });
  171. });
  172. };
  173. GraphiteDatasource.prototype.testDatasource = function() {
  174. return this.metricFindQuery('*').then(function () {
  175. return { status: "success", message: "Data source is working", title: "Success" };
  176. });
  177. };
  178. GraphiteDatasource.prototype.listDashboards = function(query) {
  179. return this.doGraphiteRequest({ method: 'GET', url: '/dashboard/find/', params: {query: query || ''} })
  180. .then(function(results) {
  181. return results.data.dashboards;
  182. });
  183. };
  184. GraphiteDatasource.prototype.loadDashboard = function(dashName) {
  185. return this.doGraphiteRequest({method: 'GET', url: '/dashboard/load/' + encodeURIComponent(dashName) });
  186. };
  187. GraphiteDatasource.prototype.doGraphiteRequest = function(options) {
  188. if (this.basicAuth || this.withCredentials) {
  189. options.withCredentials = true;
  190. }
  191. if (this.basicAuth) {
  192. options.headers = options.headers || {};
  193. options.headers.Authorization = this.basicAuth;
  194. }
  195. options.url = this.url + options.url;
  196. options.inspect = { type: 'graphite' };
  197. return backendSrv.datasourceRequest(options);
  198. };
  199. GraphiteDatasource.prototype._seriesRefLetters = [
  200. '#A', '#B', '#C', '#D',
  201. '#E', '#F', '#G', '#H',
  202. '#I', '#J', '#K', '#L',
  203. '#M', '#N', '#O', '#P',
  204. '#Q', '#R', '#S', '#T',
  205. '#U', '#V', '#W', '#X',
  206. '#Y', '#Z'
  207. ];
  208. GraphiteDatasource.prototype.buildGraphiteParams = function(options, scopedVars) {
  209. var graphite_options = ['from', 'until', 'rawData', 'format', 'maxDataPoints', 'cacheTimeout'];
  210. var clean_options = [], targets = {};
  211. var target, targetValue, i;
  212. var regex = /(\#[A-Z])/g;
  213. var intervalFormatFixRegex = /'(\d+)m'/gi;
  214. if (options.format !== 'png') {
  215. options['format'] = 'json';
  216. }
  217. function fixIntervalFormat(match) {
  218. return match.replace('m', 'min').replace('M', 'mon');
  219. }
  220. for (i = 0; i < options.targets.length; i++) {
  221. target = options.targets[i];
  222. if (!target.target) {
  223. continue;
  224. }
  225. targetValue = templateSrv.replace(target.target, scopedVars);
  226. targetValue = targetValue.replace(intervalFormatFixRegex, fixIntervalFormat);
  227. targets[this._seriesRefLetters[i]] = targetValue;
  228. }
  229. function nestedSeriesRegexReplacer(match) {
  230. return targets[match];
  231. }
  232. for (i = 0; i < options.targets.length; i++) {
  233. target = options.targets[i];
  234. if (!target.target || target.hide) {
  235. continue;
  236. }
  237. targetValue = targets[this._seriesRefLetters[i]];
  238. targetValue = targetValue.replace(regex, nestedSeriesRegexReplacer);
  239. targets[this._seriesRefLetters[i]] = targetValue;
  240. clean_options.push("target=" + encodeURIComponent(targetValue));
  241. }
  242. _.each(options, function (value, key) {
  243. if ($.inArray(key, graphite_options) === -1) { return; }
  244. if (value) {
  245. clean_options.push(key + "=" + encodeURIComponent(value));
  246. }
  247. });
  248. return clean_options;
  249. };
  250. return GraphiteDatasource;
  251. });
  252. });