explore.ts 12 KB

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