datasource.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. import _ from 'lodash';
  2. import * as dateMath from 'app/core/utils/datemath';
  3. import { isVersionGtOrEq, SemVersion } from 'app/core/utils/version';
  4. import gfunc from './gfunc';
  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.funcDefs = null;
  16. this.funcDefsPromise = null;
  17. this.getQueryOptionsInfo = function() {
  18. return {
  19. maxDataPoints: true,
  20. cacheTimeout: true,
  21. links: [
  22. {
  23. text: 'Help',
  24. url: 'http://docs.grafana.org/features/datasources/graphite/#using-graphite-in-grafana',
  25. },
  26. ],
  27. };
  28. };
  29. this.query = function(options) {
  30. var graphOptions = {
  31. from: this.translateTime(options.rangeRaw.from, false),
  32. until: this.translateTime(options.rangeRaw.to, true),
  33. targets: options.targets,
  34. format: options.format,
  35. cacheTimeout: options.cacheTimeout || this.cacheTimeout,
  36. maxDataPoints: options.maxDataPoints,
  37. };
  38. var params = this.buildGraphiteParams(graphOptions, options.scopedVars);
  39. if (params.length === 0) {
  40. return $q.when({ data: [] });
  41. }
  42. var httpOptions: any = {
  43. method: 'POST',
  44. url: '/render',
  45. data: params.join('&'),
  46. headers: {
  47. 'Content-Type': 'application/x-www-form-urlencoded',
  48. },
  49. };
  50. this.addTracingHeaders(httpOptions, options);
  51. if (options.panelId) {
  52. httpOptions.requestId = this.name + '.panelId.' + options.panelId;
  53. }
  54. return this.doGraphiteRequest(httpOptions).then(this.convertDataPointsToMs);
  55. };
  56. this.addTracingHeaders = function(httpOptions, options) {
  57. var proxyMode = !this.url.match(/^http/);
  58. if (proxyMode) {
  59. httpOptions.headers['X-Dashboard-Id'] = options.dashboardId;
  60. httpOptions.headers['X-Panel-Id'] = options.panelId;
  61. }
  62. };
  63. this.convertDataPointsToMs = function(result) {
  64. if (!result || !result.data) {
  65. return [];
  66. }
  67. for (var i = 0; i < result.data.length; i++) {
  68. var series = result.data[i];
  69. for (var y = 0; y < series.datapoints.length; y++) {
  70. series.datapoints[y][1] *= 1000;
  71. }
  72. }
  73. return result;
  74. };
  75. this.parseTags = function(tagString) {
  76. let tags = [];
  77. tags = tagString.split(',');
  78. if (tags.length === 1) {
  79. tags = tagString.split(' ');
  80. if (tags[0] === '') {
  81. tags = [];
  82. }
  83. }
  84. return tags;
  85. };
  86. this.annotationQuery = function(options) {
  87. // Graphite metric as annotation
  88. if (options.annotation.target) {
  89. var target = templateSrv.replace(options.annotation.target, {}, 'glob');
  90. var graphiteQuery = {
  91. rangeRaw: options.rangeRaw,
  92. targets: [{ target: target }],
  93. format: 'json',
  94. maxDataPoints: 100,
  95. };
  96. return this.query(graphiteQuery).then(function(result) {
  97. var list = [];
  98. for (var i = 0; i < result.data.length; i++) {
  99. var target = result.data[i];
  100. for (var y = 0; y < target.datapoints.length; y++) {
  101. var datapoint = target.datapoints[y];
  102. if (!datapoint[0]) {
  103. continue;
  104. }
  105. list.push({
  106. annotation: options.annotation,
  107. time: datapoint[1],
  108. title: target.target,
  109. });
  110. }
  111. }
  112. return list;
  113. });
  114. } else {
  115. // Graphite event as annotation
  116. var tags = templateSrv.replace(options.annotation.tags);
  117. return this.events({ range: options.rangeRaw, tags: tags }).then(results => {
  118. var list = [];
  119. for (var i = 0; i < results.data.length; i++) {
  120. var e = results.data[i];
  121. var tags = e.tags;
  122. if (_.isString(e.tags)) {
  123. tags = this.parseTags(e.tags);
  124. }
  125. list.push({
  126. annotation: options.annotation,
  127. time: e.when * 1000,
  128. title: e.what,
  129. tags: tags,
  130. text: e.data,
  131. });
  132. }
  133. return list;
  134. });
  135. }
  136. };
  137. this.events = function(options) {
  138. try {
  139. var tags = '';
  140. if (options.tags) {
  141. tags = '&tags=' + options.tags;
  142. }
  143. return this.doGraphiteRequest({
  144. method: 'GET',
  145. url:
  146. '/events/get_data?from=' +
  147. this.translateTime(options.range.from, false) +
  148. '&until=' +
  149. this.translateTime(options.range.to, true) +
  150. tags,
  151. });
  152. } catch (err) {
  153. return $q.reject(err);
  154. }
  155. };
  156. this.targetContainsTemplate = function(target) {
  157. return templateSrv.variableExists(target.target);
  158. };
  159. this.translateTime = function(date, roundUp) {
  160. if (_.isString(date)) {
  161. if (date === 'now') {
  162. return 'now';
  163. } else if (date.indexOf('now-') >= 0 && date.indexOf('/') === -1) {
  164. date = date.substring(3);
  165. date = date.replace('m', 'min');
  166. date = date.replace('M', 'mon');
  167. return date;
  168. }
  169. date = dateMath.parse(date, roundUp);
  170. }
  171. // graphite' s from filter is exclusive
  172. // here we step back one minute in order
  173. // to guarantee that we get all the data that
  174. // exists for the specified range
  175. if (roundUp) {
  176. if (date.get('s')) {
  177. date.add(1, 'm');
  178. }
  179. } else if (roundUp === false) {
  180. if (date.get('s')) {
  181. date.subtract(1, 'm');
  182. }
  183. }
  184. return date.unix();
  185. };
  186. this.metricFindQuery = function(query, optionalOptions) {
  187. let options = optionalOptions || {};
  188. let interpolatedQuery = templateSrv.replace(query);
  189. // special handling for tag_values(<tag>[,<expression>]*), this is used for template variables
  190. let matches = interpolatedQuery.match(/^tag_values\(([^,]+)((, *[^,]+)*)\)$/);
  191. if (matches) {
  192. const expressions = [];
  193. const exprRegex = /, *([^,]+)/g;
  194. let match;
  195. while ((match = exprRegex.exec(matches[2])) !== null) {
  196. expressions.push(match[1]);
  197. }
  198. options.limit = 10000;
  199. return this.getTagValuesAutoComplete(expressions, matches[1], undefined, options);
  200. }
  201. // special handling for tags(<expression>[,<expression>]*), this is used for template variables
  202. matches = interpolatedQuery.match(/^tags\(([^,]*)((, *[^,]+)*)\)$/);
  203. if (matches) {
  204. const expressions = [];
  205. if (matches[1]) {
  206. expressions.push(matches[1]);
  207. const exprRegex = /, *([^,]+)/g;
  208. let match;
  209. while ((match = exprRegex.exec(matches[2])) !== null) {
  210. expressions.push(match[1]);
  211. }
  212. }
  213. options.limit = 10000;
  214. return this.getTagsAutoComplete(expressions, undefined, options);
  215. }
  216. let httpOptions: any = {
  217. method: 'GET',
  218. url: '/metrics/find',
  219. params: {
  220. query: interpolatedQuery,
  221. },
  222. // for cancellations
  223. requestId: options.requestId,
  224. };
  225. if (options.range) {
  226. httpOptions.params.from = this.translateTime(options.range.from, false);
  227. httpOptions.params.until = this.translateTime(options.range.to, true);
  228. }
  229. return this.doGraphiteRequest(httpOptions).then(results => {
  230. return _.map(results.data, metric => {
  231. return {
  232. text: metric.text,
  233. expandable: metric.expandable ? true : false,
  234. };
  235. });
  236. });
  237. };
  238. this.getTags = function(optionalOptions) {
  239. let options = optionalOptions || {};
  240. let httpOptions: any = {
  241. method: 'GET',
  242. url: '/tags',
  243. // for cancellations
  244. requestId: options.requestId,
  245. };
  246. if (options.range) {
  247. httpOptions.params.from = this.translateTime(options.range.from, false);
  248. httpOptions.params.until = this.translateTime(options.range.to, true);
  249. }
  250. return this.doGraphiteRequest(httpOptions).then(results => {
  251. return _.map(results.data, tag => {
  252. return {
  253. text: tag.tag,
  254. id: tag.id,
  255. };
  256. });
  257. });
  258. };
  259. this.getTagValues = function(tag, optionalOptions) {
  260. let options = optionalOptions || {};
  261. let httpOptions: any = {
  262. method: 'GET',
  263. url: '/tags/' + templateSrv.replace(tag),
  264. // for cancellations
  265. requestId: options.requestId,
  266. };
  267. if (options.range) {
  268. httpOptions.params.from = this.translateTime(options.range.from, false);
  269. httpOptions.params.until = this.translateTime(options.range.to, true);
  270. }
  271. return this.doGraphiteRequest(httpOptions).then(results => {
  272. if (results.data && results.data.values) {
  273. return _.map(results.data.values, value => {
  274. return {
  275. text: value.value,
  276. id: value.id,
  277. };
  278. });
  279. } else {
  280. return [];
  281. }
  282. });
  283. };
  284. this.getTagsAutoComplete = (expressions, tagPrefix, optionalOptions) => {
  285. let options = optionalOptions || {};
  286. let httpOptions: any = {
  287. method: 'GET',
  288. url: '/tags/autoComplete/tags',
  289. params: {
  290. expr: _.map(expressions, expression => templateSrv.replace((expression || '').trim())),
  291. },
  292. // for cancellations
  293. requestId: options.requestId,
  294. };
  295. if (tagPrefix) {
  296. httpOptions.params.tagPrefix = tagPrefix;
  297. }
  298. if (options.limit) {
  299. httpOptions.params.limit = options.limit;
  300. }
  301. if (options.range) {
  302. httpOptions.params.from = this.translateTime(options.range.from, false);
  303. httpOptions.params.until = this.translateTime(options.range.to, true);
  304. }
  305. return this.doGraphiteRequest(httpOptions).then(results => {
  306. if (results.data) {
  307. return _.map(results.data, tag => {
  308. return { text: tag };
  309. });
  310. } else {
  311. return [];
  312. }
  313. });
  314. };
  315. this.getTagValuesAutoComplete = (expressions, tag, valuePrefix, optionalOptions) => {
  316. let options = optionalOptions || {};
  317. let httpOptions: any = {
  318. method: 'GET',
  319. url: '/tags/autoComplete/values',
  320. params: {
  321. expr: _.map(expressions, expression => templateSrv.replace((expression || '').trim())),
  322. tag: templateSrv.replace((tag || '').trim()),
  323. },
  324. // for cancellations
  325. requestId: options.requestId,
  326. };
  327. if (valuePrefix) {
  328. httpOptions.params.valuePrefix = valuePrefix;
  329. }
  330. if (options.limit) {
  331. httpOptions.params.limit = options.limit;
  332. }
  333. if (options.range) {
  334. httpOptions.params.from = this.translateTime(options.range.from, false);
  335. httpOptions.params.until = this.translateTime(options.range.to, true);
  336. }
  337. return this.doGraphiteRequest(httpOptions).then(results => {
  338. if (results.data) {
  339. return _.map(results.data, value => {
  340. return { text: value };
  341. });
  342. } else {
  343. return [];
  344. }
  345. });
  346. };
  347. this.getVersion = function(optionalOptions) {
  348. let options = optionalOptions || {};
  349. let httpOptions = {
  350. method: 'GET',
  351. url: '/version',
  352. requestId: options.requestId,
  353. };
  354. return this.doGraphiteRequest(httpOptions)
  355. .then(results => {
  356. if (results.data) {
  357. let semver = new SemVersion(results.data);
  358. return semver.isValid() ? results.data : '';
  359. }
  360. return '';
  361. })
  362. .catch(() => {
  363. return '';
  364. });
  365. };
  366. this.createFuncInstance = function(funcDef, options?) {
  367. return gfunc.createFuncInstance(funcDef, options, this.funcDefs);
  368. };
  369. this.getFuncDef = function(name) {
  370. return gfunc.getFuncDef(name, this.funcDefs);
  371. };
  372. this.waitForFuncDefsLoaded = function() {
  373. return this.getFuncDefs();
  374. };
  375. this.getFuncDefs = function() {
  376. if (this.funcDefsPromise !== null) {
  377. return this.funcDefsPromise;
  378. }
  379. if (!supportsFunctionIndex(this.graphiteVersion)) {
  380. this.funcDefs = gfunc.getFuncDefs(this.graphiteVersion);
  381. this.funcDefsPromise = Promise.resolve(this.funcDefs);
  382. return this.funcDefsPromise;
  383. }
  384. let httpOptions = {
  385. method: 'GET',
  386. url: '/functions',
  387. };
  388. this.funcDefsPromise = this.doGraphiteRequest(httpOptions)
  389. .then(results => {
  390. if (results.status !== 200 || typeof results.data !== 'object') {
  391. this.funcDefs = gfunc.getFuncDefs(this.graphiteVersion);
  392. } else {
  393. this.funcDefs = gfunc.parseFuncDefs(results.data);
  394. }
  395. return this.funcDefs;
  396. })
  397. .catch(err => {
  398. console.log('Fetching graphite functions error', err);
  399. this.funcDefs = gfunc.getFuncDefs(this.graphiteVersion);
  400. return this.funcDefs;
  401. });
  402. return this.funcDefsPromise;
  403. };
  404. this.testDatasource = function() {
  405. let query = {
  406. panelId: 3,
  407. rangeRaw: { from: 'now-1h', to: 'now' },
  408. targets: [{ target: 'constantLine(100)' }],
  409. maxDataPoints: 300,
  410. };
  411. return this.query(query).then(function() {
  412. return { status: 'success', message: 'Data source is working' };
  413. });
  414. };
  415. this.doGraphiteRequest = function(options) {
  416. if (this.basicAuth || this.withCredentials) {
  417. options.withCredentials = true;
  418. }
  419. if (this.basicAuth) {
  420. options.headers = options.headers || {};
  421. options.headers.Authorization = this.basicAuth;
  422. }
  423. options.url = this.url + options.url;
  424. options.inspect = { type: 'graphite' };
  425. return backendSrv.datasourceRequest(options);
  426. };
  427. this._seriesRefLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  428. this.buildGraphiteParams = function(options, scopedVars) {
  429. var graphite_options = ['from', 'until', 'rawData', 'format', 'maxDataPoints', 'cacheTimeout'];
  430. var clean_options = [],
  431. targets = {};
  432. var target, targetValue, i;
  433. var regex = /\#([A-Z])/g;
  434. var intervalFormatFixRegex = /'(\d+)m'/gi;
  435. var hasTargets = false;
  436. options['format'] = 'json';
  437. function fixIntervalFormat(match) {
  438. return match.replace('m', 'min').replace('M', 'mon');
  439. }
  440. for (i = 0; i < options.targets.length; i++) {
  441. target = options.targets[i];
  442. if (!target.target) {
  443. continue;
  444. }
  445. if (!target.refId) {
  446. target.refId = this._seriesRefLetters[i];
  447. }
  448. targetValue = templateSrv.replace(target.target, scopedVars);
  449. targetValue = targetValue.replace(intervalFormatFixRegex, fixIntervalFormat);
  450. targets[target.refId] = targetValue;
  451. }
  452. function nestedSeriesRegexReplacer(match, g1) {
  453. return targets[g1] || match;
  454. }
  455. for (i = 0; i < options.targets.length; i++) {
  456. target = options.targets[i];
  457. if (!target.target) {
  458. continue;
  459. }
  460. targetValue = targets[target.refId];
  461. targetValue = targetValue.replace(regex, nestedSeriesRegexReplacer);
  462. targets[target.refId] = targetValue;
  463. if (!target.hide) {
  464. hasTargets = true;
  465. clean_options.push('target=' + encodeURIComponent(targetValue));
  466. }
  467. }
  468. _.each(options, function(value, key) {
  469. if (_.indexOf(graphite_options, key) === -1) {
  470. return;
  471. }
  472. if (value) {
  473. clean_options.push(key + '=' + encodeURIComponent(value));
  474. }
  475. });
  476. if (!hasTargets) {
  477. return [];
  478. }
  479. return clean_options;
  480. };
  481. }
  482. function supportsTags(version: string): boolean {
  483. return isVersionGtOrEq(version, '1.1');
  484. }
  485. function supportsFunctionIndex(version: string): boolean {
  486. return isVersionGtOrEq(version, '1.1');
  487. }