PromLink.tsx 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import _ from 'lodash';
  2. import React, { Component } from 'react';
  3. import { PrometheusDatasource } from '../datasource';
  4. import { PromQuery } from '../types';
  5. import { DataQueryRequest, PanelData } from '@grafana/ui';
  6. import { getDatasourceSrv } from 'app/features/plugins/datasource_srv';
  7. interface Props {
  8. datasource: PrometheusDatasource;
  9. query: PromQuery;
  10. panelData: PanelData;
  11. }
  12. interface State {
  13. href: string;
  14. }
  15. export default class PromLink extends Component<Props, State> {
  16. state: State = { href: null };
  17. async componentDidUpdate(prevProps: Props) {
  18. if (prevProps.panelData !== this.props.panelData && this.props.panelData.request) {
  19. const href = await this.getExternalLink();
  20. this.setState({ href });
  21. }
  22. }
  23. async getExternalLink(): Promise<string> {
  24. const { query, panelData } = this.props;
  25. const target = panelData.request.targets.length > 0 ? panelData.request.targets[0] : { datasource: null };
  26. const datasourceName = target.datasource;
  27. const datasource: PrometheusDatasource = datasourceName
  28. ? (((await getDatasourceSrv().get(datasourceName)) as any) as PrometheusDatasource)
  29. : (this.props.datasource as PrometheusDatasource);
  30. const range = panelData.request.range;
  31. const start = datasource.getPrometheusTime(range.from, false);
  32. const end = datasource.getPrometheusTime(range.to, true);
  33. const rangeDiff = Math.ceil(end - start);
  34. const endTime = range.to.utc().format('YYYY-MM-DD HH:mm');
  35. const options = {
  36. interval: panelData.request.interval,
  37. } as DataQueryRequest<PromQuery>;
  38. const queryOptions = datasource.createQuery(query, options, start, end);
  39. const expr = {
  40. 'g0.expr': queryOptions.expr,
  41. 'g0.range_input': rangeDiff + 's',
  42. 'g0.end_input': endTime,
  43. 'g0.step_input': queryOptions.step,
  44. 'g0.tab': 0,
  45. };
  46. const args = _.map(expr, (v: string, k: string) => {
  47. return k + '=' + encodeURIComponent(v);
  48. }).join('&');
  49. return `${datasource.directUrl}/graph?${args}`;
  50. }
  51. render() {
  52. const { href } = this.state;
  53. return (
  54. <a href={href} target="_blank">
  55. <i className="fa fa-share-square-o" /> Prometheus
  56. </a>
  57. );
  58. }
  59. }