explore.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. // Libraries
  2. import _ from 'lodash';
  3. import { isLive } from '@grafana/ui/src/components/RefreshPicker/RefreshPicker';
  4. // Services & Utils
  5. import {
  6. dateMath,
  7. toUtc,
  8. TimeRange,
  9. RawTimeRange,
  10. TimeZone,
  11. TimeFragment,
  12. LogRowModel,
  13. LogsModel,
  14. LogsDedupStrategy,
  15. DefaultTimeZone,
  16. } from '@grafana/data';
  17. import { renderUrl } from 'app/core/utils/url';
  18. import store from 'app/core/store';
  19. import { getNextRefIdChar } from './query';
  20. // Types
  21. import { DataQuery, DataSourceApi, DataQueryError, DataQueryRequest, PanelModel } from '@grafana/ui';
  22. import {
  23. ExploreUrlState,
  24. HistoryItem,
  25. QueryTransaction,
  26. QueryIntervals,
  27. QueryOptions,
  28. ExploreMode,
  29. } from 'app/types/explore';
  30. import { config } from '../config';
  31. import { PanelQueryState } from '../../features/dashboard/state/PanelQueryState';
  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. // This is set to correct time later on before the query is actually run.
  116. startTime: 0,
  117. interval,
  118. intervalMs,
  119. // TODO: the query request expects number and we are using string here. Seems like it works so far but can create
  120. // issues down the road.
  121. panelId: panelId as any,
  122. targets: configuredQueries, // Datasources rely on DataQueries being passed under the targets key.
  123. range,
  124. requestId: 'explore',
  125. rangeRaw: range.raw,
  126. scopedVars: {
  127. __interval: { text: interval, value: interval },
  128. __interval_ms: { text: intervalMs, value: intervalMs },
  129. },
  130. maxDataPoints: queryOptions.maxDataPoints,
  131. };
  132. return {
  133. queries,
  134. request,
  135. scanning,
  136. id: generateKey(), // reusing for unique ID
  137. done: false,
  138. latency: 0,
  139. };
  140. }
  141. export const clearQueryKeys: (query: DataQuery) => object = ({ key, refId, ...rest }) => rest;
  142. const isSegment = (segment: { [key: string]: string }, ...props: string[]) =>
  143. props.some(prop => segment.hasOwnProperty(prop));
  144. enum ParseUrlStateIndex {
  145. RangeFrom = 0,
  146. RangeTo = 1,
  147. Datasource = 2,
  148. SegmentsStart = 3,
  149. }
  150. enum ParseUiStateIndex {
  151. Graph = 0,
  152. Logs = 1,
  153. Table = 2,
  154. Strategy = 3,
  155. }
  156. export const safeParseJson = (text: string) => {
  157. if (!text) {
  158. return;
  159. }
  160. try {
  161. return JSON.parse(decodeURI(text));
  162. } catch (error) {
  163. console.error(error);
  164. }
  165. };
  166. export const safeStringifyValue = (value: any, space?: number) => {
  167. if (!value) {
  168. return '';
  169. }
  170. try {
  171. return JSON.stringify(value, null, space);
  172. } catch (error) {
  173. console.error(error);
  174. }
  175. return '';
  176. };
  177. export function parseUrlState(initial: string | undefined): ExploreUrlState {
  178. const parsed = safeParseJson(initial);
  179. const errorResult: any = {
  180. datasource: null,
  181. queries: [],
  182. range: DEFAULT_RANGE,
  183. ui: DEFAULT_UI_STATE,
  184. mode: null,
  185. originPanelId: null,
  186. };
  187. if (!parsed) {
  188. return errorResult;
  189. }
  190. if (!Array.isArray(parsed)) {
  191. return parsed;
  192. }
  193. if (parsed.length <= ParseUrlStateIndex.SegmentsStart) {
  194. console.error('Error parsing compact URL state for Explore.');
  195. return errorResult;
  196. }
  197. const range = {
  198. from: parsed[ParseUrlStateIndex.RangeFrom],
  199. to: parsed[ParseUrlStateIndex.RangeTo],
  200. };
  201. const datasource = parsed[ParseUrlStateIndex.Datasource];
  202. const parsedSegments = parsed.slice(ParseUrlStateIndex.SegmentsStart);
  203. const metricProperties = ['expr', 'target', 'datasource', 'query'];
  204. const queries = parsedSegments.filter(segment => isSegment(segment, ...metricProperties));
  205. const modeObj = parsedSegments.filter(segment => isSegment(segment, 'mode'))[0];
  206. const mode = modeObj ? modeObj.mode : ExploreMode.Metrics;
  207. const uiState = parsedSegments.filter(segment => isSegment(segment, 'ui'))[0];
  208. const ui = uiState
  209. ? {
  210. showingGraph: uiState.ui[ParseUiStateIndex.Graph],
  211. showingLogs: uiState.ui[ParseUiStateIndex.Logs],
  212. showingTable: uiState.ui[ParseUiStateIndex.Table],
  213. dedupStrategy: uiState.ui[ParseUiStateIndex.Strategy],
  214. }
  215. : DEFAULT_UI_STATE;
  216. const originPanelId = parsedSegments.filter(segment => isSegment(segment, 'originPanelId'))[0];
  217. return { datasource, queries, range, ui, mode, originPanelId };
  218. }
  219. export function serializeStateToUrlParam(urlState: ExploreUrlState, compact?: boolean): string {
  220. if (compact) {
  221. return JSON.stringify([
  222. urlState.range.from,
  223. urlState.range.to,
  224. urlState.datasource,
  225. ...urlState.queries,
  226. { mode: urlState.mode },
  227. {
  228. ui: [
  229. !!urlState.ui.showingGraph,
  230. !!urlState.ui.showingLogs,
  231. !!urlState.ui.showingTable,
  232. urlState.ui.dedupStrategy,
  233. ],
  234. },
  235. ]);
  236. }
  237. return JSON.stringify(urlState);
  238. }
  239. export function generateKey(index = 0): string {
  240. return `Q-${Date.now()}-${Math.random()}-${index}`;
  241. }
  242. export function generateEmptyQuery(queries: DataQuery[], index = 0): DataQuery {
  243. return { refId: getNextRefIdChar(queries), key: generateKey(index) };
  244. }
  245. export const generateNewKeyAndAddRefIdIfMissing = (target: DataQuery, queries: DataQuery[], index = 0): DataQuery => {
  246. const key = generateKey(index);
  247. const refId = target.refId || getNextRefIdChar(queries);
  248. return { ...target, refId, key };
  249. };
  250. /**
  251. * Ensure at least one target exists and that targets have the necessary keys
  252. */
  253. export function ensureQueries(queries?: DataQuery[]): DataQuery[] {
  254. if (queries && typeof queries === 'object' && queries.length > 0) {
  255. const allQueries = [];
  256. for (let index = 0; index < queries.length; index++) {
  257. const query = queries[index];
  258. const key = generateKey(index);
  259. let refId = query.refId;
  260. if (!refId) {
  261. refId = getNextRefIdChar(allQueries);
  262. }
  263. allQueries.push({
  264. ...query,
  265. refId,
  266. key,
  267. });
  268. }
  269. return allQueries;
  270. }
  271. return [{ ...generateEmptyQuery(queries) }];
  272. }
  273. /**
  274. * A target is non-empty when it has keys (with non-empty values) other than refId, key and context.
  275. */
  276. const validKeys = ['refId', 'key', 'context'];
  277. export function hasNonEmptyQuery<TQuery extends DataQuery = any>(queries: TQuery[]): boolean {
  278. return (
  279. queries &&
  280. queries.some((query: any) => {
  281. const keys = Object.keys(query)
  282. .filter(key => validKeys.indexOf(key) === -1)
  283. .map(k => query[k])
  284. .filter(v => v);
  285. return keys.length > 0;
  286. })
  287. );
  288. }
  289. /**
  290. * Update the query history. Side-effect: store history in local storage
  291. */
  292. export function updateHistory<T extends DataQuery = any>(
  293. history: Array<HistoryItem<T>>,
  294. datasourceId: string,
  295. queries: T[]
  296. ): Array<HistoryItem<T>> {
  297. const ts = Date.now();
  298. queries.forEach(query => {
  299. history = [{ query, ts }, ...history];
  300. });
  301. if (history.length > MAX_HISTORY_ITEMS) {
  302. history = history.slice(0, MAX_HISTORY_ITEMS);
  303. }
  304. // Combine all queries of a datasource type into one history
  305. const historyKey = `grafana.explore.history.${datasourceId}`;
  306. store.setObject(historyKey, history);
  307. return history;
  308. }
  309. export function clearHistory(datasourceId: string) {
  310. const historyKey = `grafana.explore.history.${datasourceId}`;
  311. store.delete(historyKey);
  312. }
  313. export const getQueryKeys = (queries: DataQuery[], datasourceInstance: DataSourceApi): string[] => {
  314. const queryKeys = queries.reduce((newQueryKeys, query, index) => {
  315. const primaryKey = datasourceInstance && datasourceInstance.name ? datasourceInstance.name : query.key;
  316. return newQueryKeys.concat(`${primaryKey}-${index}`);
  317. }, []);
  318. return queryKeys;
  319. };
  320. export const getTimeRange = (timeZone: TimeZone, rawRange: RawTimeRange): TimeRange => {
  321. return {
  322. from: dateMath.parse(rawRange.from, false, timeZone as any),
  323. to: dateMath.parse(rawRange.to, true, timeZone as any),
  324. raw: rawRange,
  325. };
  326. };
  327. const parseRawTime = (value: any): TimeFragment => {
  328. if (value === null) {
  329. return null;
  330. }
  331. if (value.indexOf('now') !== -1) {
  332. return value;
  333. }
  334. if (value.length === 8) {
  335. return toUtc(value, 'YYYYMMDD');
  336. }
  337. if (value.length === 15) {
  338. return toUtc(value, 'YYYYMMDDTHHmmss');
  339. }
  340. // Backward compatibility
  341. if (value.length === 19) {
  342. return toUtc(value, 'YYYY-MM-DD HH:mm:ss');
  343. }
  344. if (!isNaN(value)) {
  345. const epoch = parseInt(value, 10);
  346. return toUtc(epoch);
  347. }
  348. return null;
  349. };
  350. export const getTimeRangeFromUrl = (range: RawTimeRange, timeZone: TimeZone): TimeRange => {
  351. const raw = {
  352. from: parseRawTime(range.from),
  353. to: parseRawTime(range.to),
  354. };
  355. return {
  356. from: dateMath.parse(raw.from, false, timeZone as any),
  357. to: dateMath.parse(raw.to, true, timeZone as any),
  358. raw,
  359. };
  360. };
  361. export const instanceOfDataQueryError = (value: any): value is DataQueryError => {
  362. return value.message !== undefined && value.status !== undefined && value.statusText !== undefined;
  363. };
  364. export const getValueWithRefId = (value: any): any | null => {
  365. if (!value) {
  366. return null;
  367. }
  368. if (typeof value !== 'object') {
  369. return null;
  370. }
  371. if (value.refId) {
  372. return value;
  373. }
  374. const keys = Object.keys(value);
  375. for (let index = 0; index < keys.length; index++) {
  376. const key = keys[index];
  377. const refId = getValueWithRefId(value[key]);
  378. if (refId) {
  379. return refId;
  380. }
  381. }
  382. return null;
  383. };
  384. export const getFirstQueryErrorWithoutRefId = (errors: DataQueryError[]) => {
  385. if (!errors) {
  386. return null;
  387. }
  388. return errors.filter(error => (error && error.refId ? false : true))[0];
  389. };
  390. export const getRefIds = (value: any): string[] => {
  391. if (!value) {
  392. return [];
  393. }
  394. if (typeof value !== 'object') {
  395. return [];
  396. }
  397. const keys = Object.keys(value);
  398. const refIds = [];
  399. for (let index = 0; index < keys.length; index++) {
  400. const key = keys[index];
  401. if (key === 'refId') {
  402. refIds.push(value[key]);
  403. continue;
  404. }
  405. refIds.push(getRefIds(value[key]));
  406. }
  407. return _.uniq(_.flatten(refIds));
  408. };
  409. const sortInAscendingOrder = (a: LogRowModel, b: LogRowModel) => {
  410. if (a.timestamp < b.timestamp) {
  411. return -1;
  412. }
  413. if (a.timestamp > b.timestamp) {
  414. return 1;
  415. }
  416. return 0;
  417. };
  418. const sortInDescendingOrder = (a: LogRowModel, b: LogRowModel) => {
  419. if (a.timestamp > b.timestamp) {
  420. return -1;
  421. }
  422. if (a.timestamp < b.timestamp) {
  423. return 1;
  424. }
  425. return 0;
  426. };
  427. export enum SortOrder {
  428. Descending = 'Descending',
  429. Ascending = 'Ascending',
  430. }
  431. export const refreshIntervalToSortOrder = (refreshInterval: string) =>
  432. isLive(refreshInterval) ? SortOrder.Ascending : SortOrder.Descending;
  433. export const sortLogsResult = (logsResult: LogsModel, sortOrder: SortOrder): LogsModel => {
  434. const rows = logsResult ? logsResult.rows : [];
  435. sortOrder === SortOrder.Ascending ? rows.sort(sortInAscendingOrder) : rows.sort(sortInDescendingOrder);
  436. const result: LogsModel = logsResult ? { ...logsResult, rows } : { hasUniqueLabels: false, rows };
  437. return result;
  438. };
  439. export const convertToWebSocketUrl = (url: string) => {
  440. const protocol = window.location.protocol === 'https:' ? 'wss://' : 'ws://';
  441. let backend = `${protocol}${window.location.host}${config.appSubUrl}`;
  442. if (backend.endsWith('/')) {
  443. backend = backend.slice(0, backend.length - 1);
  444. }
  445. return `${backend}${url}`;
  446. };
  447. export const stopQueryState = (queryState: PanelQueryState, reason: string) => {
  448. if (queryState && queryState.isStarted()) {
  449. queryState.cancel(reason);
  450. queryState.closeStreams(false);
  451. }
  452. };