datasource.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. define([
  2. 'angular',
  3. 'lodash',
  4. 'jquery',
  5. 'app/core/config',
  6. 'app/core/utils/datemath',
  7. './query_ctrl',
  8. './func_editor',
  9. './add_graphite_func',
  10. ],
  11. function (angular, _, $, config, dateMath) {
  12. 'use strict';
  13. /** @ngInject */
  14. function GraphiteDatasource(instanceSettings, $q, backendSrv, templateSrv) {
  15. this.basicAuth = instanceSettings.basicAuth;
  16. this.url = instanceSettings.url;
  17. this.name = instanceSettings.name;
  18. this.cacheTimeout = instanceSettings.cacheTimeout;
  19. this.withCredentials = instanceSettings.withCredentials;
  20. this.render_method = instanceSettings.render_method || 'POST';
  21. this.query = function(options) {
  22. try {
  23. var graphOptions = {
  24. from: this.translateTime(options.rangeRaw.from, false),
  25. until: this.translateTime(options.rangeRaw.to, true),
  26. targets: options.targets,
  27. format: options.format,
  28. cacheTimeout: options.cacheTimeout || this.cacheTimeout,
  29. maxDataPoints: options.maxDataPoints,
  30. };
  31. var params = this.buildGraphiteParams(graphOptions, options.scopedVars);
  32. if (params.length === 0) {
  33. return $q.when([]);
  34. }
  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. this.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. this.annotationQuery = function(options) {
  63. // Graphite metric as annotation
  64. if (options.annotation.target) {
  65. var target = templateSrv.replace(options.annotation.target);
  66. var graphiteQuery = {
  67. rangeRaw: options.rangeRaw,
  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: options.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(options.annotation.tags);
  93. return this.events({range: options.rangeRaw, tags: tags}).then(function(results) {
  94. var list = [];
  95. for (var i = 0; i < results.data.length; i++) {
  96. var e = results.data[i];
  97. list.push({
  98. annotation: options.annotation,
  99. time: e.when * 1000,
  100. title: e.what,
  101. tags: e.tags,
  102. text: e.data
  103. });
  104. }
  105. return list;
  106. });
  107. }
  108. };
  109. this.events = function(options) {
  110. try {
  111. var tags = '';
  112. if (options.tags) {
  113. tags = '&tags=' + options.tags;
  114. }
  115. return this.doGraphiteRequest({
  116. method: 'GET',
  117. url: '/events/get_data?from=' + this.translateTime(options.range.from, false) +
  118. '&until=' + this.translateTime(options.range.to, true) + tags,
  119. });
  120. }
  121. catch(err) {
  122. return $q.reject(err);
  123. }
  124. };
  125. this.translateTime = function(date, roundUp) {
  126. if (_.isString(date)) {
  127. if (date === 'now') {
  128. return 'now';
  129. }
  130. else if (date.indexOf('now-') >= 0 && date.indexOf('/') === -1) {
  131. date = date.substring(3);
  132. date = date.replace('m', 'min');
  133. date = date.replace('M', 'mon');
  134. return date;
  135. }
  136. date = dateMath.parse(date, roundUp);
  137. }
  138. // graphite' s from filter is exclusive
  139. // here we step back one minute in order
  140. // to guarantee that we get all the data that
  141. // exists for the specified range
  142. if (roundUp) {
  143. if (date.get('s')) {
  144. date.add(1, 'm');
  145. }
  146. }
  147. else if (roundUp === false) {
  148. if (date.get('s')) {
  149. date.subtract(1, 'm');
  150. }
  151. }
  152. return date.unix();
  153. };
  154. this.metricFindQuery = function(query) {
  155. var interpolated;
  156. try {
  157. interpolated = encodeURIComponent(templateSrv.replace(query));
  158. }
  159. catch(err) {
  160. return $q.reject(err);
  161. }
  162. return this.doGraphiteRequest({method: 'GET', url: '/metrics/find/?query=' + interpolated })
  163. .then(function(results) {
  164. return _.map(results.data, function(metric) {
  165. return {
  166. text: metric.text,
  167. expandable: metric.expandable ? true : false
  168. };
  169. });
  170. });
  171. };
  172. this.testDatasource = function() {
  173. return this.metricFindQuery('*').then(function () {
  174. return { status: "success", message: "Data source is working", title: "Success" };
  175. });
  176. };
  177. this.listDashboards = function(query) {
  178. return this.doGraphiteRequest({ method: 'GET', url: '/dashboard/find/', params: {query: query || ''} })
  179. .then(function(results) {
  180. return results.data.dashboards;
  181. });
  182. };
  183. this.loadDashboard = function(dashName) {
  184. return this.doGraphiteRequest({method: 'GET', url: '/dashboard/load/' + encodeURIComponent(dashName) });
  185. };
  186. this.doGraphiteRequest = function(options) {
  187. if (this.basicAuth || this.withCredentials) {
  188. options.withCredentials = true;
  189. }
  190. if (this.basicAuth) {
  191. options.headers = options.headers || {};
  192. options.headers.Authorization = this.basicAuth;
  193. }
  194. options.url = this.url + options.url;
  195. options.inspect = { type: 'graphite' };
  196. return backendSrv.datasourceRequest(options);
  197. };
  198. this._seriesRefLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  199. this.buildGraphiteParams = function(options, scopedVars) {
  200. var graphite_options = ['from', 'until', 'rawData', 'format', 'maxDataPoints', 'cacheTimeout'];
  201. var clean_options = [], targets = {};
  202. var target, targetValue, i;
  203. var regex = /\#([A-Z])/g;
  204. var intervalFormatFixRegex = /'(\d+)m'/gi;
  205. var hasTargets = false;
  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. hasTargets = true;
  237. clean_options.push("target=" + encodeURIComponent(targetValue));
  238. }
  239. }
  240. _.each(options, function (value, key) {
  241. if ($.inArray(key, graphite_options) === -1) { return; }
  242. if (value) {
  243. clean_options.push(key + "=" + encodeURIComponent(value));
  244. }
  245. });
  246. if (!hasTargets) {
  247. return [];
  248. }
  249. return clean_options;
  250. };
  251. }
  252. return GraphiteDatasource;
  253. });