explore.ts 14 KB

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