explore.ts 11 KB

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