datasource.js 8.9 KB

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