explore.ts 7.0 KB

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