Files
grafana/public/app/features/dashboard/panel_editor/QueryEditorRow.tsx

331 lines
10 KiB
TypeScript
Raw Normal View History

2019-01-14 15:44:58 +01:00
// Libraries
import React, { PureComponent } from 'react';
import classNames from 'classnames';
import _ from 'lodash';
2019-01-14 15:44:58 +01:00
// Utils & Services
import { getDatasourceSrv } from 'app/features/plugins/datasource_srv';
import { AngularComponent, getAngularLoader } from '@grafana/runtime';
import { Emitter } from 'app/core/utils/emitter';
import { getTimeSrv } from 'app/features/dashboard/services/TimeSrv';
2019-01-14 15:44:58 +01:00
// Types
import { PanelModel } from '../state/PanelModel';
import { DataQuery, DataSourceApi, PanelData, DataQueryRequest, ErrorBoundaryAlert } from '@grafana/ui';
QueryProcessing: Observable query interface and RxJS for query & stream processing (#18899) * I needed to learn some rxjs and understand this more, so just playing around * Updated * Removed all the complete calls * Refactoring * StreamHandler -> observable start * progress * simple singal works * Handle update time range * added error handling * wrap old function * minor changes * handle data format in the subscribe function * Use replay subject to return last value to subscribers * Set loading state after no response in 50ms * added missing file * updated comment * Added cancelation of network requests * runRequest: Added unit test scenario framework * Progress on tests * minor refactor of unit tests * updated test * removed some old code * Shared queries work again, and also became so much simplier * unified query and observe methods * implict any fix * Fixed closed subject issue * removed comment * Use last returned data for loading state * WIP: Explore to runRequest makover step1 * Minor progress * Minor progress on explore and runRequest * minor progress * Things are starting to work in explore * Updated prometheus to use new observable query response, greatly simplified code * Revert refId change * Found better solution for key/refId/requestId problem * use observable with loki * tests compile * fix loki query prep * Explore: correct first response handling * Refactorings * Refactoring * Explore: Fixes LoadingState and GraphResults between runs (#18986) * Refactor: Adds state to DataQueryResponse * Fix: Fixes so we do not empty results before new data arrives Fixes: #17409 * Transformations work * observable test data * remove single() from loki promise * Fixed comment * Explore: Fixes failing Loki and Prometheus unit tests (#18995) * Tests: Makes datasource tests work again * Fix: Fixes loki datasource so highligthing works * Chore: Runs Prettier * Fixed query runner tests * Delay loading state indication to 200ms * Fixed test * fixed unit tests * Clear cached calcs * Fixed bug getProcesedDataFrames * Fix the correct test is a better idea * Fix: Fixes so queries in Explore are only run if Graph/Table is shown (#19000) * Fix: Fixes so queries in Explore are only run if Graph/Table is shown Fixes: #18618 * Refactor: Removes unnecessary condition * PanelData: provide legacy data only when needed (#19018) * no legacy * invert logic... now compiles * merge getQueryResponseData and getDataRaw * update comment about query editor * use single getData() function * only send legacy when it is used in explore * pre process rather than post process * pre process rather than post process * Minor refactoring * Add missing tags to test datasource response * MixedDatasource: Adds query observable pattern to MixedDatasource (#19037) * start mixed datasource * Refactor: Refactors into observable parttern * Tests: Fixes tests * Tests: Removes console.log * Refactor: Adds unique requestId
2019-09-12 17:28:46 +02:00
import { TimeRange, LoadingState, toLegacyResponseData } from '@grafana/data';
import { DashboardModel } from '../state/DashboardModel';
2019-01-14 15:44:58 +01:00
interface Props {
panel: PanelModel;
data: PanelData;
query: DataQuery;
dashboard: DashboardModel;
onAddQuery: (query?: DataQuery) => void;
onRemoveQuery: (query: DataQuery) => void;
onMoveQuery: (query: DataQuery, direction: number) => void;
onChange: (query: DataQuery) => void;
2019-01-21 18:54:57 +01:00
dataSourceValue: string | null;
inMixedMode: boolean;
2019-01-14 15:44:58 +01:00
}
interface State {
2019-01-21 18:54:57 +01:00
loadedDataSourceValue: string | null | undefined;
datasource: DataSourceApi | null;
isCollapsed: boolean;
hasTextEditMode: boolean;
data?: PanelData;
2019-01-14 15:44:58 +01:00
}
export class QueryEditorRow extends PureComponent<Props, State> {
element: HTMLElement | null = null;
angularScope: AngularQueryComponentScope | null;
angularQueryEditor: AngularComponent | null = null;
2019-01-14 15:44:58 +01:00
state: State = {
datasource: null,
isCollapsed: false,
2019-01-21 18:54:57 +01:00
loadedDataSourceValue: undefined,
hasTextEditMode: false,
data: null,
};
componentDidMount() {
this.loadDatasource();
}
componentWillUnmount() {
if (this.angularQueryEditor) {
this.angularQueryEditor.destroy();
}
}
getAngularQueryComponentScope(): AngularQueryComponentScope {
const { panel, query, dashboard } = this.props;
const { datasource } = this.state;
return {
datasource: datasource,
target: query,
panel: panel,
dashboard: dashboard,
refresh: () => panel.refresh(),
render: () => panel.render(),
events: panel.events,
range: getTimeSrv().timeRange(),
};
}
async loadDatasource() {
const { query, panel } = this.props;
const dataSourceSrv = getDatasourceSrv();
const datasource = await dataSourceSrv.get(query.datasource || panel.datasource);
this.setState({
datasource,
loadedDataSourceValue: this.props.dataSourceValue,
hasTextEditMode: _.has(datasource, 'components.QueryCtrl.prototype.toggleEditorMode'),
});
}
componentDidUpdate(prevProps: Props) {
2019-01-21 18:54:57 +01:00
const { loadedDataSourceValue } = this.state;
QueryProcessing: Observable query interface and RxJS for query & stream processing (#18899) * I needed to learn some rxjs and understand this more, so just playing around * Updated * Removed all the complete calls * Refactoring * StreamHandler -> observable start * progress * simple singal works * Handle update time range * added error handling * wrap old function * minor changes * handle data format in the subscribe function * Use replay subject to return last value to subscribers * Set loading state after no response in 50ms * added missing file * updated comment * Added cancelation of network requests * runRequest: Added unit test scenario framework * Progress on tests * minor refactor of unit tests * updated test * removed some old code * Shared queries work again, and also became so much simplier * unified query and observe methods * implict any fix * Fixed closed subject issue * removed comment * Use last returned data for loading state * WIP: Explore to runRequest makover step1 * Minor progress * Minor progress on explore and runRequest * minor progress * Things are starting to work in explore * Updated prometheus to use new observable query response, greatly simplified code * Revert refId change * Found better solution for key/refId/requestId problem * use observable with loki * tests compile * fix loki query prep * Explore: correct first response handling * Refactorings * Refactoring * Explore: Fixes LoadingState and GraphResults between runs (#18986) * Refactor: Adds state to DataQueryResponse * Fix: Fixes so we do not empty results before new data arrives Fixes: #17409 * Transformations work * observable test data * remove single() from loki promise * Fixed comment * Explore: Fixes failing Loki and Prometheus unit tests (#18995) * Tests: Makes datasource tests work again * Fix: Fixes loki datasource so highligthing works * Chore: Runs Prettier * Fixed query runner tests * Delay loading state indication to 200ms * Fixed test * fixed unit tests * Clear cached calcs * Fixed bug getProcesedDataFrames * Fix the correct test is a better idea * Fix: Fixes so queries in Explore are only run if Graph/Table is shown (#19000) * Fix: Fixes so queries in Explore are only run if Graph/Table is shown Fixes: #18618 * Refactor: Removes unnecessary condition * PanelData: provide legacy data only when needed (#19018) * no legacy * invert logic... now compiles * merge getQueryResponseData and getDataRaw * update comment about query editor * use single getData() function * only send legacy when it is used in explore * pre process rather than post process * pre process rather than post process * Minor refactoring * Add missing tags to test datasource response * MixedDatasource: Adds query observable pattern to MixedDatasource (#19037) * start mixed datasource * Refactor: Refactors into observable parttern * Tests: Fixes tests * Tests: Removes console.log * Refactor: Adds unique requestId
2019-09-12 17:28:46 +02:00
const { data, query, panel } = this.props;
if (data !== prevProps.data) {
this.setState({ data: filterPanelDataToQuery(data, query.refId) });
if (this.angularScope) {
this.angularScope.range = getTimeSrv().timeRange();
}
if (this.angularQueryEditor) {
QueryProcessing: Observable query interface and RxJS for query & stream processing (#18899) * I needed to learn some rxjs and understand this more, so just playing around * Updated * Removed all the complete calls * Refactoring * StreamHandler -> observable start * progress * simple singal works * Handle update time range * added error handling * wrap old function * minor changes * handle data format in the subscribe function * Use replay subject to return last value to subscribers * Set loading state after no response in 50ms * added missing file * updated comment * Added cancelation of network requests * runRequest: Added unit test scenario framework * Progress on tests * minor refactor of unit tests * updated test * removed some old code * Shared queries work again, and also became so much simplier * unified query and observe methods * implict any fix * Fixed closed subject issue * removed comment * Use last returned data for loading state * WIP: Explore to runRequest makover step1 * Minor progress * Minor progress on explore and runRequest * minor progress * Things are starting to work in explore * Updated prometheus to use new observable query response, greatly simplified code * Revert refId change * Found better solution for key/refId/requestId problem * use observable with loki * tests compile * fix loki query prep * Explore: correct first response handling * Refactorings * Refactoring * Explore: Fixes LoadingState and GraphResults between runs (#18986) * Refactor: Adds state to DataQueryResponse * Fix: Fixes so we do not empty results before new data arrives Fixes: #17409 * Transformations work * observable test data * remove single() from loki promise * Fixed comment * Explore: Fixes failing Loki and Prometheus unit tests (#18995) * Tests: Makes datasource tests work again * Fix: Fixes loki datasource so highligthing works * Chore: Runs Prettier * Fixed query runner tests * Delay loading state indication to 200ms * Fixed test * fixed unit tests * Clear cached calcs * Fixed bug getProcesedDataFrames * Fix the correct test is a better idea * Fix: Fixes so queries in Explore are only run if Graph/Table is shown (#19000) * Fix: Fixes so queries in Explore are only run if Graph/Table is shown Fixes: #18618 * Refactor: Removes unnecessary condition * PanelData: provide legacy data only when needed (#19018) * no legacy * invert logic... now compiles * merge getQueryResponseData and getDataRaw * update comment about query editor * use single getData() function * only send legacy when it is used in explore * pre process rather than post process * pre process rather than post process * Minor refactoring * Add missing tags to test datasource response * MixedDatasource: Adds query observable pattern to MixedDatasource (#19037) * start mixed datasource * Refactor: Refactors into observable parttern * Tests: Fixes tests * Tests: Removes console.log * Refactor: Adds unique requestId
2019-09-12 17:28:46 +02:00
notifyAngularQueryEditorsOfData(panel, data, this.angularQueryEditor);
}
}
// check if we need to load another datasource
2019-01-21 18:54:57 +01:00
if (loadedDataSourceValue !== this.props.dataSourceValue) {
if (this.angularQueryEditor) {
this.angularQueryEditor.destroy();
this.angularQueryEditor = null;
}
this.loadDatasource();
return;
}
if (!this.element || this.angularQueryEditor) {
return;
}
const loader = getAngularLoader();
const template = '<plugin-component type="query-ctrl" />';
const scopeProps = { ctrl: this.getAngularQueryComponentScope() };
this.angularQueryEditor = loader.load(this.element, scopeProps, template);
this.angularScope = scopeProps.ctrl;
}
onToggleCollapse = () => {
this.setState({ isCollapsed: !this.state.isCollapsed });
};
onRunQuery = () => {
this.props.panel.refresh();
};
2019-01-16 17:53:40 +01:00
renderPluginEditor() {
const { query, onChange } = this.props;
const { datasource, data } = this.state;
2019-01-16 17:53:40 +01:00
if (datasource.components.QueryCtrl) {
2019-01-17 13:08:20 +01:00
return <div ref={element => (this.element = element)} />;
2019-01-16 17:53:40 +01:00
}
if (datasource.components.QueryEditor) {
const QueryEditor = datasource.components.QueryEditor;
return (
<QueryEditor
query={query}
datasource={datasource}
onChange={onChange}
onRunQuery={this.onRunQuery}
data={data}
/>
);
2019-01-16 17:53:40 +01:00
}
return <div>Data source plugin does not export any Query Editor component</div>;
}
onToggleEditMode = () => {
if (this.angularScope && this.angularScope.toggleEditorMode) {
this.angularScope.toggleEditorMode();
2019-01-16 17:53:40 +01:00
this.angularQueryEditor.digest();
}
2019-01-17 13:15:25 +01:00
if (this.state.isCollapsed) {
this.setState({ isCollapsed: false });
}
2019-01-17 13:08:20 +01:00
};
2019-01-16 17:53:40 +01:00
onRemoveQuery = () => {
this.props.onRemoveQuery(this.props.query);
};
onCopyQuery = () => {
const copy = _.cloneDeep(this.props.query);
this.props.onAddQuery(copy);
};
onDisableQuery = () => {
this.props.query.hide = !this.props.query.hide;
this.onRunQuery();
this.forceUpdate();
};
2019-01-17 13:08:20 +01:00
renderCollapsedText(): string | null {
const { datasource } = this.state;
if (datasource.getQueryDisplayText) {
return datasource.getQueryDisplayText(this.props.query);
}
if (this.angularScope && this.angularScope.getCollapsedText) {
return this.angularScope.getCollapsedText();
2019-01-17 13:08:20 +01:00
}
return null;
}
2019-01-14 15:44:58 +01:00
render() {
2019-01-21 18:54:57 +01:00
const { query, inMixedMode } = this.props;
const { datasource, isCollapsed, hasTextEditMode } = this.state;
const isDisabled = query.hide;
const bodyClasses = classNames('query-editor-row__body gf-form-query', {
'query-editor-row__body--collapsed': isCollapsed,
});
const rowClasses = classNames('query-editor-row', {
'query-editor-row--disabled': isDisabled,
'gf-form-disabled': isDisabled,
});
if (!datasource) {
return null;
}
2019-01-14 15:44:58 +01:00
2019-01-16 17:53:40 +01:00
return (
<div className={rowClasses}>
<div className="query-editor-row__header">
<div className="query-editor-row__ref-id" onClick={this.onToggleCollapse}>
2019-01-16 17:53:40 +01:00
{isCollapsed && <i className="fa fa-caret-right" />}
{!isCollapsed && <i className="fa fa-caret-down" />}
<span>{query.refId}</span>
2019-01-21 18:54:57 +01:00
{inMixedMode && <em className="query-editor-row__context-info"> ({datasource.name})</em>}
{isDisabled && <em className="query-editor-row__context-info"> Disabled</em>}
</div>
<div className="query-editor-row__collapsed-text" onClick={this.onToggleEditMode}>
2019-01-17 13:08:20 +01:00
{isCollapsed && <div>{this.renderCollapsedText()}</div>}
</div>
<div className="query-editor-row__actions">
{hasTextEditMode && (
2019-01-17 13:08:20 +01:00
<button
className="query-editor-row__action"
onClick={this.onToggleEditMode}
title="Toggle text edit mode"
>
2019-01-16 17:53:40 +01:00
<i className="fa fa-fw fa-pencil" />
</button>
)}
<button className="query-editor-row__action" onClick={() => this.props.onMoveQuery(query, 1)}>
2019-01-16 17:53:40 +01:00
<i className="fa fa-fw fa-arrow-down" />
</button>
<button className="query-editor-row__action" onClick={() => this.props.onMoveQuery(query, -1)}>
2019-01-16 17:53:40 +01:00
<i className="fa fa-fw fa-arrow-up" />
</button>
<button className="query-editor-row__action" onClick={this.onCopyQuery} title="Duplicate query">
2019-01-16 17:53:40 +01:00
<i className="fa fa-fw fa-copy" />
</button>
<button className="query-editor-row__action" onClick={this.onDisableQuery} title="Disable/enable query">
{isDisabled && <i className="fa fa-fw fa-eye-slash" />}
{!isDisabled && <i className="fa fa-fw fa-eye" />}
2019-01-16 17:53:40 +01:00
</button>
<button className="query-editor-row__action" onClick={this.onRemoveQuery} title="Remove query">
2019-01-16 17:53:40 +01:00
<i className="fa fa-fw fa-trash" />
</button>
</div>
</div>
<div className={bodyClasses}>
<ErrorBoundaryAlert>{this.renderPluginEditor()}</ErrorBoundaryAlert>
</div>
2019-01-16 17:53:40 +01:00
</div>
);
2019-01-14 15:44:58 +01:00
}
}
QueryProcessing: Observable query interface and RxJS for query & stream processing (#18899) * I needed to learn some rxjs and understand this more, so just playing around * Updated * Removed all the complete calls * Refactoring * StreamHandler -> observable start * progress * simple singal works * Handle update time range * added error handling * wrap old function * minor changes * handle data format in the subscribe function * Use replay subject to return last value to subscribers * Set loading state after no response in 50ms * added missing file * updated comment * Added cancelation of network requests * runRequest: Added unit test scenario framework * Progress on tests * minor refactor of unit tests * updated test * removed some old code * Shared queries work again, and also became so much simplier * unified query and observe methods * implict any fix * Fixed closed subject issue * removed comment * Use last returned data for loading state * WIP: Explore to runRequest makover step1 * Minor progress * Minor progress on explore and runRequest * minor progress * Things are starting to work in explore * Updated prometheus to use new observable query response, greatly simplified code * Revert refId change * Found better solution for key/refId/requestId problem * use observable with loki * tests compile * fix loki query prep * Explore: correct first response handling * Refactorings * Refactoring * Explore: Fixes LoadingState and GraphResults between runs (#18986) * Refactor: Adds state to DataQueryResponse * Fix: Fixes so we do not empty results before new data arrives Fixes: #17409 * Transformations work * observable test data * remove single() from loki promise * Fixed comment * Explore: Fixes failing Loki and Prometheus unit tests (#18995) * Tests: Makes datasource tests work again * Fix: Fixes loki datasource so highligthing works * Chore: Runs Prettier * Fixed query runner tests * Delay loading state indication to 200ms * Fixed test * fixed unit tests * Clear cached calcs * Fixed bug getProcesedDataFrames * Fix the correct test is a better idea * Fix: Fixes so queries in Explore are only run if Graph/Table is shown (#19000) * Fix: Fixes so queries in Explore are only run if Graph/Table is shown Fixes: #18618 * Refactor: Removes unnecessary condition * PanelData: provide legacy data only when needed (#19018) * no legacy * invert logic... now compiles * merge getQueryResponseData and getDataRaw * update comment about query editor * use single getData() function * only send legacy when it is used in explore * pre process rather than post process * pre process rather than post process * Minor refactoring * Add missing tags to test datasource response * MixedDatasource: Adds query observable pattern to MixedDatasource (#19037) * start mixed datasource * Refactor: Refactors into observable parttern * Tests: Fixes tests * Tests: Removes console.log * Refactor: Adds unique requestId
2019-09-12 17:28:46 +02:00
// To avoid sending duplicate events for each row we have this global cached object here
// So we can check if we already emitted this legacy data event
let globalLastPanelDataCache: PanelData = null;
function notifyAngularQueryEditorsOfData(panel: PanelModel, data: PanelData, editor: AngularComponent) {
if (data === globalLastPanelDataCache) {
return;
}
globalLastPanelDataCache = data;
if (data.state === LoadingState.Done) {
const legacy = data.series.map(v => toLegacyResponseData(v));
panel.events.emit('data-received', legacy);
} else if (data.state === LoadingState.Error) {
panel.events.emit('data-error', data.error);
}
QueryProcessing: Observable query interface and RxJS for query & stream processing (#18899) * I needed to learn some rxjs and understand this more, so just playing around * Updated * Removed all the complete calls * Refactoring * StreamHandler -> observable start * progress * simple singal works * Handle update time range * added error handling * wrap old function * minor changes * handle data format in the subscribe function * Use replay subject to return last value to subscribers * Set loading state after no response in 50ms * added missing file * updated comment * Added cancelation of network requests * runRequest: Added unit test scenario framework * Progress on tests * minor refactor of unit tests * updated test * removed some old code * Shared queries work again, and also became so much simplier * unified query and observe methods * implict any fix * Fixed closed subject issue * removed comment * Use last returned data for loading state * WIP: Explore to runRequest makover step1 * Minor progress * Minor progress on explore and runRequest * minor progress * Things are starting to work in explore * Updated prometheus to use new observable query response, greatly simplified code * Revert refId change * Found better solution for key/refId/requestId problem * use observable with loki * tests compile * fix loki query prep * Explore: correct first response handling * Refactorings * Refactoring * Explore: Fixes LoadingState and GraphResults between runs (#18986) * Refactor: Adds state to DataQueryResponse * Fix: Fixes so we do not empty results before new data arrives Fixes: #17409 * Transformations work * observable test data * remove single() from loki promise * Fixed comment * Explore: Fixes failing Loki and Prometheus unit tests (#18995) * Tests: Makes datasource tests work again * Fix: Fixes loki datasource so highligthing works * Chore: Runs Prettier * Fixed query runner tests * Delay loading state indication to 200ms * Fixed test * fixed unit tests * Clear cached calcs * Fixed bug getProcesedDataFrames * Fix the correct test is a better idea * Fix: Fixes so queries in Explore are only run if Graph/Table is shown (#19000) * Fix: Fixes so queries in Explore are only run if Graph/Table is shown Fixes: #18618 * Refactor: Removes unnecessary condition * PanelData: provide legacy data only when needed (#19018) * no legacy * invert logic... now compiles * merge getQueryResponseData and getDataRaw * update comment about query editor * use single getData() function * only send legacy when it is used in explore * pre process rather than post process * pre process rather than post process * Minor refactoring * Add missing tags to test datasource response * MixedDatasource: Adds query observable pattern to MixedDatasource (#19037) * start mixed datasource * Refactor: Refactors into observable parttern * Tests: Fixes tests * Tests: Removes console.log * Refactor: Adds unique requestId
2019-09-12 17:28:46 +02:00
// Some query controllers listen to data error events and need a digest
// for some reason this needs to be done in next tick
setTimeout(editor.digest);
}
export interface AngularQueryComponentScope {
target: DataQuery;
panel: PanelModel;
dashboard: DashboardModel;
events: Emitter;
refresh: () => void;
render: () => void;
datasource: DataSourceApi;
2019-01-16 17:53:40 +01:00
toggleEditorMode?: () => void;
2019-01-17 13:08:20 +01:00
getCollapsedText?: () => string;
range: TimeRange;
}
/**
* Get a version of the PanelData limited to the query we are looking at
*/
export function filterPanelDataToQuery(data: PanelData, refId: string): PanelData | undefined {
const series = data.series.filter(series => series.refId === refId);
// No matching series
if (!series.length) {
return undefined;
}
// Don't pass the request if all requests are the same
const request: DataQueryRequest = undefined;
// TODO: look in sub-requets to match the info
// Only say this is an error if the error links to the query
let state = LoadingState.Done;
const error = data.error && data.error.refId === refId ? data.error : undefined;
if (error) {
state = LoadingState.Error;
}
const timeRange = data.timeRange;
return {
state,
series,
request,
error,
timeRange,
};
}