QueriesTab.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. import React, { SFC, PureComponent } from 'react';
  2. import DataSourceOption from './DataSourceOption';
  3. import { getAngularLoader, AngularComponent } from 'app/core/services/AngularLoader';
  4. import { EditorTabBody } from './EditorTabBody';
  5. import { DataSourcePicker } from './DataSourcePicker';
  6. import { PanelModel } from '../panel_model';
  7. import { DashboardModel } from '../dashboard_model';
  8. import './../../panel/metrics_tab';
  9. import config from 'app/core/config';
  10. import { QueryInspector } from './QueryInspector';
  11. import { Switch } from 'app/core/components/Switch/Switch';
  12. import { Input } from 'app/core/components/Form';
  13. import { InputStatus } from 'app/core/components/Form/Input';
  14. import { isValidTimeSpan } from 'app/core/utils/rangeutil';
  15. import { ValidationRule } from 'app/types';
  16. // Services
  17. import { getDatasourceSrv } from 'app/features/plugins/datasource_srv';
  18. import { getBackendSrv, BackendSrv } from 'app/core/services/backend_srv';
  19. import { DataSourceSelectItem } from 'app/types';
  20. import Remarkable from 'remarkable';
  21. interface Props {
  22. panel: PanelModel;
  23. dashboard: DashboardModel;
  24. }
  25. interface Help {
  26. isLoading: boolean;
  27. helpHtml: any;
  28. }
  29. interface State {
  30. currentDatasource: DataSourceSelectItem;
  31. help: Help;
  32. hideTimeOverride: boolean;
  33. }
  34. interface LoadingPlaceholderProps {
  35. text: string;
  36. }
  37. const LoadingPlaceholder: SFC<LoadingPlaceholderProps> = ({ text }) => <h2>{text}</h2>;
  38. const validationRules: ValidationRule[] = [
  39. {
  40. rule: value => {
  41. if (!value) {
  42. return true;
  43. }
  44. return isValidTimeSpan(value);
  45. },
  46. errorMessage: 'Not a valid timespan',
  47. },
  48. ];
  49. export class QueriesTab extends PureComponent<Props, State> {
  50. element: any;
  51. component: AngularComponent;
  52. datasources: DataSourceSelectItem[] = getDatasourceSrv().getMetricSources();
  53. backendSrv: BackendSrv = getBackendSrv();
  54. constructor(props) {
  55. super(props);
  56. const { panel } = props;
  57. this.state = {
  58. currentDatasource: this.datasources.find(datasource => datasource.value === panel.datasource),
  59. help: {
  60. isLoading: false,
  61. helpHtml: null,
  62. },
  63. hideTimeOverride: false,
  64. };
  65. }
  66. componentDidMount() {
  67. if (!this.element) {
  68. return;
  69. }
  70. const { panel, dashboard } = this.props;
  71. const loader = getAngularLoader();
  72. const template = '<metrics-tab />';
  73. const scopeProps = {
  74. ctrl: {
  75. panel: panel,
  76. dashboard: dashboard,
  77. refresh: () => panel.refresh(),
  78. },
  79. };
  80. this.component = loader.load(this.element, scopeProps, template);
  81. }
  82. componentWillUnmount() {
  83. if (this.component) {
  84. this.component.destroy();
  85. }
  86. }
  87. onChangeDataSource = datasource => {
  88. const { panel } = this.props;
  89. const { currentDatasource } = this.state;
  90. // switching to mixed
  91. if (datasource.meta.mixed) {
  92. panel.targets.forEach(target => {
  93. target.datasource = panel.datasource;
  94. if (!target.datasource) {
  95. target.datasource = config.defaultDatasource;
  96. }
  97. });
  98. } else if (currentDatasource && currentDatasource.meta.mixed) {
  99. panel.targets.forEach(target => {
  100. delete target.datasource;
  101. });
  102. }
  103. panel.datasource = datasource.value;
  104. panel.refresh();
  105. this.setState(prevState => ({
  106. ...prevState,
  107. currentDatasource: datasource,
  108. }));
  109. };
  110. loadHelp = () => {
  111. const { currentDatasource } = this.state;
  112. const hasHelp = currentDatasource.meta.hasQueryHelp;
  113. if (hasHelp) {
  114. this.setState(prevState => ({
  115. ...prevState,
  116. help: {
  117. helpHtml: <h2>Loading help...</h2>,
  118. isLoading: true,
  119. },
  120. }));
  121. this.backendSrv
  122. .get(`/api/plugins/${currentDatasource.meta.id}/markdown/query_help`)
  123. .then(res => {
  124. const md = new Remarkable();
  125. const helpHtml = md.render(res); // TODO: Clean out dangerous code? Previous: this.helpHtml = this.$sce.trustAsHtml(md.render(res));
  126. this.setState(prevState => ({
  127. ...prevState,
  128. help: {
  129. helpHtml: <div className="markdown-html" dangerouslySetInnerHTML={{ __html: helpHtml }} />,
  130. isLoading: false,
  131. },
  132. }));
  133. })
  134. .catch(() => {
  135. this.setState(prevState => ({
  136. ...prevState,
  137. help: {
  138. helpHtml: 'Error occured when loading help',
  139. isLoading: false,
  140. },
  141. }));
  142. });
  143. }
  144. };
  145. renderOptions = close => {
  146. const { currentDatasource } = this.state;
  147. const { queryOptions } = currentDatasource.meta;
  148. const { panel } = this.props;
  149. const onChangeFn = (panelKey: string) => {
  150. return (value: string | number) => {
  151. panel[panelKey] = value;
  152. panel.refresh();
  153. };
  154. };
  155. const allOptions = {
  156. cacheTimeout: {
  157. label: 'Cache timeout',
  158. placeholder: '60',
  159. name: 'cacheTimeout',
  160. value: panel.cacheTimeout,
  161. tooltipInfo: (
  162. <>
  163. If your time series store has a query cache this option can override the default cache timeout. Specify a
  164. numeric value in seconds.
  165. </>
  166. ),
  167. },
  168. maxDataPoints: {
  169. label: 'Max data points',
  170. placeholder: 'auto',
  171. name: 'maxDataPoints',
  172. value: panel.maxDataPoints,
  173. tooltipInfo: (
  174. <>
  175. The maximum data points the query should return. For graphs this is automatically set to one data point per
  176. pixel.
  177. </>
  178. ),
  179. },
  180. minInterval: {
  181. label: 'Min time interval',
  182. placeholder: '0',
  183. name: 'minInterval',
  184. value: panel.interval,
  185. panelKey: 'interval',
  186. tooltipInfo: (
  187. <>
  188. A lower limit for the auto group by time interval. Recommended to be set to write frequency, for example{' '}
  189. <code>1m</code> if your data is written every minute. Access auto interval via variable{' '}
  190. <code>$__interval</code> for time range string and <code>$__interval_ms</code> for numeric variable that can
  191. be used in math expressions.
  192. </>
  193. ),
  194. },
  195. };
  196. return Object.keys(queryOptions).map(key => {
  197. const options = allOptions[key];
  198. return <DataSourceOption key={key} {...options} onChange={onChangeFn(allOptions[key].panelKey || key)} />;
  199. });
  200. };
  201. renderQueryInspector = () => {
  202. const { panel } = this.props;
  203. return <QueryInspector panel={panel} LoadingPlaceholder={LoadingPlaceholder} />;
  204. };
  205. renderHelp = () => {
  206. const { helpHtml, isLoading } = this.state.help;
  207. return isLoading ? <LoadingPlaceholder text="Loading help..." /> : helpHtml;
  208. };
  209. emptyToNull = (value: string) => {
  210. return value === '' ? null : value;
  211. };
  212. onOverrideTime = (evt, status: InputStatus) => {
  213. const { value } = evt.target;
  214. const { panel } = this.props;
  215. const emptyToNullValue = this.emptyToNull(value);
  216. if (status === InputStatus.Valid && panel.timeFrom !== emptyToNullValue) {
  217. panel.timeFrom = emptyToNullValue;
  218. panel.refresh();
  219. }
  220. };
  221. onTimeShift = (evt, status: InputStatus) => {
  222. const { value } = evt.target;
  223. const { panel } = this.props;
  224. const emptyToNullValue = this.emptyToNull(value);
  225. if (status === InputStatus.Valid && panel.timeShift !== emptyToNullValue) {
  226. panel.timeShift = emptyToNullValue;
  227. panel.refresh();
  228. }
  229. };
  230. onToggleTimeOverride = () => {
  231. const { panel } = this.props;
  232. panel.hideTimeOverride = !panel.hideTimeOverride;
  233. panel.refresh();
  234. };
  235. render() {
  236. const { currentDatasource } = this.state;
  237. const hideTimeOverride = this.props.panel.hideTimeOverride;
  238. console.log('hideTimeOverride', hideTimeOverride);
  239. const { hasQueryHelp, queryOptions } = currentDatasource.meta;
  240. const hasQueryOptions = !!queryOptions;
  241. const dsInformation = {
  242. title: currentDatasource.name,
  243. imgSrc: currentDatasource.meta.info.logos.small,
  244. render: closeOpenView => (
  245. <DataSourcePicker
  246. datasources={this.datasources}
  247. onChangeDataSource={ds => {
  248. closeOpenView();
  249. this.onChangeDataSource(ds);
  250. }}
  251. />
  252. ),
  253. };
  254. const queryInspector = {
  255. title: 'Query Inspector',
  256. render: this.renderQueryInspector,
  257. };
  258. const dsHelp = {
  259. title: '',
  260. icon: 'fa fa-question',
  261. disabled: !hasQueryHelp,
  262. onClick: this.loadHelp,
  263. render: this.renderHelp,
  264. };
  265. const options = {
  266. title: '',
  267. icon: 'fa fa-cog',
  268. disabled: !hasQueryOptions,
  269. render: this.renderOptions,
  270. };
  271. return (
  272. <EditorTabBody heading="Queries" main={dsInformation} toolbarItems={[options, queryInspector, dsHelp]}>
  273. <>
  274. <div ref={element => (this.element = element)} style={{ width: '100%' }} />
  275. <h5 className="section-heading">Time Range</h5>
  276. <div className="gf-form-group">
  277. <div className="gf-form">
  278. <span className="gf-form-label">
  279. <i className="fa fa-clock-o" />
  280. </span>
  281. <span className="gf-form-label width-12">Override relative time</span>
  282. <span className="gf-form-label width-6">Last</span>
  283. <Input
  284. type="text"
  285. className="gf-form-input max-width-8"
  286. placeholder="1h"
  287. onBlurWithStatus={this.onOverrideTime}
  288. validationRules={validationRules}
  289. hideErrorMessage={true}
  290. />
  291. </div>
  292. <div className="gf-form">
  293. <span className="gf-form-label">
  294. <i className="fa fa-clock-o" />
  295. </span>
  296. <span className="gf-form-label width-12">Add time shift</span>
  297. <span className="gf-form-label width-6">Amount</span>
  298. <Input
  299. type="text"
  300. className="gf-form-input max-width-8"
  301. placeholder="1h"
  302. onBlurWithStatus={this.onTimeShift}
  303. validationRules={validationRules}
  304. hideErrorMessage={true}
  305. />
  306. </div>
  307. <div className="gf-form-inline">
  308. <div className="gf-form">
  309. <span className="gf-form-label">
  310. <i className="fa fa-clock-o" />
  311. </span>
  312. </div>
  313. <Switch label="Hide time override info" checked={hideTimeOverride} onChange={this.onToggleTimeOverride} />
  314. </div>
  315. </div>
  316. </>
  317. </EditorTabBody>
  318. );
  319. }
  320. }