metrics_panel_ctrl.ts 7.3 KB

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