explore.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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, key and context.
  268. */
  269. const validKeys = ['refId', 'key', 'context'];
  270. export function hasNonEmptyQuery<TQuery extends DataQuery = any>(queries: TQuery[]): boolean {
  271. return (
  272. queries &&
  273. queries.some(query => {
  274. const keys = Object.keys(query)
  275. .filter(key => validKeys.indexOf(key) === -1)
  276. .map(k => query[k])
  277. .filter(v => v);
  278. return keys.length > 0;
  279. })
  280. );
  281. }
  282. export function getIntervals(range: TimeRange, lowLimit: string, resolution: number): IntervalValues {
  283. if (!resolution) {
  284. return { interval: '1s', intervalMs: 1000 };
  285. }
  286. return kbn.calculateInterval(range, resolution, lowLimit);
  287. }
  288. /**
  289. * Update the query history. Side-effect: store history in local storage
  290. */
  291. export function updateHistory<T extends DataQuery = any>(
  292. history: Array<HistoryItem<T>>,
  293. datasourceId: string,
  294. queries: T[]
  295. ): Array<HistoryItem<T>> {
  296. const ts = Date.now();
  297. queries.forEach(query => {
  298. history = [{ query, ts }, ...history];
  299. });
  300. if (history.length > MAX_HISTORY_ITEMS) {
  301. history = history.slice(0, MAX_HISTORY_ITEMS);
  302. }
  303. // Combine all queries of a datasource type into one history
  304. const historyKey = `grafana.explore.history.${datasourceId}`;
  305. store.setObject(historyKey, history);
  306. return history;
  307. }
  308. export function clearHistory(datasourceId: string) {
  309. const historyKey = `grafana.explore.history.${datasourceId}`;
  310. store.delete(historyKey);
  311. }
  312. export const getQueryKeys = (queries: DataQuery[], datasourceInstance: DataSourceApi): string[] => {
  313. const queryKeys = queries.reduce((newQueryKeys, query, index) => {
  314. const primaryKey = datasourceInstance && datasourceInstance.name ? datasourceInstance.name : query.key;
  315. return newQueryKeys.concat(`${primaryKey}-${index}`);
  316. }, []);
  317. return queryKeys;
  318. };
  319. export const getTimeRange = (timeZone: TimeZone, rawRange: RawTimeRange): TimeRange => {
  320. return {
  321. from: dateMath.parse(rawRange.from, false, timeZone as any),
  322. to: dateMath.parse(rawRange.to, true, timeZone as any),
  323. raw: rawRange,
  324. };
  325. };
  326. const parseRawTime = (value): TimeFragment => {
  327. if (value === null) {
  328. return null;
  329. }
  330. if (value.indexOf('now') !== -1) {
  331. return value;
  332. }
  333. if (value.length === 8) {
  334. return toUtc(value, 'YYYYMMDD');
  335. }
  336. if (value.length === 15) {
  337. return toUtc(value, 'YYYYMMDDTHHmmss');
  338. }
  339. // Backward compatibility
  340. if (value.length === 19) {
  341. return toUtc(value, 'YYYY-MM-DD HH:mm:ss');
  342. }
  343. if (!isNaN(value)) {
  344. const epoch = parseInt(value, 10);
  345. return toUtc(epoch);
  346. }
  347. return null;
  348. };
  349. export const getTimeRangeFromUrl = (range: RawTimeRange, timeZone: TimeZone): TimeRange => {
  350. const raw = {
  351. from: parseRawTime(range.from),
  352. to: parseRawTime(range.to),
  353. };
  354. return {
  355. from: dateMath.parse(raw.from, false, timeZone as any),
  356. to: dateMath.parse(raw.to, true, timeZone as any),
  357. raw,
  358. };
  359. };
  360. export const instanceOfDataQueryError = (value: any): value is DataQueryError => {
  361. return value.message !== undefined && value.status !== undefined && value.statusText !== undefined;
  362. };
  363. export const getValueWithRefId = (value: any): any | null => {
  364. if (!value) {
  365. return null;
  366. }
  367. if (typeof value !== 'object') {
  368. return null;
  369. }
  370. if (value.refId) {
  371. return value;
  372. }
  373. const keys = Object.keys(value);
  374. for (let index = 0; index < keys.length; index++) {
  375. const key = keys[index];
  376. const refId = getValueWithRefId(value[key]);
  377. if (refId) {
  378. return refId;
  379. }
  380. }
  381. return null;
  382. };
  383. export const getFirstQueryErrorWithoutRefId = (errors: DataQueryError[]) => {
  384. if (!errors) {
  385. return null;
  386. }
  387. return errors.filter(error => (error.refId ? false : true))[0];
  388. };
  389. export const getRefIds = (value: any): string[] => {
  390. if (!value) {
  391. return [];
  392. }
  393. if (typeof value !== 'object') {
  394. return [];
  395. }
  396. const keys = Object.keys(value);
  397. const refIds = [];
  398. for (let index = 0; index < keys.length; index++) {
  399. const key = keys[index];
  400. if (key === 'refId') {
  401. refIds.push(value[key]);
  402. continue;
  403. }
  404. refIds.push(getRefIds(value[key]));
  405. }
  406. return _.uniq(_.flatten(refIds));
  407. };
  408. const sortInAscendingOrder = (a: LogRowModel, b: LogRowModel) => {
  409. if (a.timeEpochMs < b.timeEpochMs) {
  410. return -1;
  411. }
  412. if (a.timeEpochMs > b.timeEpochMs) {
  413. return 1;
  414. }
  415. return 0;
  416. };
  417. const sortInDescendingOrder = (a: LogRowModel, b: LogRowModel) => {
  418. if (a.timeEpochMs > b.timeEpochMs) {
  419. return -1;
  420. }
  421. if (a.timeEpochMs < b.timeEpochMs) {
  422. return 1;
  423. }
  424. return 0;
  425. };
  426. export const sortLogsResult = (logsResult: LogsModel, refreshInterval: string) => {
  427. const rows = logsResult ? logsResult.rows : [];
  428. const live = isLive(refreshInterval);
  429. live ? rows.sort(sortInAscendingOrder) : rows.sort(sortInDescendingOrder);
  430. const result: LogsModel = logsResult ? { ...logsResult, rows } : { hasUniqueLabels: false, rows };
  431. return result;
  432. };
  433. export const convertToWebSocketUrl = (url: string) => {
  434. const protocol = window.location.protocol === 'https:' ? 'wss://' : 'ws://';
  435. let backend = `${protocol}${window.location.host}${config.appSubUrl}`;
  436. if (backend.endsWith('/')) {
  437. backend = backend.slice(0, backend.length - 1);
  438. }
  439. return `${backend}${url}`;
  440. };
  441. export const getQueryResponse = (
  442. datasourceInstance: DataSourceApi<DataQuery, DataSourceJsonData>,
  443. options: DataQueryRequest<DataQuery>,
  444. observer?: DataStreamObserver
  445. ) => {
  446. return from(datasourceInstance.query(options, observer));
  447. };