explore.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  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. DataQueryError,
  23. } from '@grafana/ui';
  24. import TimeSeries from 'app/core/time_series2';
  25. import {
  26. ExploreUrlState,
  27. HistoryItem,
  28. QueryTransaction,
  29. ResultType,
  30. QueryIntervals,
  31. QueryOptions,
  32. ResultGetter,
  33. } from 'app/types/explore';
  34. import { LogsDedupStrategy, seriesDataToLogsModel, LogsModel, LogRowModel } from 'app/core/logs_model';
  35. import { toUtc } from '@grafana/ui/src/utils/moment_wrapper';
  36. import { isLive } from '@grafana/ui/src/components/RefreshPicker/RefreshPicker';
  37. export const DEFAULT_RANGE = {
  38. from: 'now-6h',
  39. to: 'now',
  40. };
  41. export const DEFAULT_UI_STATE = {
  42. showingTable: true,
  43. showingGraph: true,
  44. showingLogs: true,
  45. dedupStrategy: LogsDedupStrategy.none,
  46. };
  47. const MAX_HISTORY_ITEMS = 100;
  48. export const LAST_USED_DATASOURCE_KEY = 'grafana.explore.datasource';
  49. /**
  50. * Returns an Explore-URL that contains a panel's queries and the dashboard time range.
  51. *
  52. * @param panel Origin panel of the jump to Explore
  53. * @param panelTargets The origin panel's query targets
  54. * @param panelDatasource The origin panel's datasource
  55. * @param datasourceSrv Datasource service to query other datasources in case the panel datasource is mixed
  56. * @param timeSrv Time service to get the current dashboard range from
  57. */
  58. export async function getExploreUrl(
  59. panel: any,
  60. panelTargets: any[],
  61. panelDatasource: any,
  62. datasourceSrv: any,
  63. timeSrv: any
  64. ) {
  65. let exploreDatasource = panelDatasource;
  66. let exploreTargets: DataQuery[] = panelTargets;
  67. let url: string;
  68. // Mixed datasources need to choose only one datasource
  69. if (panelDatasource.meta.id === 'mixed' && panelTargets) {
  70. // Find first explore datasource among targets
  71. let mixedExploreDatasource;
  72. for (const t of panel.targets) {
  73. const datasource = await datasourceSrv.get(t.datasource);
  74. if (datasource && datasource.meta.explore) {
  75. mixedExploreDatasource = datasource;
  76. break;
  77. }
  78. }
  79. // Add all its targets
  80. if (mixedExploreDatasource) {
  81. exploreDatasource = mixedExploreDatasource;
  82. exploreTargets = panelTargets.filter(t => t.datasource === mixedExploreDatasource.name);
  83. }
  84. }
  85. if (panelDatasource) {
  86. const range = timeSrv.timeRangeForUrl();
  87. let state: Partial<ExploreUrlState> = { range };
  88. if (exploreDatasource.getExploreState) {
  89. state = { ...state, ...exploreDatasource.getExploreState(exploreTargets) };
  90. } else {
  91. state = {
  92. ...state,
  93. datasource: panelDatasource.name,
  94. queries: exploreTargets.map(t => ({ ...t, datasource: panelDatasource.name })),
  95. };
  96. }
  97. const exploreState = JSON.stringify(state);
  98. url = renderUrl('/explore', { left: exploreState });
  99. }
  100. return url;
  101. }
  102. export function buildQueryTransaction(
  103. queries: DataQuery[],
  104. resultType: ResultType,
  105. queryOptions: QueryOptions,
  106. range: TimeRange,
  107. queryIntervals: QueryIntervals,
  108. scanning: boolean
  109. ): QueryTransaction {
  110. const { interval, intervalMs } = queryIntervals;
  111. const configuredQueries = queries.map(query => ({ ...query, ...queryOptions }));
  112. const key = queries.reduce((combinedKey, query) => {
  113. combinedKey += query.key;
  114. return combinedKey;
  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}-${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. queries,
  139. options,
  140. resultType,
  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 const safeStringifyValue = (value: any, space?: number) => {
  175. if (!value) {
  176. return '';
  177. }
  178. try {
  179. return JSON.stringify(value, null, space);
  180. } catch (error) {
  181. console.error(error);
  182. }
  183. return '';
  184. };
  185. export function parseUrlState(initial: string | undefined): ExploreUrlState {
  186. const parsed = safeParseJson(initial);
  187. const errorResult = {
  188. datasource: null,
  189. queries: [],
  190. range: DEFAULT_RANGE,
  191. ui: DEFAULT_UI_STATE,
  192. };
  193. if (!parsed) {
  194. return errorResult;
  195. }
  196. if (!Array.isArray(parsed)) {
  197. return parsed;
  198. }
  199. if (parsed.length <= ParseUrlStateIndex.SegmentsStart) {
  200. console.error('Error parsing compact URL state for Explore.');
  201. return errorResult;
  202. }
  203. const range = {
  204. from: parsed[ParseUrlStateIndex.RangeFrom],
  205. to: parsed[ParseUrlStateIndex.RangeTo],
  206. };
  207. const datasource = parsed[ParseUrlStateIndex.Datasource];
  208. const parsedSegments = parsed.slice(ParseUrlStateIndex.SegmentsStart);
  209. const queries = parsedSegments.filter(segment => isMetricSegment(segment));
  210. const uiState = parsedSegments.filter(segment => isUISegment(segment))[0];
  211. const ui = uiState
  212. ? {
  213. showingGraph: uiState.ui[ParseUiStateIndex.Graph],
  214. showingLogs: uiState.ui[ParseUiStateIndex.Logs],
  215. showingTable: uiState.ui[ParseUiStateIndex.Table],
  216. dedupStrategy: uiState.ui[ParseUiStateIndex.Strategy],
  217. }
  218. : DEFAULT_UI_STATE;
  219. return { datasource, queries, range, ui };
  220. }
  221. export function serializeStateToUrlParam(urlState: ExploreUrlState, compact?: boolean): string {
  222. if (compact) {
  223. return JSON.stringify([
  224. urlState.range.from,
  225. urlState.range.to,
  226. urlState.datasource,
  227. ...urlState.queries,
  228. {
  229. ui: [
  230. !!urlState.ui.showingGraph,
  231. !!urlState.ui.showingLogs,
  232. !!urlState.ui.showingTable,
  233. urlState.ui.dedupStrategy,
  234. ],
  235. },
  236. ]);
  237. }
  238. return JSON.stringify(urlState);
  239. }
  240. export function generateKey(index = 0): string {
  241. return `Q-${Date.now()}-${Math.random()}-${index}`;
  242. }
  243. export function generateEmptyQuery(queries: DataQuery[], index = 0): DataQuery {
  244. return { refId: getNextRefIdChar(queries), key: generateKey(index) };
  245. }
  246. export const generateNewKeyAndAddRefIdIfMissing = (target: DataQuery, queries: DataQuery[], index = 0): DataQuery => {
  247. const key = generateKey(index);
  248. const refId = target.refId || getNextRefIdChar(queries);
  249. return { ...target, refId, key };
  250. };
  251. /**
  252. * Ensure at least one target exists and that targets have the necessary keys
  253. */
  254. export function ensureQueries(queries?: DataQuery[]): DataQuery[] {
  255. if (queries && typeof queries === 'object' && queries.length > 0) {
  256. const allQueries = [];
  257. for (let index = 0; index < queries.length; index++) {
  258. const query = queries[index];
  259. const key = generateKey(index);
  260. let refId = query.refId;
  261. if (!refId) {
  262. refId = getNextRefIdChar(allQueries);
  263. }
  264. allQueries.push({
  265. ...query,
  266. refId,
  267. key,
  268. });
  269. }
  270. return allQueries;
  271. }
  272. return [{ ...generateEmptyQuery(queries) }];
  273. }
  274. /**
  275. * A target is non-empty when it has keys (with non-empty values) other than refId and key.
  276. */
  277. export function hasNonEmptyQuery<TQuery extends DataQuery = any>(queries: TQuery[]): boolean {
  278. return (
  279. queries &&
  280. queries.some(
  281. query =>
  282. Object.keys(query)
  283. .map(k => query[k])
  284. .filter(v => v).length > 2
  285. )
  286. );
  287. }
  288. export function calculateResultsFromQueryTransactions(result: any, resultType: ResultType, graphInterval: number) {
  289. const flattenedResult: any[] = _.flatten(result);
  290. const graphResult = resultType === 'Graph' && result ? result : null;
  291. const tableResult =
  292. resultType === 'Table' && result
  293. ? mergeTablesIntoModel(
  294. new TableModel(),
  295. ...flattenedResult.filter((r: any) => r.columns && r.rows).map((r: any) => r as TableModel)
  296. )
  297. : mergeTablesIntoModel(new TableModel());
  298. const logsResult =
  299. resultType === 'Logs' && result
  300. ? seriesDataToLogsModel(flattenedResult.map(r => guessFieldTypes(toSeriesData(r))), graphInterval)
  301. : null;
  302. return {
  303. graphResult,
  304. tableResult,
  305. logsResult,
  306. };
  307. }
  308. export function getIntervals(range: TimeRange, lowLimit: string, resolution: number): IntervalValues {
  309. if (!resolution) {
  310. return { interval: '1s', intervalMs: 1000 };
  311. }
  312. return kbn.calculateInterval(range, resolution, lowLimit);
  313. }
  314. export const makeTimeSeriesList: ResultGetter = (dataList, transaction, allTransactions) => {
  315. // Prevent multiple Graph transactions to have the same colors
  316. let colorIndexOffset = 0;
  317. for (const other of allTransactions) {
  318. // Only need to consider transactions that came before the current one
  319. if (other === transaction) {
  320. break;
  321. }
  322. // Count timeseries of previous query results
  323. if (other.resultType === 'Graph' && other.done) {
  324. colorIndexOffset += other.result.length;
  325. }
  326. }
  327. return dataList.map((seriesData, index: number) => {
  328. const datapoints = seriesData.datapoints || [];
  329. const alias = seriesData.target;
  330. const colorIndex = (colorIndexOffset + index) % colors.length;
  331. const color = colors[colorIndex];
  332. const series = new TimeSeries({
  333. datapoints,
  334. alias,
  335. color,
  336. unit: seriesData.unit,
  337. });
  338. return series;
  339. });
  340. };
  341. /**
  342. * Update the query history. Side-effect: store history in local storage
  343. */
  344. export function updateHistory<T extends DataQuery = any>(
  345. history: Array<HistoryItem<T>>,
  346. datasourceId: string,
  347. queries: T[]
  348. ): Array<HistoryItem<T>> {
  349. const ts = Date.now();
  350. queries.forEach(query => {
  351. history = [{ query, ts }, ...history];
  352. });
  353. if (history.length > MAX_HISTORY_ITEMS) {
  354. history = history.slice(0, MAX_HISTORY_ITEMS);
  355. }
  356. // Combine all queries of a datasource type into one history
  357. const historyKey = `grafana.explore.history.${datasourceId}`;
  358. store.setObject(historyKey, history);
  359. return history;
  360. }
  361. export function clearHistory(datasourceId: string) {
  362. const historyKey = `grafana.explore.history.${datasourceId}`;
  363. store.delete(historyKey);
  364. }
  365. export const getQueryKeys = (queries: DataQuery[], datasourceInstance: DataSourceApi): string[] => {
  366. const queryKeys = queries.reduce((newQueryKeys, query, index) => {
  367. const primaryKey = datasourceInstance && datasourceInstance.name ? datasourceInstance.name : query.key;
  368. return newQueryKeys.concat(`${primaryKey}-${index}`);
  369. }, []);
  370. return queryKeys;
  371. };
  372. export const getTimeRange = (timeZone: TimeZone, rawRange: RawTimeRange): TimeRange => {
  373. return {
  374. from: dateMath.parse(rawRange.from, false, timeZone.raw as any),
  375. to: dateMath.parse(rawRange.to, true, timeZone.raw as any),
  376. raw: rawRange,
  377. };
  378. };
  379. const parseRawTime = (value): TimeFragment => {
  380. if (value === null) {
  381. return null;
  382. }
  383. if (value.indexOf('now') !== -1) {
  384. return value;
  385. }
  386. if (value.length === 8) {
  387. return toUtc(value, 'YYYYMMDD');
  388. }
  389. if (value.length === 15) {
  390. return toUtc(value, 'YYYYMMDDTHHmmss');
  391. }
  392. // Backward compatibility
  393. if (value.length === 19) {
  394. return toUtc(value, 'YYYY-MM-DD HH:mm:ss');
  395. }
  396. if (!isNaN(value)) {
  397. const epoch = parseInt(value, 10);
  398. return toUtc(epoch);
  399. }
  400. return null;
  401. };
  402. export const getTimeRangeFromUrl = (range: RawTimeRange, timeZone: TimeZone): TimeRange => {
  403. const raw = {
  404. from: parseRawTime(range.from),
  405. to: parseRawTime(range.to),
  406. };
  407. return {
  408. from: dateMath.parse(raw.from, false, timeZone.raw as any),
  409. to: dateMath.parse(raw.to, true, timeZone.raw as any),
  410. raw,
  411. };
  412. };
  413. export const instanceOfDataQueryError = (value: any): value is DataQueryError => {
  414. return value.message !== undefined && value.status !== undefined && value.statusText !== undefined;
  415. };
  416. export const getValueWithRefId = (value: any): any | null => {
  417. if (!value) {
  418. return null;
  419. }
  420. if (typeof value !== 'object') {
  421. return null;
  422. }
  423. if (value.refId) {
  424. return value;
  425. }
  426. const keys = Object.keys(value);
  427. for (let index = 0; index < keys.length; index++) {
  428. const key = keys[index];
  429. const refId = getValueWithRefId(value[key]);
  430. if (refId) {
  431. return refId;
  432. }
  433. }
  434. return null;
  435. };
  436. export const getFirstQueryErrorWithoutRefId = (errors: DataQueryError[]) => {
  437. if (!errors) {
  438. return null;
  439. }
  440. return errors.filter(error => (error.refId ? false : true))[0];
  441. };
  442. export const getRefIds = (value: any): string[] => {
  443. if (!value) {
  444. return [];
  445. }
  446. if (typeof value !== 'object') {
  447. return [];
  448. }
  449. const keys = Object.keys(value);
  450. const refIds = [];
  451. for (let index = 0; index < keys.length; index++) {
  452. const key = keys[index];
  453. if (key === 'refId') {
  454. refIds.push(value[key]);
  455. continue;
  456. }
  457. refIds.push(getRefIds(value[key]));
  458. }
  459. return _.uniq(_.flatten(refIds));
  460. };
  461. const sortInAscendingOrder = (a: LogRowModel, b: LogRowModel) => {
  462. if (a.timeEpochMs < b.timeEpochMs) {
  463. return -1;
  464. }
  465. if (a.timeEpochMs > b.timeEpochMs) {
  466. return 1;
  467. }
  468. return 0;
  469. };
  470. const sortInDescendingOrder = (a: LogRowModel, b: LogRowModel) => {
  471. if (a.timeEpochMs > b.timeEpochMs) {
  472. return -1;
  473. }
  474. if (a.timeEpochMs < b.timeEpochMs) {
  475. return 1;
  476. }
  477. return 0;
  478. };
  479. export const sortLogsResult = (logsResult: LogsModel, refreshInterval: string) => {
  480. const rows = logsResult ? logsResult.rows : [];
  481. const live = isLive(refreshInterval);
  482. live ? rows.sort(sortInAscendingOrder) : rows.sort(sortInDescendingOrder);
  483. const result: LogsModel = logsResult ? { ...logsResult, rows } : { hasUniqueLabels: false, rows };
  484. return result;
  485. };