metrics_panel_ctrl.ts 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. import _ from 'lodash';
  2. import kbn from 'app/core/utils/kbn';
  3. import { PanelCtrl } from 'app/features/panel/panel_ctrl';
  4. import { getExploreUrl } from 'app/core/utils/explore';
  5. import { applyPanelTimeOverrides, getResolution } from 'app/features/dashboard/utils/panel';
  6. import { ContextSrv } from 'app/core/services/context_srv';
  7. import { toLegacyResponseData, isDataFrame, TimeRange, LoadingState, DataFrame, toDataFrameDTO } from '@grafana/data';
  8. import { LegacyResponseData, DataSourceApi, PanelData, DataQueryResponse } from '@grafana/ui';
  9. import { Unsubscribable } from 'rxjs';
  10. import { PanelModel } from 'app/features/dashboard/state';
  11. import { PanelQueryRunnerFormat } from '../dashboard/state/PanelQueryRunner';
  12. class MetricsPanelCtrl extends PanelCtrl {
  13. scope: any;
  14. datasource: DataSourceApi;
  15. $q: any;
  16. $timeout: any;
  17. contextSrv: ContextSrv;
  18. datasourceSrv: any;
  19. timeSrv: any;
  20. templateSrv: any;
  21. range: TimeRange;
  22. interval: any;
  23. intervalMs: any;
  24. resolution: any;
  25. timeInfo?: string;
  26. skipDataOnInit: boolean;
  27. dataList: LegacyResponseData[];
  28. querySubscription?: Unsubscribable;
  29. dataFormat = PanelQueryRunnerFormat.legacy;
  30. constructor($scope: any, $injector: any) {
  31. super($scope, $injector);
  32. this.$q = $injector.get('$q');
  33. this.contextSrv = $injector.get('contextSrv');
  34. this.datasourceSrv = $injector.get('datasourceSrv');
  35. this.timeSrv = $injector.get('timeSrv');
  36. this.templateSrv = $injector.get('templateSrv');
  37. this.scope = $scope;
  38. this.panel.datasource = this.panel.datasource || null;
  39. this.events.on('refresh', this.onMetricsPanelRefresh.bind(this));
  40. this.events.on('panel-teardown', this.onPanelTearDown.bind(this));
  41. }
  42. private onPanelTearDown() {
  43. if (this.querySubscription) {
  44. this.querySubscription.unsubscribe();
  45. this.querySubscription = null;
  46. }
  47. }
  48. private onMetricsPanelRefresh() {
  49. // ignore fetching data if another panel is in fullscreen
  50. if (this.otherPanelInFullscreenMode()) {
  51. return;
  52. }
  53. // if we have snapshot data use that
  54. if (this.panel.snapshotData) {
  55. this.updateTimeRange();
  56. let data = this.panel.snapshotData;
  57. // backward compatibility
  58. if (!_.isArray(data)) {
  59. data = data.data;
  60. }
  61. // Defer panel rendering till the next digest cycle.
  62. // For some reason snapshot panels don't init at this time, so this helps to avoid rendering issues.
  63. return this.$timeout(() => {
  64. this.events.emit('data-snapshot-load', data);
  65. });
  66. }
  67. // clear loading/error state
  68. delete this.error;
  69. this.loading = true;
  70. // load datasource service
  71. return this.datasourceSrv
  72. .get(this.panel.datasource, this.panel.scopedVars)
  73. .then(this.updateTimeRange.bind(this))
  74. .then(this.issueQueries.bind(this))
  75. .catch((err: any) => {
  76. this.processDataError(err);
  77. });
  78. }
  79. processDataError(err: any) {
  80. // if canceled keep loading set to true
  81. if (err.cancelled) {
  82. console.log('Panel request cancelled', err);
  83. return;
  84. }
  85. this.loading = false;
  86. this.error = err.message || 'Request Error';
  87. this.inspector = { error: err };
  88. if (err.data) {
  89. if (err.data.message) {
  90. this.error = err.data.message;
  91. }
  92. if (err.data.error) {
  93. this.error = err.data.error;
  94. }
  95. }
  96. console.log('Panel data error:', err);
  97. return this.$timeout(() => {
  98. this.events.emit('data-error', err);
  99. });
  100. }
  101. // Updates the response with information from the stream
  102. panelDataObserver = {
  103. next: (data: PanelData) => {
  104. if (data.state === LoadingState.Error) {
  105. this.loading = false;
  106. this.processDataError(data.error);
  107. return;
  108. }
  109. // Ignore data in loading state
  110. if (data.state === LoadingState.Loading) {
  111. this.loading = true;
  112. return;
  113. }
  114. if (data.request) {
  115. const { range, timeInfo } = data.request;
  116. if (range) {
  117. this.range = range;
  118. }
  119. if (timeInfo) {
  120. this.timeInfo = timeInfo;
  121. }
  122. }
  123. if (this.dataFormat === PanelQueryRunnerFormat.legacy) {
  124. // The result should already be processed, but just in case
  125. if (!data.legacy) {
  126. data.legacy = data.series.map(v => {
  127. if (isDataFrame(v)) {
  128. return toLegacyResponseData(v);
  129. }
  130. return v;
  131. });
  132. }
  133. // Make the results look like they came directly from a <6.2 datasource request
  134. // NOTE: any object other than 'data' is no longer supported supported
  135. this.handleQueryResult({ data: data.legacy });
  136. } else {
  137. this.handleDataFrames(data.series);
  138. }
  139. },
  140. };
  141. updateTimeRange(datasource?: DataSourceApi) {
  142. this.datasource = datasource || this.datasource;
  143. this.range = this.timeSrv.timeRange();
  144. this.resolution = getResolution(this.panel);
  145. const newTimeData = applyPanelTimeOverrides(this.panel, this.range);
  146. this.timeInfo = newTimeData.timeInfo;
  147. this.range = newTimeData.timeRange;
  148. this.calculateInterval();
  149. return this.datasource;
  150. }
  151. calculateInterval() {
  152. let intervalOverride = this.panel.interval;
  153. // if no panel interval check datasource
  154. if (intervalOverride) {
  155. intervalOverride = this.templateSrv.replace(intervalOverride, this.panel.scopedVars);
  156. } else if (this.datasource && this.datasource.interval) {
  157. intervalOverride = this.datasource.interval;
  158. }
  159. const res = kbn.calculateInterval(this.range, this.resolution, intervalOverride);
  160. this.interval = res.interval;
  161. this.intervalMs = res.intervalMs;
  162. }
  163. issueQueries(datasource: DataSourceApi) {
  164. this.datasource = datasource;
  165. const panel = this.panel as PanelModel;
  166. const queryRunner = panel.getQueryRunner();
  167. if (!this.querySubscription) {
  168. this.querySubscription = queryRunner.subscribe(this.panelDataObserver, this.dataFormat);
  169. }
  170. return queryRunner.run({
  171. datasource: panel.datasource,
  172. queries: panel.targets,
  173. panelId: panel.id,
  174. dashboardId: this.dashboard.id,
  175. timezone: this.dashboard.timezone,
  176. timeRange: this.range,
  177. widthPixels: this.resolution, // The pixel width
  178. maxDataPoints: panel.maxDataPoints,
  179. minInterval: panel.interval,
  180. scopedVars: panel.scopedVars,
  181. cacheTimeout: panel.cacheTimeout,
  182. });
  183. }
  184. handleDataFrames(data: DataFrame[]) {
  185. this.loading = false;
  186. if (this.dashboard && this.dashboard.snapshot) {
  187. this.panel.snapshotData = data.map(frame => toDataFrameDTO(frame));
  188. }
  189. try {
  190. this.events.emit('data-frames-received', data);
  191. } catch (err) {
  192. this.processDataError(err);
  193. }
  194. }
  195. handleQueryResult(result: DataQueryResponse) {
  196. this.loading = false;
  197. if (this.dashboard.snapshot) {
  198. this.panel.snapshotData = result.data;
  199. }
  200. if (!result || !result.data) {
  201. console.log('Data source query result invalid, missing data field:', result);
  202. result = { data: [] };
  203. }
  204. try {
  205. this.events.emit('data-received', result.data);
  206. } catch (err) {
  207. this.processDataError(err);
  208. }
  209. }
  210. async getAdditionalMenuItems() {
  211. const items = [];
  212. if (this.contextSrv.hasAccessToExplore() && this.datasource) {
  213. items.push({
  214. text: 'Explore',
  215. icon: 'gicon gicon-explore',
  216. shortcut: 'x',
  217. href: await getExploreUrl(this.panel, this.panel.targets, this.datasource, this.datasourceSrv, this.timeSrv),
  218. });
  219. }
  220. return items;
  221. }
  222. async explore() {
  223. const url = await getExploreUrl(this.panel, this.panel.targets, this.datasource, this.datasourceSrv, this.timeSrv);
  224. if (url) {
  225. this.$timeout(() => this.$location.url(url));
  226. }
  227. }
  228. }
  229. export { MetricsPanelCtrl };