PanelQueryState.ts 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. // Libraries
  2. import { isArray, isEqual, isString } from 'lodash';
  3. // Utils & Services
  4. import { getBackendSrv } from 'app/core/services/backend_srv';
  5. import {
  6. dateMath,
  7. guessFieldTypes,
  8. LoadingState,
  9. toLegacyResponseData,
  10. DataFrame,
  11. toDataFrame,
  12. isDataFrame,
  13. } from '@grafana/data';
  14. // Types
  15. import {
  16. DataSourceApi,
  17. DataQueryRequest,
  18. PanelData,
  19. DataQueryError,
  20. DataStreamObserver,
  21. DataStreamState,
  22. DataQueryResponseData,
  23. } from '@grafana/ui';
  24. export class PanelQueryState {
  25. // The current/last running request
  26. request = {
  27. startTime: 0,
  28. endTime: 1000, // Somethign not zero
  29. } as DataQueryRequest;
  30. // The result back from the datasource query
  31. response = {
  32. state: LoadingState.NotStarted,
  33. series: [],
  34. } as PanelData;
  35. // Active stream results
  36. streams: DataStreamState[] = [];
  37. sendFrames = false;
  38. sendLegacy = false;
  39. // A promise for the running query
  40. private executor?: Promise<PanelData> = null;
  41. private rejector = (reason?: any) => {};
  42. private datasource: DataSourceApi = {} as any;
  43. isFinished(state: LoadingState) {
  44. return state === LoadingState.Done || state === LoadingState.Error;
  45. }
  46. isStarted() {
  47. return this.response.state !== LoadingState.NotStarted;
  48. }
  49. isSameQuery(ds: DataSourceApi, req: DataQueryRequest) {
  50. if (ds !== this.datasource) {
  51. return false;
  52. }
  53. // For now just check that the targets look the same
  54. return isEqual(this.request.targets, req.targets);
  55. }
  56. /**
  57. * Return the currently running query
  58. */
  59. getActiveRunner(): Promise<PanelData> | undefined {
  60. return this.executor;
  61. }
  62. cancel(reason: string) {
  63. const { request } = this;
  64. this.executor = null;
  65. try {
  66. // If no endTime the call to datasource.query did not complete
  67. // call rejector to reject the executor promise
  68. if (!request.endTime) {
  69. request.endTime = Date.now();
  70. this.rejector({ cancelled: true, message: reason });
  71. }
  72. // Cancel any open HTTP request with the same ID
  73. if (request.requestId) {
  74. getBackendSrv().resolveCancelerIfExists(request.requestId);
  75. }
  76. } catch (err) {
  77. console.log('Error canceling request', err);
  78. }
  79. // Close any open streams
  80. this.closeStreams(true);
  81. }
  82. execute(ds: DataSourceApi, req: DataQueryRequest): Promise<PanelData> {
  83. this.request = {
  84. ...req,
  85. startTime: Date.now(),
  86. };
  87. this.datasource = ds;
  88. // Return early if there are no queries to run
  89. if (!req.targets.length) {
  90. console.log('No queries, so return early');
  91. this.request.endTime = Date.now();
  92. this.closeStreams();
  93. return Promise.resolve(
  94. (this.response = {
  95. state: LoadingState.Done,
  96. series: [], // Clear the data
  97. legacy: [],
  98. })
  99. );
  100. }
  101. // Set the loading state immediately
  102. this.response.state = LoadingState.Loading;
  103. this.executor = new Promise<PanelData>((resolve, reject) => {
  104. this.rejector = reject;
  105. return ds
  106. .query(this.request, this.dataStreamObserver)
  107. .then(resp => {
  108. if (!isArray(resp.data)) {
  109. throw new Error(`Expected response data to be array, got ${typeof resp.data}.`);
  110. }
  111. this.request.endTime = Date.now();
  112. this.executor = null;
  113. // Make sure we send something back -- called run() w/o subscribe!
  114. if (!(this.sendFrames || this.sendLegacy)) {
  115. this.sendFrames = true;
  116. }
  117. // Save the result state
  118. this.response = {
  119. state: LoadingState.Done,
  120. request: this.request,
  121. series: this.sendFrames ? getProcessedDataFrames(resp.data) : [],
  122. legacy: this.sendLegacy ? translateToLegacyData(resp.data) : undefined,
  123. };
  124. resolve(this.validateStreamsAndGetPanelData());
  125. })
  126. .catch(err => {
  127. this.executor = null;
  128. resolve(this.setError(err));
  129. });
  130. });
  131. return this.executor;
  132. }
  133. // Send a notice when the stream has updated the current model
  134. onStreamingDataUpdated: () => void;
  135. // This gets all stream events and keeps track of them
  136. // it will then delegate real changes to the PanelQueryRunner
  137. dataStreamObserver: DataStreamObserver = (stream: DataStreamState) => {
  138. // Streams only work with the 'series' format
  139. this.sendFrames = true;
  140. if (stream.state === LoadingState.Error) {
  141. this.setError(stream.error);
  142. this.onStreamingDataUpdated();
  143. return;
  144. }
  145. // Add the stream to our list
  146. let found = false;
  147. const active = this.streams.map(s => {
  148. if (s.key === stream.key) {
  149. found = true;
  150. return stream;
  151. }
  152. return s;
  153. });
  154. if (!found) {
  155. if (shouldDisconnect(this.request, stream)) {
  156. console.log('Got stream update from old stream, unsubscribing');
  157. stream.unsubscribe();
  158. return;
  159. }
  160. active.push(stream);
  161. }
  162. this.streams = active;
  163. this.onStreamingDataUpdated();
  164. };
  165. closeStreams(keepSeries = false) {
  166. if (!this.streams.length) {
  167. return;
  168. }
  169. const series: DataFrame[] = [];
  170. for (const stream of this.streams) {
  171. if (stream.data) {
  172. series.push.apply(series, stream.data);
  173. }
  174. try {
  175. stream.unsubscribe();
  176. } catch {
  177. console.log('Failed to unsubscribe to stream');
  178. }
  179. }
  180. this.streams = [];
  181. // Move the series from streams to the response
  182. if (keepSeries) {
  183. const { response } = this;
  184. this.response = {
  185. ...response,
  186. series: [
  187. ...response.series,
  188. ...series, // Append the streamed series
  189. ],
  190. };
  191. }
  192. }
  193. /**
  194. * This is called before broadcasting data to listeners. Given that
  195. * stream events can happen at any point, we need to make sure to
  196. * only return data from active streams.
  197. */
  198. validateStreamsAndGetPanelData(): PanelData {
  199. const { response, streams, request } = this;
  200. // When not streaming, return the response + request
  201. if (!streams.length) {
  202. return {
  203. ...response,
  204. request: request,
  205. };
  206. }
  207. let done = this.isFinished(response.state);
  208. const series = [...response.series];
  209. const active: DataStreamState[] = [];
  210. for (const stream of this.streams) {
  211. if (shouldDisconnect(request, stream)) {
  212. console.log('getPanelData() - shouldDisconnect true, unsubscribing to steam');
  213. stream.unsubscribe();
  214. continue;
  215. }
  216. active.push(stream);
  217. series.push.apply(series, stream.data);
  218. if (!this.isFinished(stream.state)) {
  219. done = false;
  220. }
  221. }
  222. this.streams = active;
  223. // Update the time range
  224. let timeRange = this.request.range;
  225. if (isString(timeRange.raw.from)) {
  226. timeRange = {
  227. from: dateMath.parse(timeRange.raw.from, false),
  228. to: dateMath.parse(timeRange.raw.to, true),
  229. raw: timeRange.raw,
  230. };
  231. }
  232. return {
  233. state: done ? LoadingState.Done : LoadingState.Streaming,
  234. // This should not be needed but unfortunately Prometheus datasource sends non DataFrame here bypassing the
  235. // typings
  236. series: this.sendFrames ? getProcessedDataFrames(series) : [],
  237. legacy: this.sendLegacy ? translateToLegacyData(series) : undefined,
  238. request: {
  239. ...this.request,
  240. range: timeRange, // update the time range
  241. },
  242. };
  243. }
  244. /**
  245. * Make sure all requested formats exist on the data
  246. */
  247. getDataAfterCheckingFormats(): PanelData {
  248. const { response, sendLegacy, sendFrames } = this;
  249. if (sendLegacy && (!response.legacy || !response.legacy.length)) {
  250. response.legacy = response.series.map(v => toLegacyResponseData(v));
  251. }
  252. if (sendFrames && !response.series.length && response.legacy) {
  253. response.series = response.legacy.map(v => toDataFrame(v));
  254. }
  255. return this.validateStreamsAndGetPanelData();
  256. }
  257. setError(err: any): PanelData {
  258. if (!this.request.endTime) {
  259. this.request.endTime = Date.now();
  260. }
  261. this.closeStreams(true);
  262. this.response = {
  263. ...this.response, // Keep any existing data
  264. state: LoadingState.Error,
  265. error: toDataQueryError(err),
  266. };
  267. return this.validateStreamsAndGetPanelData();
  268. }
  269. }
  270. export function shouldDisconnect(source: DataQueryRequest, state: DataStreamState) {
  271. // It came from the same the same request, so keep it
  272. if (source === state.request || state.request.requestId.startsWith(source.requestId)) {
  273. return false;
  274. }
  275. // We should be able to check that it is the same query regardless of
  276. // if it came from the same request. This will be important for #16676
  277. return true;
  278. }
  279. export function toDataQueryError(err: any): DataQueryError {
  280. const error = (err || {}) as DataQueryError;
  281. if (!error.message) {
  282. if (typeof err === 'string' || err instanceof String) {
  283. return { message: err } as DataQueryError;
  284. }
  285. let message = 'Query error';
  286. if (error.message) {
  287. message = error.message;
  288. } else if (error.data && error.data.message) {
  289. message = error.data.message;
  290. } else if (error.data && error.data.error) {
  291. message = error.data.error;
  292. } else if (error.status) {
  293. message = `Query error: ${error.status} ${error.statusText}`;
  294. }
  295. error.message = message;
  296. }
  297. return error;
  298. }
  299. function translateToLegacyData(data: DataQueryResponseData) {
  300. return data.map((v: any) => {
  301. if (isDataFrame(v)) {
  302. return toLegacyResponseData(v);
  303. }
  304. return v;
  305. });
  306. }
  307. /**
  308. * All panels will be passed tables that have our best guess at colum type set
  309. *
  310. * This is also used by PanelChrome for snapshot support
  311. */
  312. export function getProcessedDataFrames(results?: DataQueryResponseData[]): DataFrame[] {
  313. if (!isArray(results)) {
  314. return [];
  315. }
  316. const series: DataFrame[] = [];
  317. for (const r of results) {
  318. if (r) {
  319. series.push(guessFieldTypes(toDataFrame(r)));
  320. }
  321. }
  322. return series;
  323. }