datasource.ts 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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.annotationQuery = function(options) {
  62. // Graphite metric as annotation
  63. if (options.annotation.target) {
  64. var target = templateSrv.replace(options.annotation.target, {}, 'glob');
  65. var graphiteQuery = {
  66. rangeRaw: options.rangeRaw,
  67. targets: [{ target: target }],
  68. format: 'json',
  69. maxDataPoints: 100
  70. };
  71. return this.query(graphiteQuery).then(function(result) {
  72. var list = [];
  73. for (var i = 0; i < result.data.length; i++) {
  74. var target = result.data[i];
  75. for (var y = 0; y < target.datapoints.length; y++) {
  76. var datapoint = target.datapoints[y];
  77. if (!datapoint[0]) { continue; }
  78. list.push({
  79. annotation: options.annotation,
  80. time: datapoint[1],
  81. title: target.target
  82. });
  83. }
  84. }
  85. return list;
  86. });
  87. } else {
  88. // Graphite event as annotation
  89. var tags = templateSrv.replace(options.annotation.tags);
  90. return this.events({range: options.rangeRaw, tags: tags}).then(function(results) {
  91. var list = [];
  92. for (var i = 0; i < results.data.length; i++) {
  93. var e = results.data[i];
  94. list.push({
  95. annotation: options.annotation,
  96. time: e.when * 1000,
  97. title: e.what,
  98. tags: e.tags,
  99. text: e.data
  100. });
  101. }
  102. return list;
  103. });
  104. }
  105. };
  106. this.events = function(options) {
  107. try {
  108. var tags = '';
  109. if (options.tags) {
  110. tags = '&tags=' + options.tags;
  111. }
  112. return this.doGraphiteRequest({
  113. method: 'GET',
  114. url: '/events/get_data?from=' + this.translateTime(options.range.from, false) +
  115. '&until=' + this.translateTime(options.range.to, true) + tags,
  116. });
  117. } catch (err) {
  118. return $q.reject(err);
  119. }
  120. };
  121. this.targetContainsTemplate = function(target) {
  122. return templateSrv.variableExists(target.target);
  123. };
  124. this.translateTime = function(date, roundUp) {
  125. if (_.isString(date)) {
  126. if (date === 'now') {
  127. return 'now';
  128. } else if (date.indexOf('now-') >= 0 && date.indexOf('/') === -1) {
  129. date = date.substring(3);
  130. date = date.replace('m', 'min');
  131. date = date.replace('M', 'mon');
  132. return date;
  133. }
  134. date = dateMath.parse(date, roundUp);
  135. }
  136. // graphite' s from filter is exclusive
  137. // here we step back one minute in order
  138. // to guarantee that we get all the data that
  139. // exists for the specified range
  140. if (roundUp) {
  141. if (date.get('s')) {
  142. date.add(1, 'm');
  143. }
  144. } else if (roundUp === false) {
  145. if (date.get('s')) {
  146. date.subtract(1, 'm');
  147. }
  148. }
  149. return date.unix();
  150. };
  151. this.metricFindQuery = function(query, optionalOptions) {
  152. let options = optionalOptions || {};
  153. let interpolatedQuery = templateSrv.replace(query);
  154. let httpOptions: any = {
  155. method: 'GET',
  156. url: '/metrics/find',
  157. params: {
  158. query: interpolatedQuery
  159. },
  160. // for cancellations
  161. requestId: options.requestId,
  162. };
  163. if (options && options.range) {
  164. httpOptions.params.from = this.translateTime(options.range.from, false);
  165. httpOptions.params.until = this.translateTime(options.range.to, true);
  166. }
  167. return this.doGraphiteRequest(httpOptions).then(results => {
  168. return _.map(results.data, metric => {
  169. return {
  170. text: metric.text,
  171. expandable: metric.expandable ? true : false
  172. };
  173. });
  174. });
  175. };
  176. this.getTags = function(optionalOptions) {
  177. let options = optionalOptions || {};
  178. let httpOptions: any = {
  179. method: 'GET',
  180. url: '/tags',
  181. // for cancellations
  182. requestId: options.requestId,
  183. };
  184. if (options && options.range) {
  185. httpOptions.params.from = this.translateTime(options.range.from, false);
  186. httpOptions.params.until = this.translateTime(options.range.to, true);
  187. }
  188. return this.doGraphiteRequest(httpOptions).then(results => {
  189. return _.map(results.data, tag => {
  190. return {
  191. text: tag.tag,
  192. id: tag.id
  193. };
  194. });
  195. });
  196. };
  197. this.getTagValues = function(tag, optionalOptions) {
  198. let options = optionalOptions || {};
  199. let httpOptions: any = {
  200. method: 'GET',
  201. url: '/tags/' + tag,
  202. // for cancellations
  203. requestId: options.requestId,
  204. };
  205. if (options && options.range) {
  206. httpOptions.params.from = this.translateTime(options.range.from, false);
  207. httpOptions.params.until = this.translateTime(options.range.to, true);
  208. }
  209. return this.doGraphiteRequest(httpOptions).then(results => {
  210. if (results.data && results.data.values) {
  211. return _.map(results.data.values, value => {
  212. return {
  213. text: value.value,
  214. id: value.id
  215. };
  216. });
  217. } else {
  218. return [];
  219. }
  220. });
  221. };
  222. this.testDatasource = function() {
  223. return this.metricFindQuery('*').then(function () {
  224. return { status: "success", message: "Data source is working"};
  225. });
  226. };
  227. this.doGraphiteRequest = function(options) {
  228. if (this.basicAuth || this.withCredentials) {
  229. options.withCredentials = true;
  230. }
  231. if (this.basicAuth) {
  232. options.headers = options.headers || {};
  233. options.headers.Authorization = this.basicAuth;
  234. }
  235. options.url = this.url + options.url;
  236. options.inspect = {type: 'graphite'};
  237. return backendSrv.datasourceRequest(options);
  238. };
  239. this._seriesRefLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  240. this.buildGraphiteParams = function(options, scopedVars) {
  241. var graphite_options = ['from', 'until', 'rawData', 'format', 'maxDataPoints', 'cacheTimeout'];
  242. var clean_options = [], targets = {};
  243. var target, targetValue, i;
  244. var regex = /\#([A-Z])/g;
  245. var intervalFormatFixRegex = /'(\d+)m'/gi;
  246. var hasTargets = false;
  247. options['format'] = 'json';
  248. function fixIntervalFormat(match) {
  249. return match.replace('m', 'min').replace('M', 'mon');
  250. }
  251. for (i = 0; i < options.targets.length; i++) {
  252. target = options.targets[i];
  253. if (!target.target) {
  254. continue;
  255. }
  256. if (!target.refId) {
  257. target.refId = this._seriesRefLetters[i];
  258. }
  259. targetValue = templateSrv.replace(target.target, scopedVars);
  260. targetValue = targetValue.replace(intervalFormatFixRegex, fixIntervalFormat);
  261. targets[target.refId] = targetValue;
  262. }
  263. function nestedSeriesRegexReplacer(match, g1) {
  264. return targets[g1] || match;
  265. }
  266. for (i = 0; i < options.targets.length; i++) {
  267. target = options.targets[i];
  268. if (!target.target) {
  269. continue;
  270. }
  271. targetValue = targets[target.refId];
  272. targetValue = targetValue.replace(regex, nestedSeriesRegexReplacer);
  273. targets[target.refId] = targetValue;
  274. if (!target.hide) {
  275. hasTargets = true;
  276. clean_options.push("target=" + encodeURIComponent(targetValue));
  277. }
  278. }
  279. _.each(options, function (value, key) {
  280. if (_.indexOf(graphite_options, key) === -1) { return; }
  281. if (value) {
  282. clean_options.push(key + "=" + encodeURIComponent(value));
  283. }
  284. });
  285. if (!hasTargets) {
  286. return [];
  287. }
  288. return clean_options;
  289. };
  290. }