explore.ts 14 KB

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