metrics_panel_ctrl.ts 7.4 KB

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