datasource.ts 11 KB

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