explore.ts 14 KB

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