QueriesTab.tsx 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. // Libraries
  2. import React, { SFC, PureComponent } from 'react';
  3. import Remarkable from 'remarkable';
  4. import _ from 'lodash';
  5. // Components
  6. import DataSourceOption from './DataSourceOption';
  7. import { EditorTabBody } from './EditorTabBody';
  8. import { DataSourcePicker } from './DataSourcePicker';
  9. import { QueryInspector } from './QueryInspector';
  10. import { TimeRangeOptions } from './TimeRangeOptions';
  11. import './../../panel/metrics_tab';
  12. import { AngularQueryComponentScope } from 'app/features/panel/metrics_tab';
  13. // Services
  14. import { getDatasourceSrv } from 'app/features/plugins/datasource_srv';
  15. import { getBackendSrv, BackendSrv } from 'app/core/services/backend_srv';
  16. import { getAngularLoader, AngularComponent } from 'app/core/services/AngularLoader';
  17. import config from 'app/core/config';
  18. // Types
  19. import { PanelModel } from '../panel_model';
  20. import { DashboardModel } from '../dashboard_model';
  21. import { DataSourceSelectItem, DataQuery } from 'app/types';
  22. interface Props {
  23. panel: PanelModel;
  24. dashboard: DashboardModel;
  25. }
  26. interface State {
  27. currentDS: DataSourceSelectItem;
  28. helpContent: JSX.Element;
  29. isLoadingHelp: boolean;
  30. isPickerOpen: boolean;
  31. isAddingMixed: boolean;
  32. }
  33. interface LoadingPlaceholderProps {
  34. text: string;
  35. }
  36. const LoadingPlaceholder: SFC<LoadingPlaceholderProps> = ({ text }) => <h2>{text}</h2>;
  37. export class QueriesTab extends PureComponent<Props, State> {
  38. element: HTMLElement;
  39. component: AngularComponent;
  40. datasources: DataSourceSelectItem[] = getDatasourceSrv().getMetricSources();
  41. backendSrv: BackendSrv = getBackendSrv();
  42. constructor(props) {
  43. super(props);
  44. const { panel } = props;
  45. this.state = {
  46. currentDS: this.datasources.find(datasource => datasource.value === panel.datasource),
  47. isLoadingHelp: false,
  48. helpContent: null,
  49. isPickerOpen: false,
  50. isAddingMixed: false,
  51. };
  52. }
  53. getAngularQueryComponentScope(): AngularQueryComponentScope {
  54. const { panel, dashboard } = this.props;
  55. return {
  56. panel: panel,
  57. dashboard: dashboard,
  58. refresh: () => panel.refresh(),
  59. render: () => panel.render,
  60. addQuery: this.onAddQuery,
  61. moveQuery: this.onMoveQuery,
  62. removeQuery: this.onRemoveQuery,
  63. events: panel.events,
  64. };
  65. }
  66. componentDidMount() {
  67. if (!this.element) {
  68. return;
  69. }
  70. const loader = getAngularLoader();
  71. const template = '<metrics-tab />';
  72. const scopeProps = {
  73. ctrl: this.getAngularQueryComponentScope(),
  74. };
  75. this.component = loader.load(this.element, scopeProps, template);
  76. }
  77. componentWillUnmount() {
  78. if (this.component) {
  79. this.component.destroy();
  80. }
  81. }
  82. onChangeDataSource = datasource => {
  83. const { panel } = this.props;
  84. const { currentDS } = this.state;
  85. // switching to mixed
  86. if (datasource.meta.mixed) {
  87. panel.targets.forEach(target => {
  88. target.datasource = panel.datasource;
  89. if (!target.datasource) {
  90. target.datasource = config.defaultDatasource;
  91. }
  92. });
  93. } else if (currentDS) {
  94. // if switching from mixed
  95. if (currentDS.meta.mixed) {
  96. for (const target of panel.targets) {
  97. delete target.datasource;
  98. }
  99. } else if (currentDS.meta.id !== datasource.meta.id) {
  100. // we are changing data source type, clear queries
  101. panel.targets = [{ refId: 'A' }];
  102. }
  103. }
  104. panel.datasource = datasource.value;
  105. panel.refresh();
  106. this.setState({
  107. currentDS: datasource,
  108. });
  109. };
  110. loadHelp = () => {
  111. const { currentDS } = this.state;
  112. const hasHelp = currentDS.meta.hasQueryHelp;
  113. if (hasHelp) {
  114. this.setState({
  115. helpContent: <h3>Loading help...</h3>,
  116. isLoadingHelp: true,
  117. });
  118. this.backendSrv
  119. .get(`/api/plugins/${currentDS.meta.id}/markdown/query_help`)
  120. .then(res => {
  121. const md = new Remarkable();
  122. const helpHtml = md.render(res);
  123. this.setState({
  124. helpContent: <div className="markdown-html" dangerouslySetInnerHTML={{ __html: helpHtml }} />,
  125. isLoadingHelp: false,
  126. });
  127. })
  128. .catch(() => {
  129. this.setState({
  130. helpContent: <h3>'Error occured when loading help'</h3>,
  131. isLoadingHelp: false,
  132. });
  133. });
  134. }
  135. };
  136. renderOptions = close => {
  137. const { currentDS } = this.state;
  138. const { queryOptions } = currentDS.meta;
  139. const { panel } = this.props;
  140. const onChangeFn = (panelKey: string) => {
  141. return (value: string | number) => {
  142. panel[panelKey] = value;
  143. panel.refresh();
  144. };
  145. };
  146. const allOptions = {
  147. cacheTimeout: {
  148. label: 'Cache timeout',
  149. placeholder: '60',
  150. name: 'cacheTimeout',
  151. value: panel.cacheTimeout,
  152. tooltipInfo: (
  153. <>
  154. If your time series store has a query cache this option can override the default cache timeout. Specify a
  155. numeric value in seconds.
  156. </>
  157. ),
  158. },
  159. maxDataPoints: {
  160. label: 'Max data points',
  161. placeholder: 'auto',
  162. name: 'maxDataPoints',
  163. value: panel.maxDataPoints,
  164. tooltipInfo: (
  165. <>
  166. The maximum data points the query should return. For graphs this is automatically set to one data point per
  167. pixel.
  168. </>
  169. ),
  170. },
  171. minInterval: {
  172. label: 'Min time interval',
  173. placeholder: '0',
  174. name: 'minInterval',
  175. value: panel.interval,
  176. panelKey: 'interval',
  177. tooltipInfo: (
  178. <>
  179. A lower limit for the auto group by time interval. Recommended to be set to write frequency, for example{' '}
  180. <code>1m</code> if your data is written every minute. Access auto interval via variable{' '}
  181. <code>$__interval</code> for time range string and <code>$__interval_ms</code> for numeric variable that can
  182. be used in math expressions.
  183. </>
  184. ),
  185. },
  186. };
  187. const dsOptions = queryOptions
  188. ? Object.keys(queryOptions).map(key => {
  189. const options = allOptions[key];
  190. return <DataSourceOption key={key} {...options} onChange={onChangeFn(allOptions[key].panelKey || key)} />;
  191. })
  192. : null;
  193. return (
  194. <>
  195. <TimeRangeOptions panel={this.props.panel} />
  196. {dsOptions}
  197. </>
  198. );
  199. };
  200. renderQueryInspector = () => {
  201. const { panel } = this.props;
  202. return <QueryInspector panel={panel} LoadingPlaceholder={LoadingPlaceholder} />;
  203. };
  204. renderHelp = () => {
  205. const { helpContent, isLoadingHelp } = this.state;
  206. return isLoadingHelp ? <LoadingPlaceholder text="Loading help..." /> : helpContent;
  207. };
  208. onAddQuery = (query?: Partial<DataQuery>) => {
  209. this.props.panel.addQuery(query);
  210. this.forceUpdate();
  211. };
  212. onAddQueryClick = () => {
  213. if (this.state.currentDS.meta.mixed) {
  214. this.setState({ isAddingMixed: true });
  215. return;
  216. }
  217. this.props.panel.addQuery();
  218. this.component.digest();
  219. this.forceUpdate();
  220. };
  221. onRemoveQuery = (query: DataQuery) => {
  222. const { panel } = this.props;
  223. const index = _.indexOf(panel.targets, query);
  224. panel.targets.splice(index, 1);
  225. panel.refresh();
  226. this.forceUpdate();
  227. };
  228. onMoveQuery = (query: DataQuery, direction: number) => {
  229. const { panel } = this.props;
  230. const index = _.indexOf(panel.targets, query);
  231. _.move(panel.targets, index, index + direction);
  232. this.forceUpdate();
  233. };
  234. renderToolbar = () => {
  235. const { currentDS } = this.state;
  236. return (
  237. <DataSourcePicker
  238. datasources={this.datasources}
  239. onChangeDataSource={this.onChangeDataSource}
  240. current={currentDS}
  241. />
  242. );
  243. };
  244. renderMixedPicker = () => {
  245. return (
  246. <DataSourcePicker
  247. datasources={this.datasources}
  248. onChangeDataSource={this.onAddMixedQuery}
  249. current={null}
  250. autoFocus={true}
  251. onBlur={this.onMixedPickerBlur}
  252. />
  253. );
  254. };
  255. onAddMixedQuery = datasource => {
  256. this.onAddQuery({ datasource: datasource.name });
  257. this.component.digest();
  258. this.setState({ isAddingMixed: false });
  259. };
  260. onMixedPickerBlur = () => {
  261. this.setState({ isAddingMixed: false });
  262. };
  263. render() {
  264. const { panel } = this.props;
  265. const { currentDS, isAddingMixed } = this.state;
  266. const { hasQueryHelp } = currentDS.meta;
  267. const queryInspector = {
  268. title: 'Query Inspector',
  269. render: this.renderQueryInspector,
  270. };
  271. const dsHelp = {
  272. title: '',
  273. icon: 'fa fa-question',
  274. disabled: !hasQueryHelp,
  275. onClick: this.loadHelp,
  276. render: this.renderHelp,
  277. };
  278. const options = {
  279. title: 'Time Range',
  280. icon: '',
  281. disabled: false,
  282. render: this.renderOptions,
  283. };
  284. return (
  285. <EditorTabBody
  286. heading="Queries"
  287. renderToolbar={this.renderToolbar}
  288. toolbarItems={[options, queryInspector, dsHelp]}
  289. >
  290. <div className="query-editor-rows gf-form-group">
  291. <div ref={element => (this.element = element)} />
  292. <div className="gf-form-query">
  293. <div className="gf-form gf-form-query-letter-cell">
  294. <label className="gf-form-label">
  295. <span className="gf-form-query-letter-cell-carret muted">
  296. <i className="fa fa-caret-down" />
  297. </span>
  298. <span className="gf-form-query-letter-cell-letter">{panel.getNextQueryLetter()}</span>
  299. </label>
  300. {!isAddingMixed && (
  301. <button className="btn btn-secondary gf-form-btn" onClick={this.onAddQueryClick}>
  302. Add Query
  303. </button>
  304. )}
  305. {isAddingMixed && this.renderMixedPicker()}
  306. </div>
  307. </div>
  308. </div>
  309. </EditorTabBody>
  310. );
  311. }
  312. }