explore.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. // Libraries
  2. import _ from 'lodash';
  3. import moment, { Moment } from 'moment';
  4. // Services & Utils
  5. import * as dateMath from 'app/core/utils/datemath';
  6. import { renderUrl } from 'app/core/utils/url';
  7. import kbn from 'app/core/utils/kbn';
  8. import store from 'app/core/store';
  9. import TableModel, { mergeTablesIntoModel } from 'app/core/table_model';
  10. import { getNextRefIdChar } from './query';
  11. // Types
  12. import { colors, TimeRange, RawTimeRange, TimeZone, IntervalValues, DataQuery, DataSourceApi } from '@grafana/ui';
  13. import TimeSeries from 'app/core/time_series2';
  14. import {
  15. ExploreUrlState,
  16. HistoryItem,
  17. QueryTransaction,
  18. ResultType,
  19. QueryIntervals,
  20. QueryOptions,
  21. ResultGetter,
  22. } from 'app/types/explore';
  23. import { LogsDedupStrategy } from 'app/core/logs_model';
  24. export const DEFAULT_RANGE = {
  25. from: 'now-6h',
  26. to: 'now',
  27. };
  28. export const DEFAULT_UI_STATE = {
  29. showingTable: true,
  30. showingGraph: true,
  31. showingLogs: true,
  32. dedupStrategy: LogsDedupStrategy.none,
  33. };
  34. const MAX_HISTORY_ITEMS = 100;
  35. export const LAST_USED_DATASOURCE_KEY = 'grafana.explore.datasource';
  36. /**
  37. * Returns an Explore-URL that contains a panel's queries and the dashboard time range.
  38. *
  39. * @param panel Origin panel of the jump to Explore
  40. * @param panelTargets The origin panel's query targets
  41. * @param panelDatasource The origin panel's datasource
  42. * @param datasourceSrv Datasource service to query other datasources in case the panel datasource is mixed
  43. * @param timeSrv Time service to get the current dashboard range from
  44. */
  45. export async function getExploreUrl(
  46. panel: any,
  47. panelTargets: any[],
  48. panelDatasource: any,
  49. datasourceSrv: any,
  50. timeSrv: any
  51. ) {
  52. let exploreDatasource = panelDatasource;
  53. let exploreTargets: DataQuery[] = panelTargets;
  54. let url: string;
  55. // Mixed datasources need to choose only one datasource
  56. if (panelDatasource.meta.id === 'mixed' && panelTargets) {
  57. // Find first explore datasource among targets
  58. let mixedExploreDatasource;
  59. for (const t of panel.targets) {
  60. const datasource = await datasourceSrv.get(t.datasource);
  61. if (datasource && datasource.meta.explore) {
  62. mixedExploreDatasource = datasource;
  63. break;
  64. }
  65. }
  66. // Add all its targets
  67. if (mixedExploreDatasource) {
  68. exploreDatasource = mixedExploreDatasource;
  69. exploreTargets = panelTargets.filter(t => t.datasource === mixedExploreDatasource.name);
  70. }
  71. }
  72. if (panelDatasource) {
  73. const range = timeSrv.timeRangeForUrl();
  74. let state: Partial<ExploreUrlState> = { range };
  75. if (exploreDatasource.getExploreState) {
  76. state = { ...state, ...exploreDatasource.getExploreState(exploreTargets) };
  77. } else {
  78. state = {
  79. ...state,
  80. datasource: panelDatasource.name,
  81. queries: exploreTargets.map(t => ({ ...t, datasource: panelDatasource.name })),
  82. };
  83. }
  84. const exploreState = JSON.stringify(state);
  85. url = renderUrl('/explore', { left: exploreState });
  86. }
  87. return url;
  88. }
  89. export function buildQueryTransaction(
  90. query: DataQuery,
  91. rowIndex: number,
  92. resultType: ResultType,
  93. queryOptions: QueryOptions,
  94. range: TimeRange,
  95. queryIntervals: QueryIntervals,
  96. scanning: boolean
  97. ): QueryTransaction {
  98. const { interval, intervalMs } = queryIntervals;
  99. const configuredQueries = [
  100. {
  101. ...query,
  102. ...queryOptions,
  103. },
  104. ];
  105. // Clone range for query request
  106. // const queryRange: RawTimeRange = { ...range };
  107. // const { from, to, raw } = this.timeSrv.timeRange();
  108. // Most datasource is using `panelId + query.refId` for cancellation logic.
  109. // Using `format` here because it relates to the view panel that the request is for.
  110. // However, some datasources don't use `panelId + query.refId`, but only `panelId`.
  111. // Therefore panel id has to be unique.
  112. const panelId = `${queryOptions.format}-${query.key}`;
  113. const options = {
  114. interval,
  115. intervalMs,
  116. panelId,
  117. targets: configuredQueries, // Datasources rely on DataQueries being passed under the targets key.
  118. range,
  119. rangeRaw: range.raw,
  120. scopedVars: {
  121. __interval: { text: interval, value: interval },
  122. __interval_ms: { text: intervalMs, value: intervalMs },
  123. },
  124. maxDataPoints: queryOptions.maxDataPoints,
  125. };
  126. return {
  127. options,
  128. query,
  129. resultType,
  130. rowIndex,
  131. scanning,
  132. id: generateKey(), // reusing for unique ID
  133. done: false,
  134. latency: 0,
  135. };
  136. }
  137. export const clearQueryKeys: (query: DataQuery) => object = ({ key, refId, ...rest }) => rest;
  138. const metricProperties = ['expr', 'target', 'datasource'];
  139. const isMetricSegment = (segment: { [key: string]: string }) =>
  140. metricProperties.some(prop => segment.hasOwnProperty(prop));
  141. const isUISegment = (segment: { [key: string]: string }) => segment.hasOwnProperty('ui');
  142. enum ParseUrlStateIndex {
  143. RangeFrom = 0,
  144. RangeTo = 1,
  145. Datasource = 2,
  146. SegmentsStart = 3,
  147. }
  148. enum ParseUiStateIndex {
  149. Graph = 0,
  150. Logs = 1,
  151. Table = 2,
  152. Strategy = 3,
  153. }
  154. export const safeParseJson = (text: string) => {
  155. if (!text) {
  156. return;
  157. }
  158. try {
  159. return JSON.parse(decodeURI(text));
  160. } catch (error) {
  161. console.error(error);
  162. }
  163. };
  164. export function parseUrlState(initial: string | undefined): ExploreUrlState {
  165. const parsed = safeParseJson(initial);
  166. const errorResult = {
  167. datasource: null,
  168. queries: [],
  169. range: DEFAULT_RANGE,
  170. ui: DEFAULT_UI_STATE,
  171. };
  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: TimeRange, lowLimit: string, resolution: number): IntervalValues {
  278. if (!resolution) {
  279. return { interval: '1s', intervalMs: 1000 };
  280. }
  281. return kbn.calculateInterval(range, resolution, lowLimit);
  282. }
  283. export const makeTimeSeriesList: ResultGetter = (dataList, transaction, allTransactions) => {
  284. // Prevent multiple Graph transactions to have the same colors
  285. let colorIndexOffset = 0;
  286. for (const other of allTransactions) {
  287. // Only need to consider transactions that came before the current one
  288. if (other === transaction) {
  289. break;
  290. }
  291. // Count timeseries of previous query results
  292. if (other.resultType === 'Graph' && other.done) {
  293. colorIndexOffset += other.result.length;
  294. }
  295. }
  296. return dataList.map((seriesData, index: number) => {
  297. const datapoints = seriesData.datapoints || [];
  298. const alias = seriesData.target;
  299. const colorIndex = (colorIndexOffset + index) % colors.length;
  300. const color = colors[colorIndex];
  301. const series = new TimeSeries({
  302. datapoints,
  303. alias,
  304. color,
  305. unit: seriesData.unit,
  306. });
  307. return series;
  308. });
  309. };
  310. /**
  311. * Update the query history. Side-effect: store history in local storage
  312. */
  313. export function updateHistory<T extends DataQuery = any>(
  314. history: Array<HistoryItem<T>>,
  315. datasourceId: string,
  316. queries: T[]
  317. ): Array<HistoryItem<T>> {
  318. const ts = Date.now();
  319. queries.forEach(query => {
  320. history = [{ query, ts }, ...history];
  321. });
  322. if (history.length > MAX_HISTORY_ITEMS) {
  323. history = history.slice(0, MAX_HISTORY_ITEMS);
  324. }
  325. // Combine all queries of a datasource type into one history
  326. const historyKey = `grafana.explore.history.${datasourceId}`;
  327. store.setObject(historyKey, history);
  328. return history;
  329. }
  330. export function clearHistory(datasourceId: string) {
  331. const historyKey = `grafana.explore.history.${datasourceId}`;
  332. store.delete(historyKey);
  333. }
  334. export const getQueryKeys = (queries: DataQuery[], datasourceInstance: DataSourceApi): string[] => {
  335. const queryKeys = queries.reduce((newQueryKeys, query, index) => {
  336. const primaryKey = datasourceInstance && datasourceInstance.name ? datasourceInstance.name : query.key;
  337. return newQueryKeys.concat(`${primaryKey}-${index}`);
  338. }, []);
  339. return queryKeys;
  340. };
  341. export const getTimeRange = (timeZone: TimeZone, rawRange: RawTimeRange): TimeRange => {
  342. return {
  343. from: dateMath.parse(rawRange.from, false, timeZone.raw as any),
  344. to: dateMath.parse(rawRange.to, true, timeZone.raw as any),
  345. raw: rawRange,
  346. };
  347. };
  348. const parseRawTime = (value): Moment | string => {
  349. if (value === null) {
  350. return null;
  351. }
  352. if (value.indexOf('now') !== -1) {
  353. return value;
  354. }
  355. if (value.length === 8) {
  356. return moment.utc(value, 'YYYYMMDD');
  357. }
  358. if (value.length === 15) {
  359. return moment.utc(value, 'YYYYMMDDTHHmmss');
  360. }
  361. // Backward compatibility
  362. if (value.length === 19) {
  363. return moment.utc(value, 'YYYY-MM-DD HH:mm:ss');
  364. }
  365. if (!isNaN(value)) {
  366. const epoch = parseInt(value, 10);
  367. return moment.utc(epoch);
  368. }
  369. return null;
  370. };
  371. export const getTimeRangeFromUrl = (range: RawTimeRange, timeZone: TimeZone): TimeRange => {
  372. const raw = {
  373. from: parseRawTime(range.from),
  374. to: parseRawTime(range.to),
  375. };
  376. return {
  377. from: dateMath.parse(raw.from, false, timeZone.raw as any),
  378. to: dateMath.parse(raw.to, true, timeZone.raw as any),
  379. raw,
  380. };
  381. };