datasource.js 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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, $http, templateSrv) {
  16. function GraphiteDatasource(datasource) {
  17. this.type = 'graphite';
  18. this.basicAuth = datasource.basicAuth;
  19. this.url = datasource.url;
  20. this.name = datasource.name;
  21. this.cacheTimeout = datasource.cacheTimeout;
  22. this.withCredentials = datasource.withCredentials;
  23. this.render_method = datasource.render_method || 'POST';
  24. this.supportAnnotations = true;
  25. this.supportMetrics = true;
  26. this.editorSrc = 'app/features/graphite/partials/query.editor.html';
  27. this.annotationEditorSrc = 'app/features/graphite/partials/annotations.editor.html';
  28. }
  29. GraphiteDatasource.prototype.query = function(options) {
  30. try {
  31. var graphOptions = {
  32. from: this.translateTime(options.range.from, 'round-down'),
  33. until: this.translateTime(options.range.to, 'round-up'),
  34. targets: options.targets,
  35. format: options.format,
  36. cacheTimeout: options.cacheTimeout || this.cacheTimeout,
  37. maxDataPoints: options.maxDataPoints,
  38. };
  39. var params = this.buildGraphiteParams(graphOptions);
  40. if (options.format === 'png') {
  41. return $q.when(this.url + '/render' + '?' + params.join('&'));
  42. }
  43. var httpOptions = { method: this.render_method, url: '/render' };
  44. if (httpOptions.method === 'GET') {
  45. httpOptions.url = httpOptions.url + '?' + params.join('&');
  46. }
  47. else {
  48. httpOptions.data = params.join('&');
  49. httpOptions.headers = { 'Content-Type': 'application/x-www-form-urlencoded' };
  50. }
  51. return this.doGraphiteRequest(httpOptions).then(this.convertDataPointsToMs);
  52. }
  53. catch(err) {
  54. return $q.reject(err);
  55. }
  56. };
  57. GraphiteDatasource.prototype.convertDataPointsToMs = function(result) {
  58. if (!result || !result.data) { return []; }
  59. for (var i = 0; i < result.data.length; i++) {
  60. var series = result.data[i];
  61. for (var y = 0; y < series.datapoints.length; y++) {
  62. series.datapoints[y][1] *= 1000;
  63. }
  64. }
  65. return result;
  66. };
  67. GraphiteDatasource.prototype.annotationQuery = function(annotation, rangeUnparsed) {
  68. // Graphite metric as annotation
  69. if (annotation.target) {
  70. var target = templateSrv.replace(annotation.target);
  71. var graphiteQuery = {
  72. range: rangeUnparsed,
  73. targets: [{ target: target }],
  74. format: 'json',
  75. maxDataPoints: 100
  76. };
  77. return this.query(graphiteQuery)
  78. .then(function(result) {
  79. var list = [];
  80. for (var i = 0; i < result.data.length; i++) {
  81. var target = result.data[i];
  82. for (var y = 0; y < target.datapoints.length; y++) {
  83. var datapoint = target.datapoints[y];
  84. if (!datapoint[0]) { continue; }
  85. list.push({
  86. annotation: annotation,
  87. time: datapoint[1],
  88. title: target.target
  89. });
  90. }
  91. }
  92. return list;
  93. });
  94. }
  95. // Graphite event as annotation
  96. else {
  97. var tags = templateSrv.replace(annotation.tags);
  98. return this.events({ range: rangeUnparsed, tags: tags })
  99. .then(function(results) {
  100. var list = [];
  101. for (var i = 0; i < results.data.length; i++) {
  102. var e = results.data[i];
  103. list.push({
  104. annotation: annotation,
  105. time: e.when * 1000,
  106. title: e.what,
  107. tags: e.tags,
  108. text: e.data
  109. });
  110. }
  111. return list;
  112. });
  113. }
  114. };
  115. GraphiteDatasource.prototype.events = function(options) {
  116. try {
  117. var tags = '';
  118. if (options.tags) {
  119. tags = '&tags=' + options.tags;
  120. }
  121. return this.doGraphiteRequest({
  122. method: 'GET',
  123. url: '/events/get_data?from=' + this.translateTime(options.range.from) + '&until=' + this.translateTime(options.range.to) + tags,
  124. });
  125. }
  126. catch(err) {
  127. return $q.reject(err);
  128. }
  129. };
  130. GraphiteDatasource.prototype.translateTime = function(date, rounding) {
  131. if (_.isString(date)) {
  132. if (date === 'now') {
  133. return 'now';
  134. }
  135. else if (date.indexOf('now') >= 0) {
  136. date = date.substring(3);
  137. date = date.replace('m', 'min');
  138. date = date.replace('M', 'mon');
  139. return date;
  140. }
  141. date = kbn.parseDate(date);
  142. }
  143. date = moment.utc(date);
  144. if (rounding === 'round-up') {
  145. if (date.get('s')) {
  146. date.add(1, 'm');
  147. }
  148. }
  149. else if (rounding === 'round-down') {
  150. // graphite' s from filter is exclusive
  151. // here we step back one minute in order
  152. // to guarantee that we get all the data that
  153. // exists for the specified range
  154. if (date.get('s')) {
  155. date.subtract(1, 'm');
  156. }
  157. }
  158. return date.unix();
  159. };
  160. GraphiteDatasource.prototype.metricFindQuery = function(query) {
  161. var interpolated;
  162. try {
  163. interpolated = encodeURIComponent(templateSrv.replace(query));
  164. }
  165. catch(err) {
  166. return $q.reject(err);
  167. }
  168. return this.doGraphiteRequest({method: 'GET', url: '/metrics/find/?query=' + interpolated })
  169. .then(function(results) {
  170. return _.map(results.data, function(metric) {
  171. return {
  172. text: metric.text,
  173. expandable: metric.expandable ? true : false
  174. };
  175. });
  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 = 'Basic ' + this.basicAuth;
  194. }
  195. options.url = this.url + options.url;
  196. options.inspect = { type: 'graphite' };
  197. return $http(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) {
  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);
  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. clean_options.push("target=" + encodeURIComponent(targetValue));
  240. }
  241. _.each(options, function (value, key) {
  242. if ($.inArray(key, graphite_options) === -1) { return; }
  243. if (value) {
  244. clean_options.push(key + "=" + encodeURIComponent(value));
  245. }
  246. });
  247. return clean_options;
  248. };
  249. return GraphiteDatasource;
  250. });
  251. });