explore.ts 14 KB

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