datasource.ts 8.3 KB

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