PromLink.tsx 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import { map } from 'lodash';
  2. import React, { FC, useEffect, useState, memo } from 'react';
  3. import { DataQueryRequest, PanelData, ScopedVars, textUtil, rangeUtil } from '@grafana/data';
  4. import { PrometheusDatasource } from '../datasource';
  5. import { PromQuery } from '../types';
  6. interface Props {
  7. datasource: PrometheusDatasource;
  8. query: PromQuery;
  9. panelData?: PanelData;
  10. }
  11. const PromLink: FC<Props> = ({ panelData, query, datasource }) => {
  12. const [href, setHref] = useState('');
  13. useEffect(() => {
  14. if (panelData) {
  15. const getExternalLink = () => {
  16. if (!panelData.request) {
  17. return '';
  18. }
  19. const {
  20. request: { range, interval, scopedVars },
  21. } = panelData;
  22. const start = datasource.getPrometheusTime(range.from, false);
  23. const end = datasource.getPrometheusTime(range.to, true);
  24. const rangeDiff = Math.ceil(end - start);
  25. const endTime = range.to.utc().format('YYYY-MM-DD HH:mm');
  26. const enrichedScopedVars: ScopedVars = {
  27. ...scopedVars,
  28. // As we support $__rate_interval variable in min step, we need add it to scopedVars
  29. ...datasource.getRateIntervalScopedVariable(
  30. rangeUtil.intervalToSeconds(interval),
  31. rangeUtil.intervalToSeconds(datasource.interval)
  32. ),
  33. };
  34. const options = {
  35. interval,
  36. scopedVars: enrichedScopedVars,
  37. } as DataQueryRequest<PromQuery>;
  38. const customQueryParameters: { [key: string]: string } = {};
  39. if (datasource.customQueryParameters) {
  40. for (const [k, v] of datasource.customQueryParameters) {
  41. customQueryParameters[k] = v;
  42. }
  43. }
  44. const queryOptions = datasource.createQuery(query, options, start, end);
  45. const expr = {
  46. ...customQueryParameters,
  47. 'g0.expr': queryOptions.expr,
  48. 'g0.range_input': rangeDiff + 's',
  49. 'g0.end_input': endTime,
  50. 'g0.step_input': queryOptions.step,
  51. 'g0.tab': 0,
  52. };
  53. const args = map(expr, (v: string, k: string) => {
  54. return k + '=' + encodeURIComponent(v);
  55. }).join('&');
  56. return `${datasource.directUrl}/graph?${args}`;
  57. };
  58. setHref(getExternalLink());
  59. }
  60. }, [datasource, panelData, query]);
  61. return (
  62. <a href={textUtil.sanitizeUrl(href)} target="_blank" rel="noopener noreferrer">
  63. Prometheus
  64. </a>
  65. );
  66. };
  67. export default memo(PromLink);