datasource.js 8.9 KB

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