datasource.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. ///<reference path="../../../headers/common.d.ts" />
  2. import _ from 'lodash';
  3. import * as dateMath from 'app/core/utils/datemath';
  4. import { isVersionGtOrEq, SemVersion } from 'app/core/utils/version';
  5. /** @ngInject */
  6. export function GraphiteDatasource(
  7. instanceSettings,
  8. $q,
  9. backendSrv,
  10. templateSrv
  11. ) {
  12. this.basicAuth = instanceSettings.basicAuth;
  13. this.url = instanceSettings.url;
  14. this.name = instanceSettings.name;
  15. this.graphiteVersion = instanceSettings.jsonData.graphiteVersion || '0.9';
  16. this.supportsTags = supportsTags(this.graphiteVersion);
  17. this.cacheTimeout = instanceSettings.cacheTimeout;
  18. this.withCredentials = instanceSettings.withCredentials;
  19. this.render_method = instanceSettings.render_method || 'POST';
  20. this.getQueryOptionsInfo = function() {
  21. return {
  22. maxDataPoints: true,
  23. cacheTimeout: true,
  24. links: [
  25. {
  26. text: 'Help',
  27. url:
  28. 'http://docs.grafana.org/features/datasources/graphite/#using-graphite-in-grafana',
  29. },
  30. ],
  31. };
  32. };
  33. this.query = function(options) {
  34. var graphOptions = {
  35. from: this.translateTime(options.rangeRaw.from, false),
  36. until: this.translateTime(options.rangeRaw.to, true),
  37. targets: options.targets,
  38. format: options.format,
  39. cacheTimeout: options.cacheTimeout || this.cacheTimeout,
  40. maxDataPoints: options.maxDataPoints,
  41. };
  42. var params = this.buildGraphiteParams(graphOptions, options.scopedVars);
  43. if (params.length === 0) {
  44. return $q.when({ data: [] });
  45. }
  46. var httpOptions: any = {
  47. method: 'POST',
  48. url: '/render',
  49. data: params.join('&'),
  50. headers: {
  51. 'Content-Type': 'application/x-www-form-urlencoded',
  52. },
  53. };
  54. if (options.panelId) {
  55. httpOptions.requestId = this.name + '.panelId.' + options.panelId;
  56. }
  57. return this.doGraphiteRequest(httpOptions).then(this.convertDataPointsToMs);
  58. };
  59. this.convertDataPointsToMs = function(result) {
  60. if (!result || !result.data) {
  61. return [];
  62. }
  63. for (var i = 0; i < result.data.length; i++) {
  64. var series = result.data[i];
  65. for (var y = 0; y < series.datapoints.length; y++) {
  66. series.datapoints[y][1] *= 1000;
  67. }
  68. }
  69. return result;
  70. };
  71. this.parseTags = function(tagString) {
  72. let tags = [];
  73. tags = tagString.split(',');
  74. if (tags.length === 1) {
  75. tags = tagString.split(' ');
  76. if (tags[0] === '') {
  77. tags = [];
  78. }
  79. }
  80. return tags;
  81. };
  82. this.annotationQuery = function(options) {
  83. // Graphite metric as annotation
  84. if (options.annotation.target) {
  85. var target = templateSrv.replace(options.annotation.target, {}, 'glob');
  86. var graphiteQuery = {
  87. rangeRaw: options.rangeRaw,
  88. targets: [{ target: target }],
  89. format: 'json',
  90. maxDataPoints: 100,
  91. };
  92. return this.query(graphiteQuery).then(function(result) {
  93. var list = [];
  94. for (var i = 0; i < result.data.length; i++) {
  95. var target = result.data[i];
  96. for (var y = 0; y < target.datapoints.length; y++) {
  97. var datapoint = target.datapoints[y];
  98. if (!datapoint[0]) {
  99. continue;
  100. }
  101. list.push({
  102. annotation: options.annotation,
  103. time: datapoint[1],
  104. title: target.target,
  105. });
  106. }
  107. }
  108. return list;
  109. });
  110. } else {
  111. // Graphite event as annotation
  112. var tags = templateSrv.replace(options.annotation.tags);
  113. return this.events({ range: options.rangeRaw, tags: tags }).then(
  114. results => {
  115. var list = [];
  116. for (var i = 0; i < results.data.length; i++) {
  117. var e = results.data[i];
  118. var tags = e.tags;
  119. if (_.isString(e.tags)) {
  120. tags = this.parseTags(e.tags);
  121. }
  122. list.push({
  123. annotation: options.annotation,
  124. time: e.when * 1000,
  125. title: e.what,
  126. tags: tags,
  127. text: e.data,
  128. });
  129. }
  130. return list;
  131. }
  132. );
  133. }
  134. };
  135. this.events = function(options) {
  136. try {
  137. var tags = '';
  138. if (options.tags) {
  139. tags = '&tags=' + options.tags;
  140. }
  141. return this.doGraphiteRequest({
  142. method: 'GET',
  143. url:
  144. '/events/get_data?from=' +
  145. this.translateTime(options.range.from, false) +
  146. '&until=' +
  147. this.translateTime(options.range.to, true) +
  148. tags,
  149. });
  150. } catch (err) {
  151. return $q.reject(err);
  152. }
  153. };
  154. this.targetContainsTemplate = function(target) {
  155. return templateSrv.variableExists(target.target);
  156. };
  157. this.translateTime = function(date, roundUp) {
  158. if (_.isString(date)) {
  159. if (date === 'now') {
  160. return 'now';
  161. } else if (date.indexOf('now-') >= 0 && date.indexOf('/') === -1) {
  162. date = date.substring(3);
  163. date = date.replace('m', 'min');
  164. date = date.replace('M', 'mon');
  165. return date;
  166. }
  167. date = dateMath.parse(date, roundUp);
  168. }
  169. // graphite' s from filter is exclusive
  170. // here we step back one minute in order
  171. // to guarantee that we get all the data that
  172. // exists for the specified range
  173. if (roundUp) {
  174. if (date.get('s')) {
  175. date.add(1, 'm');
  176. }
  177. } else if (roundUp === false) {
  178. if (date.get('s')) {
  179. date.subtract(1, 'm');
  180. }
  181. }
  182. return date.unix();
  183. };
  184. this.metricFindQuery = function(query, optionalOptions) {
  185. let options = optionalOptions || {};
  186. let interpolatedQuery = templateSrv.replace(query);
  187. let httpOptions: any = {
  188. method: 'GET',
  189. url: '/metrics/find',
  190. params: {
  191. query: interpolatedQuery,
  192. },
  193. // for cancellations
  194. requestId: options.requestId,
  195. };
  196. if (options && options.range) {
  197. httpOptions.params.from = this.translateTime(options.range.from, false);
  198. httpOptions.params.until = this.translateTime(options.range.to, true);
  199. }
  200. return this.doGraphiteRequest(httpOptions).then(results => {
  201. return _.map(results.data, metric => {
  202. return {
  203. text: metric.text,
  204. expandable: metric.expandable ? true : false,
  205. };
  206. });
  207. });
  208. };
  209. this.getTags = function(optionalOptions) {
  210. let options = optionalOptions || {};
  211. let httpOptions: any = {
  212. method: 'GET',
  213. url: '/tags',
  214. // for cancellations
  215. requestId: options.requestId,
  216. };
  217. if (options && options.range) {
  218. httpOptions.params.from = this.translateTime(options.range.from, false);
  219. httpOptions.params.until = this.translateTime(options.range.to, true);
  220. }
  221. return this.doGraphiteRequest(httpOptions).then(results => {
  222. return _.map(results.data, tag => {
  223. return {
  224. text: tag.tag,
  225. id: tag.id,
  226. };
  227. });
  228. });
  229. };
  230. this.getTagValues = function(tag, optionalOptions) {
  231. let options = optionalOptions || {};
  232. let httpOptions: any = {
  233. method: 'GET',
  234. url: '/tags/' + tag,
  235. // for cancellations
  236. requestId: options.requestId,
  237. };
  238. if (options && options.range) {
  239. httpOptions.params.from = this.translateTime(options.range.from, false);
  240. httpOptions.params.until = this.translateTime(options.range.to, true);
  241. }
  242. return this.doGraphiteRequest(httpOptions).then(results => {
  243. if (results.data && results.data.values) {
  244. return _.map(results.data.values, value => {
  245. return {
  246. text: value.value,
  247. id: value.id,
  248. };
  249. });
  250. } else {
  251. return [];
  252. }
  253. });
  254. };
  255. this.getTagsAutoComplete = (expression, tagPrefix) => {
  256. let httpOptions: any = {
  257. method: 'GET',
  258. url: '/tags/autoComplete/tags',
  259. params: {
  260. expr: expression,
  261. },
  262. };
  263. if (tagPrefix) {
  264. httpOptions.params.tagPrefix = tagPrefix;
  265. }
  266. return this.doGraphiteRequest(httpOptions).then(results => {
  267. if (results.data) {
  268. return _.map(results.data, tag => {
  269. return { text: tag };
  270. });
  271. } else {
  272. return [];
  273. }
  274. });
  275. };
  276. this.getTagValuesAutoComplete = (expression, tag, valuePrefix) => {
  277. let httpOptions: any = {
  278. method: 'GET',
  279. url: '/tags/autoComplete/values',
  280. params: {
  281. expr: expression,
  282. tag: tag,
  283. },
  284. };
  285. if (valuePrefix) {
  286. httpOptions.params.valuePrefix = valuePrefix;
  287. }
  288. return this.doGraphiteRequest(httpOptions).then(results => {
  289. if (results.data) {
  290. return _.map(results.data, value => {
  291. return { text: value };
  292. });
  293. } else {
  294. return [];
  295. }
  296. });
  297. };
  298. this.getVersion = function() {
  299. let httpOptions = {
  300. method: 'GET',
  301. url: '/version/_', // Prevent last / trimming
  302. };
  303. return this.doGraphiteRequest(httpOptions)
  304. .then(results => {
  305. if (results.data) {
  306. let semver = new SemVersion(results.data);
  307. return semver.isValid() ? results.data : '';
  308. }
  309. return '';
  310. })
  311. .catch(() => {
  312. return '';
  313. });
  314. };
  315. this.testDatasource = function() {
  316. return this.metricFindQuery('*').then(function() {
  317. return { status: 'success', message: 'Data source is working' };
  318. });
  319. };
  320. this.doGraphiteRequest = function(options) {
  321. if (this.basicAuth || this.withCredentials) {
  322. options.withCredentials = true;
  323. }
  324. if (this.basicAuth) {
  325. options.headers = options.headers || {};
  326. options.headers.Authorization = this.basicAuth;
  327. }
  328. options.url = this.url + options.url;
  329. options.inspect = { type: 'graphite' };
  330. return backendSrv.datasourceRequest(options);
  331. };
  332. this._seriesRefLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  333. this.buildGraphiteParams = function(options, scopedVars) {
  334. var graphite_options = [
  335. 'from',
  336. 'until',
  337. 'rawData',
  338. 'format',
  339. 'maxDataPoints',
  340. 'cacheTimeout',
  341. ];
  342. var clean_options = [],
  343. targets = {};
  344. var target, targetValue, i;
  345. var regex = /\#([A-Z])/g;
  346. var intervalFormatFixRegex = /'(\d+)m'/gi;
  347. var hasTargets = false;
  348. options['format'] = 'json';
  349. function fixIntervalFormat(match) {
  350. return match.replace('m', 'min').replace('M', 'mon');
  351. }
  352. for (i = 0; i < options.targets.length; i++) {
  353. target = options.targets[i];
  354. if (!target.target) {
  355. continue;
  356. }
  357. if (!target.refId) {
  358. target.refId = this._seriesRefLetters[i];
  359. }
  360. targetValue = templateSrv.replace(target.target, scopedVars);
  361. targetValue = targetValue.replace(
  362. intervalFormatFixRegex,
  363. fixIntervalFormat
  364. );
  365. targets[target.refId] = targetValue;
  366. }
  367. function nestedSeriesRegexReplacer(match, g1) {
  368. return targets[g1] || match;
  369. }
  370. for (i = 0; i < options.targets.length; i++) {
  371. target = options.targets[i];
  372. if (!target.target) {
  373. continue;
  374. }
  375. targetValue = targets[target.refId];
  376. targetValue = targetValue.replace(regex, nestedSeriesRegexReplacer);
  377. targets[target.refId] = targetValue;
  378. if (!target.hide) {
  379. hasTargets = true;
  380. clean_options.push('target=' + encodeURIComponent(targetValue));
  381. }
  382. }
  383. _.each(options, function(value, key) {
  384. if (_.indexOf(graphite_options, key) === -1) {
  385. return;
  386. }
  387. if (value) {
  388. clean_options.push(key + '=' + encodeURIComponent(value));
  389. }
  390. });
  391. if (!hasTargets) {
  392. return [];
  393. }
  394. return clean_options;
  395. };
  396. }
  397. function supportsTags(version: string): boolean {
  398. return isVersionGtOrEq(version, '1.1');
  399. }