explore.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. // Libraries
  2. import _ from 'lodash';
  3. // Services & Utils
  4. import * as dateMath from 'app/core/utils/datemath';
  5. import { renderUrl } from 'app/core/utils/url';
  6. import kbn from 'app/core/utils/kbn';
  7. import store from 'app/core/store';
  8. import { parse as parseDate } from 'app/core/utils/datemath';
  9. import { colors } from '@grafana/ui';
  10. import TableModel, { mergeTablesIntoModel } from 'app/core/table_model';
  11. import { getNextRefIdChar } from './query';
  12. // Types
  13. import { RawTimeRange, IntervalValues, DataQuery, DataSourceApi } from '@grafana/ui';
  14. import TimeSeries from 'app/core/time_series2';
  15. import {
  16. ExploreUrlState,
  17. HistoryItem,
  18. QueryTransaction,
  19. ResultType,
  20. QueryIntervals,
  21. QueryOptions,
  22. ResultGetter,
  23. } from 'app/types/explore';
  24. import { LogsDedupStrategy } from 'app/core/logs_model';
  25. export const DEFAULT_RANGE = {
  26. from: 'now-6h',
  27. to: 'now',
  28. };
  29. export const DEFAULT_UI_STATE = {
  30. showingTable: true,
  31. showingGraph: true,
  32. showingLogs: true,
  33. dedupStrategy: LogsDedupStrategy.none,
  34. };
  35. const MAX_HISTORY_ITEMS = 100;
  36. export const LAST_USED_DATASOURCE_KEY = 'grafana.explore.datasource';
  37. /**
  38. * Returns an Explore-URL that contains a panel's queries and the dashboard time range.
  39. *
  40. * @param panel Origin panel of the jump to Explore
  41. * @param panelTargets The origin panel's query targets
  42. * @param panelDatasource The origin panel's datasource
  43. * @param datasourceSrv Datasource service to query other datasources in case the panel datasource is mixed
  44. * @param timeSrv Time service to get the current dashboard range from
  45. */
  46. export async function getExploreUrl(
  47. panel: any,
  48. panelTargets: any[],
  49. panelDatasource: any,
  50. datasourceSrv: any,
  51. timeSrv: any
  52. ) {
  53. let exploreDatasource = panelDatasource;
  54. let exploreTargets: DataQuery[] = panelTargets;
  55. let url;
  56. // Mixed datasources need to choose only one datasource
  57. if (panelDatasource.meta.id === 'mixed' && panelTargets) {
  58. // Find first explore datasource among targets
  59. let mixedExploreDatasource;
  60. for (const t of panel.targets) {
  61. const datasource = await datasourceSrv.get(t.datasource);
  62. if (datasource && datasource.meta.explore) {
  63. mixedExploreDatasource = datasource;
  64. break;
  65. }
  66. }
  67. // Add all its targets
  68. if (mixedExploreDatasource) {
  69. exploreDatasource = mixedExploreDatasource;
  70. exploreTargets = panelTargets.filter(t => t.datasource === mixedExploreDatasource.name);
  71. }
  72. }
  73. if (panelDatasource) {
  74. const range = timeSrv.timeRangeForUrl();
  75. let state: Partial<ExploreUrlState> = { range };
  76. if (exploreDatasource.getExploreState) {
  77. state = { ...state, ...exploreDatasource.getExploreState(exploreTargets) };
  78. } else {
  79. state = {
  80. ...state,
  81. datasource: panelDatasource.name,
  82. queries: exploreTargets.map(t => ({ ...t, datasource: panelDatasource.name })),
  83. };
  84. }
  85. const exploreState = JSON.stringify(state);
  86. url = renderUrl('/explore', { left: exploreState });
  87. }
  88. return url;
  89. }
  90. export function buildQueryTransaction(
  91. query: DataQuery,
  92. rowIndex: number,
  93. resultType: ResultType,
  94. queryOptions: QueryOptions,
  95. range: RawTimeRange,
  96. queryIntervals: QueryIntervals,
  97. scanning: boolean
  98. ): QueryTransaction {
  99. const { interval, intervalMs } = queryIntervals;
  100. const configuredQueries = [
  101. {
  102. ...query,
  103. ...queryOptions,
  104. },
  105. ];
  106. // Clone range for query request
  107. // const queryRange: RawTimeRange = { ...range };
  108. // const { from, to, raw } = this.timeSrv.timeRange();
  109. // Most datasource is using `panelId + query.refId` for cancellation logic.
  110. // Using `format` here because it relates to the view panel that the request is for.
  111. // However, some datasources don't use `panelId + query.refId`, but only `panelId`.
  112. // Therefore panel id has to be unique.
  113. const panelId = `${queryOptions.format}-${query.key}`;
  114. const options = {
  115. interval,
  116. intervalMs,
  117. panelId,
  118. targets: configuredQueries, // Datasources rely on DataQueries being passed under the targets key.
  119. range: {
  120. from: dateMath.parse(range.from, false),
  121. to: dateMath.parse(range.to, true),
  122. raw: range,
  123. },
  124. rangeRaw: range,
  125. scopedVars: {
  126. __interval: { text: interval, value: interval },
  127. __interval_ms: { text: intervalMs, value: intervalMs },
  128. },
  129. maxDataPoints: queryOptions.maxDataPoints,
  130. };
  131. return {
  132. options,
  133. query,
  134. resultType,
  135. rowIndex,
  136. scanning,
  137. id: generateKey(), // reusing for unique ID
  138. done: false,
  139. latency: 0,
  140. };
  141. }
  142. export const clearQueryKeys: (query: DataQuery) => object = ({ key, refId, ...rest }) => rest;
  143. const metricProperties = ['expr', 'target', 'datasource'];
  144. const isMetricSegment = (segment: { [key: string]: string }) =>
  145. metricProperties.some(prop => segment.hasOwnProperty(prop));
  146. const isUISegment = (segment: { [key: string]: string }) => segment.hasOwnProperty('ui');
  147. enum ParseUrlStateIndex {
  148. RangeFrom = 0,
  149. RangeTo = 1,
  150. Datasource = 2,
  151. SegmentsStart = 3,
  152. }
  153. enum ParseUiStateIndex {
  154. Graph = 0,
  155. Logs = 1,
  156. Table = 2,
  157. Strategy = 3,
  158. }
  159. export const safeParseJson = (text: string) => {
  160. if (!text) {
  161. return;
  162. }
  163. try {
  164. return JSON.parse(decodeURI(text));
  165. } catch (error) {
  166. console.error(error);
  167. }
  168. };
  169. export function parseUrlState(initial: string | undefined): ExploreUrlState {
  170. const parsed = safeParseJson(initial);
  171. const errorResult = { datasource: null, queries: [], range: DEFAULT_RANGE, ui: DEFAULT_UI_STATE };
  172. if (!parsed) {
  173. return errorResult;
  174. }
  175. if (!Array.isArray(parsed)) {
  176. return parsed;
  177. }
  178. if (parsed.length <= ParseUrlStateIndex.SegmentsStart) {
  179. console.error('Error parsing compact URL state for Explore.');
  180. return errorResult;
  181. }
  182. const range = {
  183. from: parsed[ParseUrlStateIndex.RangeFrom],
  184. to: parsed[ParseUrlStateIndex.RangeTo],
  185. };
  186. const datasource = parsed[ParseUrlStateIndex.Datasource];
  187. const parsedSegments = parsed.slice(ParseUrlStateIndex.SegmentsStart);
  188. const queries = parsedSegments.filter(segment => isMetricSegment(segment));
  189. const uiState = parsedSegments.filter(segment => isUISegment(segment))[0];
  190. const ui = uiState
  191. ? {
  192. showingGraph: uiState.ui[ParseUiStateIndex.Graph],
  193. showingLogs: uiState.ui[ParseUiStateIndex.Logs],
  194. showingTable: uiState.ui[ParseUiStateIndex.Table],
  195. dedupStrategy: uiState.ui[ParseUiStateIndex.Strategy],
  196. }
  197. : DEFAULT_UI_STATE;
  198. return { datasource, queries, range, ui };
  199. }
  200. export function serializeStateToUrlParam(urlState: ExploreUrlState, compact?: boolean): string {
  201. if (compact) {
  202. return JSON.stringify([
  203. urlState.range.from,
  204. urlState.range.to,
  205. urlState.datasource,
  206. ...urlState.queries,
  207. {
  208. ui: [
  209. !!urlState.ui.showingGraph,
  210. !!urlState.ui.showingLogs,
  211. !!urlState.ui.showingTable,
  212. urlState.ui.dedupStrategy,
  213. ],
  214. },
  215. ]);
  216. }
  217. return JSON.stringify(urlState);
  218. }
  219. export function generateKey(index = 0): string {
  220. return `Q-${Date.now()}-${Math.random()}-${index}`;
  221. }
  222. export function generateEmptyQuery(queries: DataQuery[], index = 0): DataQuery {
  223. return { refId: getNextRefIdChar(queries), key: generateKey(index) };
  224. }
  225. /**
  226. * Ensure at least one target exists and that targets have the necessary keys
  227. */
  228. export function ensureQueries(queries?: DataQuery[]): DataQuery[] {
  229. if (queries && typeof queries === 'object' && queries.length > 0) {
  230. return queries.map((query, i) => ({ ...query, ...generateEmptyQuery(queries, i) }));
  231. }
  232. return [{ ...generateEmptyQuery(queries) }];
  233. }
  234. /**
  235. * A target is non-empty when it has keys (with non-empty values) other than refId and key.
  236. */
  237. export function hasNonEmptyQuery<TQuery extends DataQuery = any>(queries: TQuery[]): boolean {
  238. return (
  239. queries &&
  240. queries.some(
  241. query =>
  242. Object.keys(query)
  243. .map(k => query[k])
  244. .filter(v => v).length > 2
  245. )
  246. );
  247. }
  248. export function calculateResultsFromQueryTransactions(
  249. queryTransactions: QueryTransaction[],
  250. datasource: any,
  251. graphInterval: number
  252. ) {
  253. const graphResult = _.flatten(
  254. queryTransactions.filter(qt => qt.resultType === 'Graph' && qt.done && qt.result).map(qt => qt.result)
  255. );
  256. const tableResult = mergeTablesIntoModel(
  257. new TableModel(),
  258. ...queryTransactions
  259. .filter(qt => qt.resultType === 'Table' && qt.done && qt.result && qt.result.columns && qt.result.rows)
  260. .map(qt => qt.result)
  261. );
  262. const logsResult =
  263. datasource && datasource.mergeStreams
  264. ? datasource.mergeStreams(
  265. _.flatten(
  266. queryTransactions.filter(qt => qt.resultType === 'Logs' && qt.done && qt.result).map(qt => qt.result)
  267. ),
  268. graphInterval
  269. )
  270. : undefined;
  271. return {
  272. graphResult,
  273. tableResult,
  274. logsResult,
  275. };
  276. }
  277. export function getIntervals(range: RawTimeRange, lowLimit: string, resolution: number): IntervalValues {
  278. if (!resolution) {
  279. return { interval: '1s', intervalMs: 1000 };
  280. }
  281. const absoluteRange: RawTimeRange = {
  282. from: parseDate(range.from, false),
  283. to: parseDate(range.to, true),
  284. };
  285. return kbn.calculateInterval(absoluteRange, resolution, lowLimit);
  286. }
  287. export const makeTimeSeriesList: ResultGetter = (dataList, transaction, allTransactions) => {
  288. // Prevent multiple Graph transactions to have the same colors
  289. let colorIndexOffset = 0;
  290. for (const other of allTransactions) {
  291. // Only need to consider transactions that came before the current one
  292. if (other === transaction) {
  293. break;
  294. }
  295. // Count timeseries of previous query results
  296. if (other.resultType === 'Graph' && other.done) {
  297. colorIndexOffset += other.result.length;
  298. }
  299. }
  300. return dataList.map((seriesData, index: number) => {
  301. const datapoints = seriesData.datapoints || [];
  302. const alias = seriesData.target;
  303. const colorIndex = (colorIndexOffset + index) % colors.length;
  304. const color = colors[colorIndex];
  305. const series = new TimeSeries({
  306. datapoints,
  307. alias,
  308. color,
  309. unit: seriesData.unit,
  310. });
  311. return series;
  312. });
  313. };
  314. /**
  315. * Update the query history. Side-effect: store history in local storage
  316. */
  317. export function updateHistory<T extends DataQuery = any>(
  318. history: Array<HistoryItem<T>>,
  319. datasourceId: string,
  320. queries: T[]
  321. ): Array<HistoryItem<T>> {
  322. const ts = Date.now();
  323. queries.forEach(query => {
  324. history = [{ query, ts }, ...history];
  325. });
  326. if (history.length > MAX_HISTORY_ITEMS) {
  327. history = history.slice(0, MAX_HISTORY_ITEMS);
  328. }
  329. // Combine all queries of a datasource type into one history
  330. const historyKey = `grafana.explore.history.${datasourceId}`;
  331. store.setObject(historyKey, history);
  332. return history;
  333. }
  334. export function clearHistory(datasourceId: string) {
  335. const historyKey = `grafana.explore.history.${datasourceId}`;
  336. store.delete(historyKey);
  337. }
  338. export const getQueryKeys = (queries: DataQuery[], datasourceInstance: DataSourceApi): string[] => {
  339. const queryKeys = queries.reduce((newQueryKeys, query, index) => {
  340. const primaryKey = datasourceInstance && datasourceInstance.name ? datasourceInstance.name : query.key;
  341. return newQueryKeys.concat(`${primaryKey}-${index}`);
  342. }, []);
  343. return queryKeys;
  344. };