datasource.js 8.7 KB

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