datasource.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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. /** @ngInject */
  15. function GraphiteDatasource(instanceSettings, $q, backendSrv, templateSrv) {
  16. this.basicAuth = instanceSettings.basicAuth;
  17. this.url = instanceSettings.url;
  18. this.name = instanceSettings.name;
  19. this.cacheTimeout = instanceSettings.cacheTimeout;
  20. this.withCredentials = instanceSettings.withCredentials;
  21. this.render_method = instanceSettings.render_method || 'POST';
  22. this.query = function(options) {
  23. try {
  24. var graphOptions = {
  25. from: this.translateTime(options.rangeRaw.from, false),
  26. until: this.translateTime(options.rangeRaw.to, true),
  27. targets: options.targets,
  28. format: options.format,
  29. cacheTimeout: options.cacheTimeout || this.cacheTimeout,
  30. maxDataPoints: options.maxDataPoints,
  31. };
  32. var params = this.buildGraphiteParams(graphOptions, options.scopedVars);
  33. if (params.length === 0) {
  34. return $q.when([]);
  35. }
  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. this.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. this.annotationQuery = function(options) {
  64. // Graphite metric as annotation
  65. if (options.annotation.target) {
  66. var target = templateSrv.replace(options.annotation.target);
  67. var graphiteQuery = {
  68. rangeRaw: options.rangeRaw,
  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: options.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(options.annotation.tags);
  94. return this.events({range: options.rangeRaw, tags: tags}).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: options.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. this.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. this.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. this.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. this.testDatasource = function() {
  174. return this.metricFindQuery('*').then(function () {
  175. return { status: "success", message: "Data source is working", title: "Success" };
  176. });
  177. };
  178. this.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. this.loadDashboard = function(dashName) {
  185. return this.doGraphiteRequest({method: 'GET', url: '/dashboard/load/' + encodeURIComponent(dashName) });
  186. };
  187. this.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. this._seriesRefLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  200. this.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. var hasTargets = false;
  207. if (options.format !== 'png') {
  208. options['format'] = 'json';
  209. }
  210. function fixIntervalFormat(match) {
  211. return match.replace('m', 'min').replace('M', 'mon');
  212. }
  213. for (i = 0; i < options.targets.length; i++) {
  214. target = options.targets[i];
  215. if (!target.target) {
  216. continue;
  217. }
  218. if (!target.refId) {
  219. target.refId = this._seriesRefLetters[i];
  220. }
  221. targetValue = templateSrv.replace(target.target, scopedVars);
  222. targetValue = targetValue.replace(intervalFormatFixRegex, fixIntervalFormat);
  223. targets[target.refId] = targetValue;
  224. }
  225. function nestedSeriesRegexReplacer(match, g1) {
  226. return targets[g1];
  227. }
  228. for (i = 0; i < options.targets.length; i++) {
  229. target = options.targets[i];
  230. if (!target.target) {
  231. continue;
  232. }
  233. targetValue = targets[target.refId];
  234. targetValue = targetValue.replace(regex, nestedSeriesRegexReplacer);
  235. targets[target.refId] = targetValue;
  236. if (!target.hide) {
  237. hasTargets = true;
  238. clean_options.push("target=" + encodeURIComponent(targetValue));
  239. }
  240. }
  241. _.each(options, function (value, key) {
  242. if ($.inArray(key, graphite_options) === -1) { return; }
  243. if (value) {
  244. clean_options.push(key + "=" + encodeURIComponent(value));
  245. }
  246. });
  247. if (!hasTargets) {
  248. return [];
  249. }
  250. return clean_options;
  251. };
  252. }
  253. return {
  254. Datasource: GraphiteDatasource
  255. };
  256. });