explore.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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. };
  130. return {
  131. options,
  132. query,
  133. resultType,
  134. rowIndex,
  135. scanning,
  136. id: generateKey(), // reusing for unique ID
  137. done: false,
  138. latency: 0,
  139. };
  140. }
  141. export const clearQueryKeys: (query: DataQuery) => object = ({ key, refId, ...rest }) => rest;
  142. const metricProperties = ['expr', 'target', 'datasource'];
  143. const isMetricSegment = (segment: { [key: string]: string }) =>
  144. metricProperties.some(prop => segment.hasOwnProperty(prop));
  145. const isUISegment = (segment: { [key: string]: string }) => segment.hasOwnProperty('ui');
  146. enum ParseUrlStateIndex {
  147. RangeFrom = 0,
  148. RangeTo = 1,
  149. Datasource = 2,
  150. SegmentsStart = 3,
  151. }
  152. enum ParseUiStateIndex {
  153. Graph = 0,
  154. Logs = 1,
  155. Table = 2,
  156. Strategy = 3,
  157. }
  158. export const safeParseJson = (text: string) => {
  159. if (!text) {
  160. return;
  161. }
  162. try {
  163. return JSON.parse(decodeURI(text));
  164. } catch (error) {
  165. console.error(error);
  166. }
  167. };
  168. export function parseUrlState(initial: string | undefined): ExploreUrlState {
  169. const parsed = safeParseJson(initial);
  170. const errorResult = { datasource: null, queries: [], range: DEFAULT_RANGE, ui: DEFAULT_UI_STATE };
  171. if (!parsed) {
  172. return errorResult;
  173. }
  174. if (!Array.isArray(parsed)) {
  175. return parsed;
  176. }
  177. if (parsed.length <= ParseUrlStateIndex.SegmentsStart) {
  178. console.error('Error parsing compact URL state for Explore.');
  179. return errorResult;
  180. }
  181. const range = {
  182. from: parsed[ParseUrlStateIndex.RangeFrom],
  183. to: parsed[ParseUrlStateIndex.RangeTo],
  184. };
  185. const datasource = parsed[ParseUrlStateIndex.Datasource];
  186. const parsedSegments = parsed.slice(ParseUrlStateIndex.SegmentsStart);
  187. const queries = parsedSegments.filter(segment => isMetricSegment(segment));
  188. const uiState = parsedSegments.filter(segment => isUISegment(segment))[0];
  189. const ui = uiState
  190. ? {
  191. showingGraph: uiState.ui[ParseUiStateIndex.Graph],
  192. showingLogs: uiState.ui[ParseUiStateIndex.Logs],
  193. showingTable: uiState.ui[ParseUiStateIndex.Table],
  194. dedupStrategy: uiState.ui[ParseUiStateIndex.Strategy],
  195. }
  196. : DEFAULT_UI_STATE;
  197. return { datasource, queries, range, ui };
  198. }
  199. export function serializeStateToUrlParam(urlState: ExploreUrlState, compact?: boolean): string {
  200. if (compact) {
  201. return JSON.stringify([
  202. urlState.range.from,
  203. urlState.range.to,
  204. urlState.datasource,
  205. ...urlState.queries,
  206. {
  207. ui: [
  208. !!urlState.ui.showingGraph,
  209. !!urlState.ui.showingLogs,
  210. !!urlState.ui.showingTable,
  211. urlState.ui.dedupStrategy,
  212. ],
  213. },
  214. ]);
  215. }
  216. return JSON.stringify(urlState);
  217. }
  218. export function generateKey(index = 0): string {
  219. return `Q-${Date.now()}-${Math.random()}-${index}`;
  220. }
  221. export function generateEmptyQuery(queries: DataQuery[], index = 0): DataQuery {
  222. return { refId: getNextRefIdChar(queries), key: generateKey(index) };
  223. }
  224. /**
  225. * Ensure at least one target exists and that targets have the necessary keys
  226. */
  227. export function ensureQueries(queries?: DataQuery[]): DataQuery[] {
  228. if (queries && typeof queries === 'object' && queries.length > 0) {
  229. return queries.map((query, i) => ({ ...query, ...generateEmptyQuery(queries, i) }));
  230. }
  231. return [{ ...generateEmptyQuery(queries) }];
  232. }
  233. /**
  234. * A target is non-empty when it has keys (with non-empty values) other than refId and key.
  235. */
  236. export function hasNonEmptyQuery<TQuery extends DataQuery = any>(queries: TQuery[]): boolean {
  237. return (
  238. queries &&
  239. queries.some(
  240. query =>
  241. Object.keys(query)
  242. .map(k => query[k])
  243. .filter(v => v).length > 2
  244. )
  245. );
  246. }
  247. export function calculateResultsFromQueryTransactions(
  248. queryTransactions: QueryTransaction[],
  249. datasource: any,
  250. graphInterval: number
  251. ) {
  252. const graphResult = _.flatten(
  253. queryTransactions.filter(qt => qt.resultType === 'Graph' && qt.done && qt.result).map(qt => qt.result)
  254. );
  255. const tableResult = mergeTablesIntoModel(
  256. new TableModel(),
  257. ...queryTransactions
  258. .filter(qt => qt.resultType === 'Table' && qt.done && qt.result && qt.result.columns && qt.result.rows)
  259. .map(qt => qt.result)
  260. );
  261. const logsResult =
  262. datasource && datasource.mergeStreams
  263. ? datasource.mergeStreams(
  264. _.flatten(
  265. queryTransactions.filter(qt => qt.resultType === 'Logs' && qt.done && qt.result).map(qt => qt.result)
  266. ),
  267. graphInterval
  268. )
  269. : undefined;
  270. return {
  271. graphResult,
  272. tableResult,
  273. logsResult,
  274. };
  275. }
  276. export function getIntervals(range: RawTimeRange, lowLimit: string, resolution: number): IntervalValues {
  277. if (!resolution) {
  278. return { interval: '1s', intervalMs: 1000 };
  279. }
  280. const absoluteRange: RawTimeRange = {
  281. from: parseDate(range.from, false),
  282. to: parseDate(range.to, true),
  283. };
  284. return kbn.calculateInterval(absoluteRange, resolution, lowLimit);
  285. }
  286. export const makeTimeSeriesList: ResultGetter = (dataList, transaction, allTransactions) => {
  287. // Prevent multiple Graph transactions to have the same colors
  288. let colorIndexOffset = 0;
  289. for (const other of allTransactions) {
  290. // Only need to consider transactions that came before the current one
  291. if (other === transaction) {
  292. break;
  293. }
  294. // Count timeseries of previous query results
  295. if (other.resultType === 'Graph' && other.done) {
  296. colorIndexOffset += other.result.length;
  297. }
  298. }
  299. return dataList.map((seriesData, index: number) => {
  300. const datapoints = seriesData.datapoints || [];
  301. const alias = seriesData.target;
  302. const colorIndex = (colorIndexOffset + index) % colors.length;
  303. const color = colors[colorIndex];
  304. const series = new TimeSeries({
  305. datapoints,
  306. alias,
  307. color,
  308. unit: seriesData.unit,
  309. });
  310. return series;
  311. });
  312. };
  313. /**
  314. * Update the query history. Side-effect: store history in local storage
  315. */
  316. export function updateHistory<T extends DataQuery = any>(
  317. history: Array<HistoryItem<T>>,
  318. datasourceId: string,
  319. queries: T[]
  320. ): Array<HistoryItem<T>> {
  321. const ts = Date.now();
  322. queries.forEach(query => {
  323. history = [{ query, ts }, ...history];
  324. });
  325. if (history.length > MAX_HISTORY_ITEMS) {
  326. history = history.slice(0, MAX_HISTORY_ITEMS);
  327. }
  328. // Combine all queries of a datasource type into one history
  329. const historyKey = `grafana.explore.history.${datasourceId}`;
  330. store.setObject(historyKey, history);
  331. return history;
  332. }
  333. export function clearHistory(datasourceId: string) {
  334. const historyKey = `grafana.explore.history.${datasourceId}`;
  335. store.delete(historyKey);
  336. }
  337. export const getQueryKeys = (queries: DataQuery[], datasourceInstance: DataSourceApi): string[] => {
  338. const queryKeys = queries.reduce((newQueryKeys, query, index) => {
  339. const primaryKey = datasourceInstance && datasourceInstance.name ? datasourceInstance.name : query.key;
  340. return newQueryKeys.concat(`${primaryKey}-${index}`);
  341. }, []);
  342. return queryKeys;
  343. };