grafana/public/app/features/explore/Explore.tsx

493 lines
15 KiB
TypeScript
Raw Normal View History

2019-01-17 10:59:47 -06:00
// Libraries
import React from 'react';
2018-04-26 04:58:42 -05:00
import { hot } from 'react-hot-loader';
import { css, cx } from 'emotion';
2019-01-10 07:24:31 -06:00
import { connect } from 'react-redux';
import AutoSizer from 'react-virtualized-auto-sizer';
import memoizeOne from 'memoize-one';
2019-01-17 10:59:47 -06:00
// Services & Utils
import store from 'app/core/store';
2019-01-17 10:59:47 -06:00
// Components
import { ErrorBoundaryAlert, stylesFactory } from '@grafana/ui';
2019-01-17 10:59:47 -06:00
import LogsContainer from './LogsContainer';
import QueryRows from './QueryRows';
import TableContainer from './TableContainer';
import RichHistoryContainer from './RichHistory/RichHistoryContainer';
2019-01-17 10:59:47 -06:00
// Actions
import {
changeSize,
initializeExplore,
modifyQueries,
scanStart,
setQueries,
refreshExplore,
updateTimeRange,
toggleGraph,
addQueryRow,
} from './state/actions';
2019-01-17 10:59:47 -06:00
// Types
import {
DataQuery,
DataSourceApi,
PanelData,
RawTimeRange,
TimeRange,
GraphSeriesXY,
TimeZone,
AbsoluteTimeRange,
LoadingState,
Explore: Adds Loki explore query editor (#21497) * Explore: updates grafana-data explore query field props with explore mode * Explore: updates query row to pass down explore mode to query fields * Explore: adds LokiExploreQueryEditor * Explore: updates loki query field form to render children * Explore: adds loki explore extra field component * Explore: adds extra field element to loki query field form * Explore: updates loki explore query editor to use extra field element * Explore: moves ExploreMode to grafana-data * Explore: updates query row limit string * Explore: adds maxLines to DataQuery * Explore: adds maxLines to loki datasource runRangeQueryWithFallback * Explore: adds onChangeQueryLimit to LokiExploreQueryEditor * Explore: updates loki explore query editor to render extra field only in logs mode * Explore: fixes query limits for live and legacy queries * Explore: fixes result processor max lines limit in get logs result * Explore: fixes Loki datasource limit test * Explore: removes unnecessary ExploreMode from Loki language provider * Explore: fixes formatting * Explore: updates grafana-data datasource types - replaces strings with explore mode enum * Explore: updates loki explore query field props to take ReactNode * Explore: updates the way we calculate loki query lines limit to fall back to 0 lines on negative or invalid input instead of datasource maxLines * Explore: updates result processor get logs result method to avoid counting invalid/negative line limits * Explore: updates loki result transformer to process only an appropriate slice of a result instead of an entire one * Explore: adds a method for query limit preprocessing/mapping * Explore: updates loki datasource run range query with fallback method to use options.maxDataPoints in dashboards * Explore: removes unnecessary maxlineslimt from getLogsResult in resultProcessor * Explore: moves line limit to metadata * Explore: adds an ability to specify input type of extra field * Explore: updates LokiExploreQueryEditor - adds an input type * Explore: updates LokiExploreQueryEditor to run queries when maxLines is positive * Explore: fixes failing import of ExploreMode * Explore: fixes reducers test imports formatting * Explore: updates Loki extra field with min value set to 0 * Explore: exports LokiExploreExtraFieldProps * Explore: adds render test of LokiExploreQueryEditor * Explore: adds LokiExploreQueryEditor snapshot * Explore: updates LokiExploreQueryEditor onChangeQueryLimit method to prevent it from running when query input is empty - fixes cheatsheet display issue * Explore: updates Loki editor snapshots * Explore: fixes typo in test set name in LokiExploreQueryEditor * Explore: adds a render test of LokiExploreExtraField * Explore: fixes typo in LokiExploreQueryEditor * Explore: updates LokiExploreQueryEditor snapshot due to timezone issues * Explore: updates LokiExploreExtraField to export both functional component and a version using memo * Explore: updates LokiExploreQueryEditor to export both functional component and memoized function * Explore: updates LokiExploreQueryEditor - removes unnecessary react fragment * Explore: updates LokiExploreQueryEditor snapshot * Explore: adds LokiExploreQueryEditor tests for different explore mode cases * Explore: fixes Loki datasource and result transformer * Explore: updates LokiExploreQueryEditor snapshot * Explore: updates LokiExploreQueryEditor tests and test setup * Explore: updates LokiExploreQueryEditor - refactors component * Explore: updates LokiExploreQueryEditor to use default import from LokiExploreExtraField * Explore: updates LokiExploreQueryEditor snapshot * Explore: fixes formatting * Explore: updates LokiExploreQueryEditor max lines change * Explore: updates LokiExploreQueryEditor tests checking ExtraFieldElement * Explore: adds mock loki datasource to LokiExploreQueryEditor * Explore: updates LokiExploreQueryEditor test mock - adds language provider * Explore: updates LokiExploreQueryEditor snapshot * Explore: updates Loki ResultTransformer to filter out rows on limit - logic to be moved into a component with new form styles * Explore: updates LokiExploreQueryEditor tests
2020-02-06 06:34:52 -06:00
ExploreMode,
} from '@grafana/data';
Explore: Adds Loki explore query editor (#21497) * Explore: updates grafana-data explore query field props with explore mode * Explore: updates query row to pass down explore mode to query fields * Explore: adds LokiExploreQueryEditor * Explore: updates loki query field form to render children * Explore: adds loki explore extra field component * Explore: adds extra field element to loki query field form * Explore: updates loki explore query editor to use extra field element * Explore: moves ExploreMode to grafana-data * Explore: updates query row limit string * Explore: adds maxLines to DataQuery * Explore: adds maxLines to loki datasource runRangeQueryWithFallback * Explore: adds onChangeQueryLimit to LokiExploreQueryEditor * Explore: updates loki explore query editor to render extra field only in logs mode * Explore: fixes query limits for live and legacy queries * Explore: fixes result processor max lines limit in get logs result * Explore: fixes Loki datasource limit test * Explore: removes unnecessary ExploreMode from Loki language provider * Explore: fixes formatting * Explore: updates grafana-data datasource types - replaces strings with explore mode enum * Explore: updates loki explore query field props to take ReactNode * Explore: updates the way we calculate loki query lines limit to fall back to 0 lines on negative or invalid input instead of datasource maxLines * Explore: updates result processor get logs result method to avoid counting invalid/negative line limits * Explore: updates loki result transformer to process only an appropriate slice of a result instead of an entire one * Explore: adds a method for query limit preprocessing/mapping * Explore: updates loki datasource run range query with fallback method to use options.maxDataPoints in dashboards * Explore: removes unnecessary maxlineslimt from getLogsResult in resultProcessor * Explore: moves line limit to metadata * Explore: adds an ability to specify input type of extra field * Explore: updates LokiExploreQueryEditor - adds an input type * Explore: updates LokiExploreQueryEditor to run queries when maxLines is positive * Explore: fixes failing import of ExploreMode * Explore: fixes reducers test imports formatting * Explore: updates Loki extra field with min value set to 0 * Explore: exports LokiExploreExtraFieldProps * Explore: adds render test of LokiExploreQueryEditor * Explore: adds LokiExploreQueryEditor snapshot * Explore: updates LokiExploreQueryEditor onChangeQueryLimit method to prevent it from running when query input is empty - fixes cheatsheet display issue * Explore: updates Loki editor snapshots * Explore: fixes typo in test set name in LokiExploreQueryEditor * Explore: adds a render test of LokiExploreExtraField * Explore: fixes typo in LokiExploreQueryEditor * Explore: updates LokiExploreQueryEditor snapshot due to timezone issues * Explore: updates LokiExploreExtraField to export both functional component and a version using memo * Explore: updates LokiExploreQueryEditor to export both functional component and memoized function * Explore: updates LokiExploreQueryEditor - removes unnecessary react fragment * Explore: updates LokiExploreQueryEditor snapshot * Explore: adds LokiExploreQueryEditor tests for different explore mode cases * Explore: fixes Loki datasource and result transformer * Explore: updates LokiExploreQueryEditor snapshot * Explore: updates LokiExploreQueryEditor tests and test setup * Explore: updates LokiExploreQueryEditor - refactors component * Explore: updates LokiExploreQueryEditor to use default import from LokiExploreExtraField * Explore: updates LokiExploreQueryEditor snapshot * Explore: fixes formatting * Explore: updates LokiExploreQueryEditor max lines change * Explore: updates LokiExploreQueryEditor tests checking ExtraFieldElement * Explore: adds mock loki datasource to LokiExploreQueryEditor * Explore: updates LokiExploreQueryEditor test mock - adds language provider * Explore: updates LokiExploreQueryEditor snapshot * Explore: updates Loki ResultTransformer to filter out rows on limit - logic to be moved into a component with new form styles * Explore: updates LokiExploreQueryEditor tests
2020-02-06 06:34:52 -06:00
import { ExploreItemState, ExploreUrlState, ExploreId, ExploreUpdateState, ExploreUIState } from 'app/types/explore';
2019-01-17 10:59:47 -06:00
import { StoreState } from 'app/types';
import {
ensureQueries,
DEFAULT_RANGE,
DEFAULT_UI_STATE,
getTimeRangeFromUrl,
getTimeRange,
lastUsedDatasourceKeyForOrgId,
getFirstNonQueryRowSpecificError,
} from 'app/core/utils/explore';
2019-01-17 10:59:47 -06:00
import { Emitter } from 'app/core/utils/emitter';
import { ExploreToolbar } from './ExploreToolbar';
import { NoDataSourceCallToAction } from './NoDataSourceCallToAction';
import { getTimeZone } from '../profile/state/selectors';
import { ErrorContainer } from './ErrorContainer';
import { scanStopAction } from './state/actionTypes';
import { ExploreGraphPanel } from './ExploreGraphPanel';
const getStyles = stylesFactory(() => {
return {
logsMain: css`
label: logsMain;
// Is needed for some transition animations to work.
position: relative;
`,
button: css`
margin: 1em 4px 0 0;
`,
};
});
export interface ExploreProps {
2019-01-11 11:26:56 -06:00
changeSize: typeof changeSize;
datasourceInstance: DataSourceApi;
2019-01-10 07:24:31 -06:00
datasourceMissing: boolean;
2019-01-11 11:26:56 -06:00
exploreId: ExploreId;
2019-01-10 07:24:31 -06:00
initializeExplore: typeof initializeExplore;
2019-01-12 16:22:28 -06:00
initialized: boolean;
2019-01-10 07:24:31 -06:00
modifyQueries: typeof modifyQueries;
update: ExploreUpdateState;
refreshExplore: typeof refreshExplore;
2019-01-10 07:24:31 -06:00
scanning?: boolean;
scanRange?: RawTimeRange;
scanStart: typeof scanStart;
scanStopAction: typeof scanStopAction;
setQueries: typeof setQueries;
split: boolean;
2019-02-04 06:41:29 -06:00
queryKeys: string[];
initialDatasource: string;
initialQueries: DataQuery[];
initialRange: TimeRange;
mode: ExploreMode;
initialUI: ExploreUIState;
isLive: boolean;
syncedTimes: boolean;
updateTimeRange: typeof updateTimeRange;
graphResult?: GraphSeriesXY[];
loading?: boolean;
absoluteRange: AbsoluteTimeRange;
showingGraph?: boolean;
showingTable?: boolean;
timeZone?: TimeZone;
onHiddenSeriesChanged?: (hiddenSeries: string[]) => void;
toggleGraph: typeof toggleGraph;
queryResponse: PanelData;
originPanelId: number;
addQueryRow: typeof addQueryRow;
}
interface ExploreState {
showRichHistory: boolean;
}
/**
* Explore provides an area for quick query iteration for a given datasource.
* Once a datasource is selected it populates the query section at the top.
* When queries are run, their results are being displayed in the main section.
* The datasource determines what kind of query editor it brings, and what kind
2019-01-12 16:44:24 -06:00
* of results viewers it supports. The state is managed entirely in Redux.
2018-11-22 05:00:41 -06:00
*
2019-01-12 16:44:24 -06:00
* SPLIT VIEW
2018-11-22 05:00:41 -06:00
*
2019-01-12 16:44:24 -06:00
* Explore can have two Explore areas side-by-side. This is handled in `Wrapper.tsx`.
* Since there can be multiple Explores (e.g., left and right) each action needs
* the `exploreId` as first parameter so that the reducer knows which Explore state
* is affected.
2018-11-22 05:00:41 -06:00
*
* DATASOURCE REQUESTS
*
* A click on Run Query creates transactions for all DataQueries for all expanded
* result viewers. New runs are discarding previous runs. Upon completion a transaction
* saves the result. The result viewers construct their data from the currently existing
* transactions.
*
* The result viewers determine some of the query options sent to the datasource, e.g.,
* `format`, to indicate eventual transformations by the datasources' result transformers.
*/
export class Explore extends React.PureComponent<ExploreProps, ExploreState> {
el: any;
2018-11-23 08:12:20 -06:00
exploreEvents: Emitter;
constructor(props: ExploreProps) {
2018-04-26 04:58:42 -05:00
super(props);
2018-11-23 08:12:20 -06:00
this.exploreEvents = new Emitter();
this.state = {
showRichHistory: false,
};
2018-04-26 04:58:42 -05:00
}
componentDidMount() {
const {
initialized,
exploreId,
initialDatasource,
initialQueries,
initialRange,
mode,
initialUI,
originPanelId,
} = this.props;
const width = this.el ? this.el.offsetWidth : 0;
// initialize the whole explore first time we mount and if browser history contains a change in datasource
if (!initialized) {
2019-01-11 11:26:56 -06:00
this.props.initializeExplore(
exploreId,
initialDatasource,
initialQueries,
initialRange,
mode,
2019-01-11 11:26:56 -06:00
width,
this.exploreEvents,
initialUI,
originPanelId
2019-01-11 11:26:56 -06:00
);
}
2018-04-26 04:58:42 -05:00
}
componentWillUnmount() {
this.exploreEvents.removeAllListeners();
}
componentDidUpdate(prevProps: ExploreProps) {
this.refreshExplore();
}
getRef = (el: any) => {
this.el = el;
};
onChangeTime = (rawRange: RawTimeRange) => {
const { updateTimeRange, exploreId } = this.props;
updateTimeRange({ exploreId, rawRange });
};
// Use this in help pages to set page to a single query
2018-11-21 09:28:30 -06:00
onClickExample = (query: DataQuery) => {
this.props.setQueries(this.props.exploreId, [query]);
};
onClickFilterLabel = (key: string, value: string) => {
this.onModifyQueries({ type: 'ADD_FILTER', key, value });
};
onClickFilterOutLabel = (key: string, value: string) => {
this.onModifyQueries({ type: 'ADD_FILTER_OUT', key, value });
};
onClickAddQueryRowButton = () => {
const { exploreId, queryKeys } = this.props;
this.props.addQueryRow(exploreId, queryKeys.length);
};
onModifyQueries = (action: any, index?: number) => {
2019-01-10 07:24:31 -06:00
const { datasourceInstance } = this.props;
if (datasourceInstance?.modifyQuery) {
const modifier = (queries: DataQuery, modification: any) =>
datasourceInstance.modifyQuery!(queries, modification);
this.props.modifyQueries(this.props.exploreId, action, modifier, index);
}
};
2019-01-11 11:26:56 -06:00
onResize = (size: { height: number; width: number }) => {
this.props.changeSize(this.props.exploreId, size);
2018-04-26 04:58:42 -05:00
};
2018-11-27 09:35:37 -06:00
onStartScanning = () => {
2019-01-10 07:24:31 -06:00
// Scanner will trigger a query
this.props.scanStart(this.props.exploreId);
};
2018-11-27 09:35:37 -06:00
onStopScanning = () => {
this.props.scanStopAction({ exploreId: this.props.exploreId });
};
onToggleGraph = (showingGraph: boolean) => {
const { toggleGraph, exploreId } = this.props;
toggleGraph(exploreId, showingGraph);
};
onUpdateTimeRange = (absoluteRange: AbsoluteTimeRange) => {
const { exploreId, updateTimeRange } = this.props;
updateTimeRange({ exploreId, absoluteRange });
};
toggleShowRichHistory = () => {
this.setState(state => {
return {
showRichHistory: !state.showRichHistory,
};
});
};
refreshExplore = () => {
const { exploreId, update } = this.props;
if (update.queries || update.ui || update.range || update.datasource || update.mode) {
this.props.refreshExplore(exploreId);
}
};
renderEmptyState = () => {
return (
<div className="explore-container">
<NoDataSourceCallToAction />
</div>
);
};
2018-04-26 04:58:42 -05:00
render() {
const {
2019-01-10 07:24:31 -06:00
datasourceInstance,
datasourceMissing,
2019-01-11 11:26:56 -06:00
exploreId,
2019-01-10 07:24:31 -06:00
split,
2019-02-04 06:41:29 -06:00
queryKeys,
mode,
graphResult,
loading,
absoluteRange,
showingGraph,
showingTable,
timeZone,
queryResponse,
syncedTimes,
isLive,
2019-01-10 07:24:31 -06:00
} = this.props;
const { showRichHistory } = this.state;
const exploreClass = split ? 'explore explore-split' : 'explore';
const styles = getStyles();
const StartPage = datasourceInstance?.components?.ExploreStartPage;
const showStartPage = !queryResponse || queryResponse.state === LoadingState.NotStarted;
// gets an error without a refID, so non-query-row-related error, like a connection error
const queryErrors = queryResponse.error ? [queryResponse.error] : undefined;
const queryError = getFirstNonQueryRowSpecificError(queryErrors);
2018-04-26 04:58:42 -05:00
return (
<div className={exploreClass} ref={this.getRef}>
<ExploreToolbar exploreId={exploreId} onChangeTime={this.onChangeTime} />
{datasourceMissing ? this.renderEmptyState() : null}
{datasourceInstance && (
<div className="explore-container">
<QueryRows exploreEvents={this.exploreEvents} exploreId={exploreId} queryKeys={queryKeys} />
<div className="gf-form">
<button
aria-label="Add row button"
className={`gf-form-label gf-form-label--btn ${styles.button}`}
onClick={this.onClickAddQueryRowButton}
disabled={isLive}
>
<i className={'fa fa-fw fa-plus icon-margin-right'} />
<span className="btn-title">{'\xA0' + 'Add query'}</span>
</button>
<button
aria-label="Rich history button"
className={cx(`gf-form-label gf-form-label--btn ${styles.button}`, {
['explore-active-button']: showRichHistory,
})}
onClick={this.toggleShowRichHistory}
disabled={isLive}
>
<i className={'fa fa-fw fa-history icon-margin-right '} />
<span className="btn-title">{'\xA0' + 'Query history'}</span>
</button>
</div>
<ErrorContainer queryError={queryError} />
<AutoSizer onResize={this.onResize} disableHeight>
{({ width }) => {
if (width === 0) {
return null;
}
return (
<main className={`m-t-2 ${styles.logsMain}`} style={{ width }}>
<ErrorBoundaryAlert>
{showStartPage && StartPage && (
<div className={'grafana-info-box grafana-info-box--max-lg'}>
<StartPage
onClickExample={this.onClickExample}
datasource={datasourceInstance}
exploreMode={mode}
/>
</div>
)}
{!showStartPage && (
<>
{mode === ExploreMode.Metrics && (
<ExploreGraphPanel
series={graphResult}
width={width}
loading={loading}
absoluteRange={absoluteRange}
isStacked={false}
showPanel={true}
showingGraph={showingGraph}
showingTable={showingTable}
timeZone={timeZone}
onToggleGraph={this.onToggleGraph}
onUpdateTimeRange={this.onUpdateTimeRange}
showBars={false}
showLines={true}
/>
)}
{mode === ExploreMode.Metrics && (
<TableContainer width={width} exploreId={exploreId} onClickCell={this.onClickFilterLabel} />
)}
{mode === ExploreMode.Logs && (
<LogsContainer
width={width}
exploreId={exploreId}
syncedTimes={syncedTimes}
onClickFilterLabel={this.onClickFilterLabel}
onClickFilterOutLabel={this.onClickFilterOutLabel}
onStartScanning={this.onStartScanning}
onStopScanning={this.onStopScanning}
/>
)}
</>
)}
{showRichHistory && <RichHistoryContainer width={width} exploreId={exploreId} />}
</ErrorBoundaryAlert>
</main>
);
}}
</AutoSizer>
</div>
)}
2018-04-26 04:58:42 -05:00
</div>
);
}
}
const ensureQueriesMemoized = memoizeOne(ensureQueries);
const getTimeRangeFromUrlMemoized = memoizeOne(getTimeRangeFromUrl);
function mapStateToProps(state: StoreState, { exploreId }: ExploreProps): Partial<ExploreProps> {
2019-01-11 11:26:56 -06:00
const explore = state.explore;
const { split, syncedTimes } = explore;
2019-01-11 11:26:56 -06:00
const item: ExploreItemState = explore[exploreId];
const timeZone = getTimeZone(state.user);
2019-01-10 07:24:31 -06:00
const {
datasourceInstance,
datasourceMissing,
2019-01-12 16:22:28 -06:00
initialized,
2019-02-04 06:41:29 -06:00
queryKeys,
urlState,
update,
isLive,
supportedModes,
mode,
graphResult,
loading,
showingGraph,
showingTable,
absoluteRange,
queryResponse,
2019-01-11 11:26:56 -06:00
} = item;
const { datasource, queries, range: urlRange, mode: urlMode, ui, originPanelId } = (urlState ||
{}) as ExploreUrlState;
const initialDatasource = datasource || store.get(lastUsedDatasourceKeyForOrgId(state.user.orgId));
const initialQueries: DataQuery[] = ensureQueriesMemoized(queries);
const initialRange = urlRange
? getTimeRangeFromUrlMemoized(urlRange, timeZone)
: getTimeRange(timeZone, DEFAULT_RANGE);
let newMode: ExploreMode | undefined;
if (supportedModes.length) {
const urlModeIsValid = supportedModes.includes(urlMode);
const modeStateIsValid = supportedModes.includes(mode);
if (modeStateIsValid) {
newMode = mode;
} else if (urlModeIsValid) {
newMode = urlMode;
} else {
newMode = supportedModes[0];
}
} else {
newMode = [ExploreMode.Metrics, ExploreMode.Logs].includes(urlMode) ? urlMode : undefined;
}
const initialUI = ui || DEFAULT_UI_STATE;
2019-01-10 07:24:31 -06:00
return {
datasourceInstance,
datasourceMissing,
2019-01-12 16:22:28 -06:00
initialized,
2019-01-11 11:26:56 -06:00
split,
2019-02-04 06:41:29 -06:00
queryKeys,
update,
initialDatasource,
initialQueries,
initialRange,
mode: newMode,
initialUI,
isLive,
graphResult,
loading,
showingGraph,
showingTable,
absoluteRange,
queryResponse,
originPanelId,
syncedTimes,
timeZone,
2019-01-10 07:24:31 -06:00
};
}
const mapDispatchToProps: Partial<ExploreProps> = {
2019-01-11 11:26:56 -06:00
changeSize,
2019-01-10 07:24:31 -06:00
initializeExplore,
modifyQueries,
refreshExplore,
2019-01-10 07:24:31 -06:00
scanStart,
scanStopAction,
setQueries,
updateTimeRange,
toggleGraph,
addQueryRow,
2019-01-10 07:24:31 -06:00
};
export default hot(module)(
// @ts-ignore
connect(mapStateToProps, mapDispatchToProps)(Explore)
2019-05-13 02:38:19 -05:00
) as React.ComponentType<{ exploreId: ExploreId }>;