explore.ts 12 KB

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