explore.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. // Libraries
  2. import _ from 'lodash';
  3. import { Unsubscribable } from 'rxjs';
  4. import { isLive } from '@grafana/ui/src/components/RefreshPicker/RefreshPicker';
  5. // Services & Utils
  6. import {
  7. dateMath,
  8. toUtc,
  9. TimeRange,
  10. RawTimeRange,
  11. TimeZone,
  12. TimeFragment,
  13. LogRowModel,
  14. LogsModel,
  15. LogsDedupStrategy,
  16. DefaultTimeZone,
  17. } from '@grafana/data';
  18. import { renderUrl } from 'app/core/utils/url';
  19. import store from 'app/core/store';
  20. import { getNextRefIdChar } from './query';
  21. // Types
  22. import { DataQuery, DataSourceApi, DataQueryError, DataQueryRequest, PanelModel } from '@grafana/ui';
  23. import {
  24. ExploreUrlState,
  25. HistoryItem,
  26. QueryTransaction,
  27. QueryIntervals,
  28. QueryOptions,
  29. ExploreMode,
  30. } from 'app/types/explore';
  31. import { config } from '../config';
  32. import { TimeSrv } from 'app/features/dashboard/services/TimeSrv';
  33. export const DEFAULT_RANGE = {
  34. from: 'now-1h',
  35. to: 'now',
  36. };
  37. export const DEFAULT_UI_STATE = {
  38. showingTable: true,
  39. showingGraph: true,
  40. showingLogs: true,
  41. dedupStrategy: LogsDedupStrategy.none,
  42. };
  43. const MAX_HISTORY_ITEMS = 100;
  44. export const LAST_USED_DATASOURCE_KEY = 'grafana.explore.datasource';
  45. export const lastUsedDatasourceKeyForOrgId = (orgId: number) => `${LAST_USED_DATASOURCE_KEY}.${orgId}`;
  46. /**
  47. * Returns an Explore-URL that contains a panel's queries and the dashboard time range.
  48. *
  49. * @param panelTargets The origin panel's query targets
  50. * @param panelDatasource The origin panel's datasource
  51. * @param datasourceSrv Datasource service to query other datasources in case the panel datasource is mixed
  52. * @param timeSrv Time service to get the current dashboard range from
  53. */
  54. export async function getExploreUrl(
  55. panel: PanelModel,
  56. panelTargets: DataQuery[],
  57. panelDatasource: any,
  58. datasourceSrv: any,
  59. timeSrv: TimeSrv
  60. ) {
  61. let exploreDatasource = panelDatasource;
  62. let exploreTargets: DataQuery[] = panelTargets;
  63. let url: string;
  64. // Mixed datasources need to choose only one datasource
  65. if (panelDatasource.meta.id === 'mixed' && exploreTargets) {
  66. // Find first explore datasource among targets
  67. for (const t of exploreTargets) {
  68. const datasource = await datasourceSrv.get(t.datasource);
  69. if (datasource) {
  70. exploreDatasource = datasource;
  71. exploreTargets = panelTargets.filter(t => t.datasource === datasource.name);
  72. break;
  73. }
  74. }
  75. }
  76. if (exploreDatasource) {
  77. const range = timeSrv.timeRangeForUrl();
  78. let state: Partial<ExploreUrlState> = { range };
  79. if (exploreDatasource.getExploreState) {
  80. state = { ...state, ...exploreDatasource.getExploreState(exploreTargets) };
  81. } else {
  82. state = {
  83. ...state,
  84. datasource: exploreDatasource.name,
  85. queries: exploreTargets.map(t => ({ ...t, datasource: exploreDatasource.name })),
  86. };
  87. }
  88. const exploreState = JSON.stringify({ ...state, originPanelId: panel.id });
  89. url = renderUrl('/explore', { left: exploreState });
  90. }
  91. return url;
  92. }
  93. export function buildQueryTransaction(
  94. queries: DataQuery[],
  95. queryOptions: QueryOptions,
  96. range: TimeRange,
  97. queryIntervals: QueryIntervals,
  98. scanning: boolean
  99. ): QueryTransaction {
  100. const { interval, intervalMs } = queryIntervals;
  101. const configuredQueries = queries.map(query => ({ ...query, ...queryOptions }));
  102. const key = queries.reduce((combinedKey, query) => {
  103. combinedKey += query.key;
  104. return combinedKey;
  105. }, '');
  106. // Most datasource is using `panelId + query.refId` for cancellation logic.
  107. // Using `format` here because it relates to the view panel that the request is for.
  108. // However, some datasources don't use `panelId + query.refId`, but only `panelId`.
  109. // Therefore panel id has to be unique.
  110. const panelId = `${key}`;
  111. const request: DataQueryRequest = {
  112. dashboardId: 0,
  113. // TODO probably should be taken from preferences but does not seem to be used anyway.
  114. timezone: DefaultTimeZone,
  115. startTime: Date.now(),
  116. interval,
  117. intervalMs,
  118. // TODO: the query request expects number and we are using string here. Seems like it works so far but can create
  119. // issues down the road.
  120. panelId: panelId as any,
  121. targets: configuredQueries, // Datasources rely on DataQueries being passed under the targets key.
  122. range,
  123. requestId: 'explore',
  124. rangeRaw: range.raw,
  125. scopedVars: {
  126. __interval: { text: interval, value: interval },
  127. __interval_ms: { text: intervalMs, value: intervalMs },
  128. },
  129. maxDataPoints: queryOptions.maxDataPoints,
  130. };
  131. return {
  132. queries,
  133. request,
  134. scanning,
  135. id: generateKey(), // reusing for unique ID
  136. done: false,
  137. latency: 0,
  138. };
  139. }
  140. export const clearQueryKeys: (query: DataQuery) => object = ({ key, refId, ...rest }) => rest;
  141. const isSegment = (segment: { [key: string]: string }, ...props: string[]) =>
  142. props.some(prop => segment.hasOwnProperty(prop));
  143. enum ParseUrlStateIndex {
  144. RangeFrom = 0,
  145. RangeTo = 1,
  146. Datasource = 2,
  147. SegmentsStart = 3,
  148. }
  149. enum ParseUiStateIndex {
  150. Graph = 0,
  151. Logs = 1,
  152. Table = 2,
  153. Strategy = 3,
  154. }
  155. export const safeParseJson = (text: string) => {
  156. if (!text) {
  157. return;
  158. }
  159. try {
  160. return JSON.parse(decodeURI(text));
  161. } catch (error) {
  162. console.error(error);
  163. }
  164. };
  165. export const safeStringifyValue = (value: any, space?: number) => {
  166. if (!value) {
  167. return '';
  168. }
  169. try {
  170. return JSON.stringify(value, null, space);
  171. } catch (error) {
  172. console.error(error);
  173. }
  174. return '';
  175. };
  176. export function parseUrlState(initial: string | undefined): ExploreUrlState {
  177. const parsed = safeParseJson(initial);
  178. const errorResult: any = {
  179. datasource: null,
  180. queries: [],
  181. range: DEFAULT_RANGE,
  182. ui: DEFAULT_UI_STATE,
  183. mode: null,
  184. originPanelId: null,
  185. };
  186. if (!parsed) {
  187. return errorResult;
  188. }
  189. if (!Array.isArray(parsed)) {
  190. return parsed;
  191. }
  192. if (parsed.length <= ParseUrlStateIndex.SegmentsStart) {
  193. console.error('Error parsing compact URL state for Explore.');
  194. return errorResult;
  195. }
  196. const range = {
  197. from: parsed[ParseUrlStateIndex.RangeFrom],
  198. to: parsed[ParseUrlStateIndex.RangeTo],
  199. };
  200. const datasource = parsed[ParseUrlStateIndex.Datasource];
  201. const parsedSegments = parsed.slice(ParseUrlStateIndex.SegmentsStart);
  202. const metricProperties = ['expr', 'target', 'datasource', 'query'];
  203. const queries = parsedSegments.filter(segment => isSegment(segment, ...metricProperties));
  204. const modeObj = parsedSegments.filter(segment => isSegment(segment, 'mode'))[0];
  205. const mode = modeObj ? modeObj.mode : ExploreMode.Metrics;
  206. const uiState = parsedSegments.filter(segment => isSegment(segment, 'ui'))[0];
  207. const ui = uiState
  208. ? {
  209. showingGraph: uiState.ui[ParseUiStateIndex.Graph],
  210. showingLogs: uiState.ui[ParseUiStateIndex.Logs],
  211. showingTable: uiState.ui[ParseUiStateIndex.Table],
  212. dedupStrategy: uiState.ui[ParseUiStateIndex.Strategy],
  213. }
  214. : DEFAULT_UI_STATE;
  215. const originPanelId = parsedSegments.filter(segment => isSegment(segment, 'originPanelId'))[0];
  216. return { datasource, queries, range, ui, mode, originPanelId };
  217. }
  218. export function serializeStateToUrlParam(urlState: ExploreUrlState, compact?: boolean): string {
  219. if (compact) {
  220. return JSON.stringify([
  221. urlState.range.from,
  222. urlState.range.to,
  223. urlState.datasource,
  224. ...urlState.queries,
  225. { mode: urlState.mode },
  226. {
  227. ui: [
  228. !!urlState.ui.showingGraph,
  229. !!urlState.ui.showingLogs,
  230. !!urlState.ui.showingTable,
  231. urlState.ui.dedupStrategy,
  232. ],
  233. },
  234. ]);
  235. }
  236. return JSON.stringify(urlState);
  237. }
  238. export function generateKey(index = 0): string {
  239. return `Q-${Date.now()}-${Math.random()}-${index}`;
  240. }
  241. export function generateEmptyQuery(queries: DataQuery[], index = 0): DataQuery {
  242. return { refId: getNextRefIdChar(queries), key: generateKey(index) };
  243. }
  244. export const generateNewKeyAndAddRefIdIfMissing = (target: DataQuery, queries: DataQuery[], index = 0): DataQuery => {
  245. const key = generateKey(index);
  246. const refId = target.refId || getNextRefIdChar(queries);
  247. return { ...target, refId, key };
  248. };
  249. /**
  250. * Ensure at least one target exists and that targets have the necessary keys
  251. */
  252. export function ensureQueries(queries?: DataQuery[]): DataQuery[] {
  253. if (queries && typeof queries === 'object' && queries.length > 0) {
  254. const allQueries = [];
  255. for (let index = 0; index < queries.length; index++) {
  256. const query = queries[index];
  257. const key = generateKey(index);
  258. let refId = query.refId;
  259. if (!refId) {
  260. refId = getNextRefIdChar(allQueries);
  261. }
  262. allQueries.push({
  263. ...query,
  264. refId,
  265. key,
  266. });
  267. }
  268. return allQueries;
  269. }
  270. return [{ ...generateEmptyQuery(queries) }];
  271. }
  272. /**
  273. * A target is non-empty when it has keys (with non-empty values) other than refId, key and context.
  274. */
  275. const validKeys = ['refId', 'key', 'context'];
  276. export function hasNonEmptyQuery<TQuery extends DataQuery = any>(queries: TQuery[]): boolean {
  277. return (
  278. queries &&
  279. queries.some((query: any) => {
  280. const keys = Object.keys(query)
  281. .filter(key => validKeys.indexOf(key) === -1)
  282. .map(k => query[k])
  283. .filter(v => v);
  284. return keys.length > 0;
  285. })
  286. );
  287. }
  288. /**
  289. * Update the query history. Side-effect: store history in local storage
  290. */
  291. export function updateHistory<T extends DataQuery = any>(
  292. history: Array<HistoryItem<T>>,
  293. datasourceId: string,
  294. queries: T[]
  295. ): Array<HistoryItem<T>> {
  296. const ts = Date.now();
  297. queries.forEach(query => {
  298. history = [{ query, ts }, ...history];
  299. });
  300. if (history.length > MAX_HISTORY_ITEMS) {
  301. history = history.slice(0, MAX_HISTORY_ITEMS);
  302. }
  303. // Combine all queries of a datasource type into one history
  304. const historyKey = `grafana.explore.history.${datasourceId}`;
  305. store.setObject(historyKey, history);
  306. return history;
  307. }
  308. export function clearHistory(datasourceId: string) {
  309. const historyKey = `grafana.explore.history.${datasourceId}`;
  310. store.delete(historyKey);
  311. }
  312. export const getQueryKeys = (queries: DataQuery[], datasourceInstance: DataSourceApi): string[] => {
  313. const queryKeys = queries.reduce((newQueryKeys, query, index) => {
  314. const primaryKey = datasourceInstance && datasourceInstance.name ? datasourceInstance.name : query.key;
  315. return newQueryKeys.concat(`${primaryKey}-${index}`);
  316. }, []);
  317. return queryKeys;
  318. };
  319. export const getTimeRange = (timeZone: TimeZone, rawRange: RawTimeRange): TimeRange => {
  320. return {
  321. from: dateMath.parse(rawRange.from, false, timeZone as any),
  322. to: dateMath.parse(rawRange.to, true, timeZone as any),
  323. raw: rawRange,
  324. };
  325. };
  326. const parseRawTime = (value: any): TimeFragment => {
  327. if (value === null) {
  328. return null;
  329. }
  330. if (value.indexOf('now') !== -1) {
  331. return value;
  332. }
  333. if (value.length === 8) {
  334. return toUtc(value, 'YYYYMMDD');
  335. }
  336. if (value.length === 15) {
  337. return toUtc(value, 'YYYYMMDDTHHmmss');
  338. }
  339. // Backward compatibility
  340. if (value.length === 19) {
  341. return toUtc(value, 'YYYY-MM-DD HH:mm:ss');
  342. }
  343. if (!isNaN(value)) {
  344. const epoch = parseInt(value, 10);
  345. return toUtc(epoch);
  346. }
  347. return null;
  348. };
  349. export const getTimeRangeFromUrl = (range: RawTimeRange, timeZone: TimeZone): TimeRange => {
  350. const raw = {
  351. from: parseRawTime(range.from),
  352. to: parseRawTime(range.to),
  353. };
  354. return {
  355. from: dateMath.parse(raw.from, false, timeZone as any),
  356. to: dateMath.parse(raw.to, true, timeZone as any),
  357. raw,
  358. };
  359. };
  360. export const getValueWithRefId = (value: any): any | null => {
  361. if (!value) {
  362. return null;
  363. }
  364. if (typeof value !== 'object') {
  365. return null;
  366. }
  367. if (value.refId) {
  368. return value;
  369. }
  370. const keys = Object.keys(value);
  371. for (let index = 0; index < keys.length; index++) {
  372. const key = keys[index];
  373. const refId = getValueWithRefId(value[key]);
  374. if (refId) {
  375. return refId;
  376. }
  377. }
  378. return null;
  379. };
  380. export const getFirstQueryErrorWithoutRefId = (errors: DataQueryError[]) => {
  381. if (!errors) {
  382. return null;
  383. }
  384. return errors.filter(error => (error && error.refId ? false : true))[0];
  385. };
  386. export const getRefIds = (value: any): string[] => {
  387. if (!value) {
  388. return [];
  389. }
  390. if (typeof value !== 'object') {
  391. return [];
  392. }
  393. const keys = Object.keys(value);
  394. const refIds = [];
  395. for (let index = 0; index < keys.length; index++) {
  396. const key = keys[index];
  397. if (key === 'refId') {
  398. refIds.push(value[key]);
  399. continue;
  400. }
  401. refIds.push(getRefIds(value[key]));
  402. }
  403. return _.uniq(_.flatten(refIds));
  404. };
  405. export const sortInAscendingOrder = (a: LogRowModel, b: LogRowModel) => {
  406. if (a.timestamp < b.timestamp) {
  407. return -1;
  408. }
  409. if (a.timestamp > b.timestamp) {
  410. return 1;
  411. }
  412. return 0;
  413. };
  414. const sortInDescendingOrder = (a: LogRowModel, b: LogRowModel) => {
  415. if (a.timestamp > b.timestamp) {
  416. return -1;
  417. }
  418. if (a.timestamp < b.timestamp) {
  419. return 1;
  420. }
  421. return 0;
  422. };
  423. export enum SortOrder {
  424. Descending = 'Descending',
  425. Ascending = 'Ascending',
  426. }
  427. export const refreshIntervalToSortOrder = (refreshInterval: string) =>
  428. isLive(refreshInterval) ? SortOrder.Ascending : SortOrder.Descending;
  429. export const sortLogsResult = (logsResult: LogsModel, sortOrder: SortOrder): LogsModel => {
  430. const rows = logsResult ? logsResult.rows : [];
  431. sortOrder === SortOrder.Ascending ? rows.sort(sortInAscendingOrder) : rows.sort(sortInDescendingOrder);
  432. const result: LogsModel = logsResult ? { ...logsResult, rows } : { hasUniqueLabels: false, rows };
  433. return result;
  434. };
  435. export const convertToWebSocketUrl = (url: string) => {
  436. const protocol = window.location.protocol === 'https:' ? 'wss://' : 'ws://';
  437. let backend = `${protocol}${window.location.host}${config.appSubUrl}`;
  438. if (backend.endsWith('/')) {
  439. backend = backend.slice(0, backend.length - 1);
  440. }
  441. return `${backend}${url}`;
  442. };
  443. export const stopQueryState = (querySubscription: Unsubscribable) => {
  444. if (querySubscription) {
  445. querySubscription.unsubscribe();
  446. }
  447. };