explore.ts 14 KB

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