explore.ts 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. import { renderUrl } from 'app/core/utils/url';
  2. import { ExploreState, ExploreUrlState, HistoryItem } from 'app/types/explore';
  3. import { DataQuery, RawTimeRange } from 'app/types/series';
  4. import kbn from 'app/core/utils/kbn';
  5. import colors from 'app/core/utils/colors';
  6. import TimeSeries from 'app/core/time_series2';
  7. import { parse as parseDate } from 'app/core/utils/datemath';
  8. import store from 'app/core/store';
  9. export const DEFAULT_RANGE = {
  10. from: 'now-6h',
  11. to: 'now',
  12. };
  13. const MAX_HISTORY_ITEMS = 100;
  14. /**
  15. * Returns an Explore-URL that contains a panel's queries and the dashboard time range.
  16. *
  17. * @param panel Origin panel of the jump to Explore
  18. * @param panelTargets The origin panel's query targets
  19. * @param panelDatasource The origin panel's datasource
  20. * @param datasourceSrv Datasource service to query other datasources in case the panel datasource is mixed
  21. * @param timeSrv Time service to get the current dashboard range from
  22. */
  23. export async function getExploreUrl(
  24. panel: any,
  25. panelTargets: any[],
  26. panelDatasource: any,
  27. datasourceSrv: any,
  28. timeSrv: any
  29. ) {
  30. let exploreDatasource = panelDatasource;
  31. let exploreTargets: DataQuery[] = panelTargets;
  32. let url;
  33. // Mixed datasources need to choose only one datasource
  34. if (panelDatasource.meta.id === 'mixed' && panelTargets) {
  35. // Find first explore datasource among targets
  36. let mixedExploreDatasource;
  37. for (const t of panel.targets) {
  38. const datasource = await datasourceSrv.get(t.datasource);
  39. if (datasource && datasource.meta.explore) {
  40. mixedExploreDatasource = datasource;
  41. break;
  42. }
  43. }
  44. // Add all its targets
  45. if (mixedExploreDatasource) {
  46. exploreDatasource = mixedExploreDatasource;
  47. exploreTargets = panelTargets.filter(t => t.datasource === mixedExploreDatasource.name);
  48. }
  49. }
  50. if (exploreDatasource && exploreDatasource.meta.explore) {
  51. const range = timeSrv.timeRangeForUrl();
  52. const state = {
  53. ...exploreDatasource.getExploreState(exploreTargets),
  54. range,
  55. };
  56. const exploreState = JSON.stringify(state);
  57. url = renderUrl('/explore', { state: exploreState });
  58. }
  59. return url;
  60. }
  61. const clearQueryKeys: ((query: DataQuery) => object) = ({ key, refId, ...rest }) => rest;
  62. export function parseUrlState(initial: string | undefined): ExploreUrlState {
  63. if (initial) {
  64. try {
  65. const parsed = JSON.parse(decodeURI(initial));
  66. if (Array.isArray(parsed)) {
  67. if (parsed.length <= 3) {
  68. throw new Error('Error parsing compact URL state for Explore.');
  69. }
  70. const range = {
  71. from: parsed[0],
  72. to: parsed[1],
  73. };
  74. const datasource = parsed[2];
  75. const queries = parsed.slice(3);
  76. return { datasource, queries, range };
  77. }
  78. return parsed;
  79. } catch (e) {
  80. console.error(e);
  81. }
  82. }
  83. return { datasource: null, queries: [], range: DEFAULT_RANGE };
  84. }
  85. export function serializeStateToUrlParam(state: ExploreState, compact?: boolean): string {
  86. const urlState: ExploreUrlState = {
  87. datasource: state.datasourceName,
  88. queries: state.initialQueries.map(clearQueryKeys),
  89. range: state.range,
  90. };
  91. if (compact) {
  92. return JSON.stringify([urlState.range.from, urlState.range.to, urlState.datasource, ...urlState.queries]);
  93. }
  94. return JSON.stringify(urlState);
  95. }
  96. export function generateKey(index = 0): string {
  97. return `Q-${Date.now()}-${Math.random()}-${index}`;
  98. }
  99. export function generateRefId(index = 0): string {
  100. return `${index + 1}`;
  101. }
  102. export function generateQueryKeys(index = 0): { refId: string; key: string } {
  103. return { refId: generateRefId(index), key: generateKey(index) };
  104. }
  105. /**
  106. * Ensure at least one target exists and that targets have the necessary keys
  107. */
  108. export function ensureQueries(queries?: DataQuery[]): DataQuery[] {
  109. if (queries && typeof queries === 'object' && queries.length > 0) {
  110. return queries.map((query, i) => ({ ...query, ...generateQueryKeys(i) }));
  111. }
  112. return [{ ...generateQueryKeys() }];
  113. }
  114. /**
  115. * A target is non-empty when it has keys other than refId and key.
  116. */
  117. export function hasNonEmptyQuery(queries: DataQuery[]): boolean {
  118. return queries.some(query => Object.keys(query).length > 2);
  119. }
  120. export function getIntervals(
  121. range: RawTimeRange,
  122. datasource,
  123. resolution: number
  124. ): { interval: string; intervalMs: number } {
  125. if (!datasource || !resolution) {
  126. return { interval: '1s', intervalMs: 1000 };
  127. }
  128. const absoluteRange: RawTimeRange = {
  129. from: parseDate(range.from, false),
  130. to: parseDate(range.to, true),
  131. };
  132. return kbn.calculateInterval(absoluteRange, resolution, datasource.interval);
  133. }
  134. export function makeTimeSeriesList(dataList) {
  135. return dataList.map((seriesData, index) => {
  136. const datapoints = seriesData.datapoints || [];
  137. const alias = seriesData.target;
  138. const colorIndex = index % colors.length;
  139. const color = colors[colorIndex];
  140. const series = new TimeSeries({
  141. datapoints,
  142. alias,
  143. color,
  144. unit: seriesData.unit,
  145. });
  146. return series;
  147. });
  148. }
  149. /**
  150. * Update the query history. Side-effect: store history in local storage
  151. */
  152. export function updateHistory(history: HistoryItem[], datasourceId: string, queries: DataQuery[]): HistoryItem[] {
  153. const ts = Date.now();
  154. queries.forEach(query => {
  155. history = [{ query, ts }, ...history];
  156. });
  157. if (history.length > MAX_HISTORY_ITEMS) {
  158. history = history.slice(0, MAX_HISTORY_ITEMS);
  159. }
  160. // Combine all queries of a datasource type into one history
  161. const historyKey = `grafana.explore.history.${datasourceId}`;
  162. store.setObject(historyKey, history);
  163. return history;
  164. }
  165. export function clearHistory(datasourceId: string) {
  166. const historyKey = `grafana.explore.history.${datasourceId}`;
  167. store.delete(historyKey);
  168. }