explore.ts 14 KB

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