datasource.ts 11 KB

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