datasource.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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.range.from, false),
  29. until: this.translateTime(options.range.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) + '&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) {
  132. date = date.substring(3);
  133. date = date.replace('m', 'min');
  134. date = date.replace('M', 'mon');
  135. return date;
  136. }
  137. console.log('date: ' + date + ' round up: ' + roundUp);
  138. date = dateMath.parse(date, roundUp);
  139. console.log('date: ' + date + ' round up: ' + roundUp + ' ' + date.format('YYYY-MM-DD:HH:mm'));
  140. }
  141. date = moment.utc(date);
  142. if (roundUp) {
  143. if (date.get('s')) {
  144. date.add(1, 'm');
  145. }
  146. }
  147. else if (roundUp === false) {
  148. // graphite' s from filter is exclusive
  149. // here we step back one minute in order
  150. // to guarantee that we get all the data that
  151. // exists for the specified range
  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. if (options.format !== 'png') {
  210. options['format'] = 'json';
  211. }
  212. function fixIntervalFormat(match) {
  213. return match.replace('m', 'min').replace('M', 'mon');
  214. }
  215. for (i = 0; i < options.targets.length; i++) {
  216. target = options.targets[i];
  217. if (!target.target) {
  218. continue;
  219. }
  220. if (!target.refId) {
  221. target.refId = this._seriesRefLetters[i];
  222. }
  223. targetValue = templateSrv.replace(target.target, scopedVars);
  224. targetValue = targetValue.replace(intervalFormatFixRegex, fixIntervalFormat);
  225. targets[target.refId] = targetValue;
  226. }
  227. function nestedSeriesRegexReplacer(match, g1) {
  228. return targets[g1];
  229. }
  230. for (i = 0; i < options.targets.length; i++) {
  231. target = options.targets[i];
  232. if (!target.target) {
  233. continue;
  234. }
  235. targetValue = targets[target.refId];
  236. targetValue = targetValue.replace(regex, nestedSeriesRegexReplacer);
  237. targets[target.refId] = targetValue;
  238. if (!target.hide) {
  239. clean_options.push("target=" + encodeURIComponent(targetValue));
  240. }
  241. }
  242. _.each(options, function (value, key) {
  243. if ($.inArray(key, graphite_options) === -1) { return; }
  244. if (value) {
  245. clean_options.push(key + "=" + encodeURIComponent(value));
  246. }
  247. });
  248. return clean_options;
  249. };
  250. return GraphiteDatasource;
  251. });
  252. });