datasource.ts 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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.getTags = function(optionalOptions) {
  192. let options = optionalOptions || {};
  193. let httpOptions: any = {
  194. method: 'GET',
  195. url: '/tags',
  196. // for cancellations
  197. requestId: options.requestId,
  198. };
  199. if (options && options.range) {
  200. httpOptions.params.from = this.translateTime(options.range.from, false);
  201. httpOptions.params.until = this.translateTime(options.range.to, true);
  202. }
  203. return this.doGraphiteRequest(httpOptions).then(results => {
  204. return _.map(results.data, tag => {
  205. return {
  206. text: tag.tag,
  207. id: tag.id
  208. };
  209. });
  210. });
  211. };
  212. this.getTagValues = function(tag, optionalOptions) {
  213. let options = optionalOptions || {};
  214. let httpOptions: any = {
  215. method: 'GET',
  216. url: '/tags/' + tag,
  217. // for cancellations
  218. requestId: options.requestId,
  219. };
  220. if (options && options.range) {
  221. httpOptions.params.from = this.translateTime(options.range.from, false);
  222. httpOptions.params.until = this.translateTime(options.range.to, true);
  223. }
  224. return this.doGraphiteRequest(httpOptions).then(results => {
  225. if (results.data && results.data.values) {
  226. return _.map(results.data.values, value => {
  227. return {
  228. text: value.value,
  229. id: value.id
  230. };
  231. });
  232. } else {
  233. return [];
  234. }
  235. });
  236. };
  237. this.testDatasource = function() {
  238. return this.metricFindQuery('*').then(function () {
  239. return { status: "success", message: "Data source is working"};
  240. });
  241. };
  242. this.doGraphiteRequest = function(options) {
  243. if (this.basicAuth || this.withCredentials) {
  244. options.withCredentials = true;
  245. }
  246. if (this.basicAuth) {
  247. options.headers = options.headers || {};
  248. options.headers.Authorization = this.basicAuth;
  249. }
  250. options.url = this.url + options.url;
  251. options.inspect = {type: 'graphite'};
  252. return backendSrv.datasourceRequest(options);
  253. };
  254. this._seriesRefLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  255. this.buildGraphiteParams = function(options, scopedVars) {
  256. var graphite_options = ['from', 'until', 'rawData', 'format', 'maxDataPoints', 'cacheTimeout'];
  257. var clean_options = [], targets = {};
  258. var target, targetValue, i;
  259. var regex = /\#([A-Z])/g;
  260. var intervalFormatFixRegex = /'(\d+)m'/gi;
  261. var hasTargets = false;
  262. options['format'] = 'json';
  263. function fixIntervalFormat(match) {
  264. return match.replace('m', 'min').replace('M', 'mon');
  265. }
  266. for (i = 0; i < options.targets.length; i++) {
  267. target = options.targets[i];
  268. if (!target.target) {
  269. continue;
  270. }
  271. if (!target.refId) {
  272. target.refId = this._seriesRefLetters[i];
  273. }
  274. targetValue = templateSrv.replace(target.target, scopedVars);
  275. targetValue = targetValue.replace(intervalFormatFixRegex, fixIntervalFormat);
  276. targets[target.refId] = targetValue;
  277. }
  278. function nestedSeriesRegexReplacer(match, g1) {
  279. return targets[g1] || match;
  280. }
  281. for (i = 0; i < options.targets.length; i++) {
  282. target = options.targets[i];
  283. if (!target.target) {
  284. continue;
  285. }
  286. targetValue = targets[target.refId];
  287. targetValue = targetValue.replace(regex, nestedSeriesRegexReplacer);
  288. targets[target.refId] = targetValue;
  289. if (!target.hide) {
  290. hasTargets = true;
  291. clean_options.push("target=" + encodeURIComponent(targetValue));
  292. }
  293. }
  294. _.each(options, function (value, key) {
  295. if (_.indexOf(graphite_options, key) === -1) { return; }
  296. if (value) {
  297. clean_options.push(key + "=" + encodeURIComponent(value));
  298. }
  299. });
  300. if (!hasTargets) {
  301. return [];
  302. }
  303. return clean_options;
  304. };
  305. }