datasource.js 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. define([
  2. 'angular',
  3. 'lodash',
  4. 'jquery',
  5. '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 (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. rangeRaw: 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, false) +
  119. '&until=' + this.translateTime(options.range.to, true) + tags,
  120. });
  121. }
  122. catch(err) {
  123. return $q.reject(err);
  124. }
  125. };
  126. GraphiteDatasource.prototype.translateTime = function(date, roundUp) {
  127. if (_.isString(date)) {
  128. if (date === 'now') {
  129. return 'now';
  130. }
  131. else if (date.indexOf('now-') >= 0 && date.indexOf('/') === -1) {
  132. date = date.substring(3);
  133. date = date.replace('m', 'min');
  134. date = date.replace('M', 'mon');
  135. return date;
  136. }
  137. date = dateMath.parse(date, roundUp);
  138. }
  139. // graphite' s from filter is exclusive
  140. // here we step back one minute in order
  141. // to guarantee that we get all the data that
  142. // exists for the specified range
  143. if (roundUp) {
  144. if (date.get('s')) {
  145. date.add(1, 'm');
  146. }
  147. }
  148. else if (roundUp === false) {
  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 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  200. GraphiteDatasource.prototype.buildGraphiteParams = function(options, scopedVars) {
  201. var graphite_options = ['from', 'until', 'rawData', 'format', 'maxDataPoints', 'cacheTimeout'];
  202. var clean_options = [], targets = {};
  203. var target, targetValue, i;
  204. var regex = /\#([A-Z])/g;
  205. var intervalFormatFixRegex = /'(\d+)m'/gi;
  206. if (options.format !== 'png') {
  207. options['format'] = 'json';
  208. }
  209. function fixIntervalFormat(match) {
  210. return match.replace('m', 'min').replace('M', 'mon');
  211. }
  212. for (i = 0; i < options.targets.length; i++) {
  213. target = options.targets[i];
  214. if (!target.target) {
  215. continue;
  216. }
  217. if (!target.refId) {
  218. target.refId = this._seriesRefLetters[i];
  219. }
  220. targetValue = templateSrv.replace(target.target, scopedVars);
  221. targetValue = targetValue.replace(intervalFormatFixRegex, fixIntervalFormat);
  222. targets[target.refId] = targetValue;
  223. }
  224. function nestedSeriesRegexReplacer(match, g1) {
  225. return targets[g1];
  226. }
  227. for (i = 0; i < options.targets.length; i++) {
  228. target = options.targets[i];
  229. if (!target.target) {
  230. continue;
  231. }
  232. targetValue = targets[target.refId];
  233. targetValue = targetValue.replace(regex, nestedSeriesRegexReplacer);
  234. targets[target.refId] = targetValue;
  235. if (!target.hide) {
  236. clean_options.push("target=" + encodeURIComponent(targetValue));
  237. }
  238. }
  239. _.each(options, function (value, key) {
  240. if ($.inArray(key, graphite_options) === -1) { return; }
  241. if (value) {
  242. clean_options.push(key + "=" + encodeURIComponent(value));
  243. }
  244. });
  245. return clean_options;
  246. };
  247. return GraphiteDatasource;
  248. });
  249. });