metrics_panel_ctrl.ts 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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. isSeriesData,
  10. LegacyResponseData,
  11. TimeRange,
  12. DataSourceApi,
  13. PanelData,
  14. LoadingState,
  15. DataQueryResponse,
  16. SeriesData,
  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 (
  81. this.datasourceSrv
  82. .get(this.panel.datasource, this.panel.scopedVars)
  83. .then(this.updateTimeRange.bind(this))
  84. .then(this.issueQueries.bind(this))
  85. // NOTE handleQueryResult is called by panelDataObserver
  86. .catch((err: any) => {
  87. this.processDataError(err);
  88. })
  89. );
  90. }
  91. processDataError(err: any) {
  92. // if canceled keep loading set to true
  93. if (err.cancelled) {
  94. console.log('Panel request cancelled', err);
  95. return;
  96. }
  97. this.loading = false;
  98. this.error = err.message || 'Request Error';
  99. this.inspector = { error: err };
  100. if (err.data) {
  101. if (err.data.message) {
  102. this.error = err.data.message;
  103. }
  104. if (err.data.error) {
  105. this.error = err.data.error;
  106. }
  107. }
  108. this.events.emit('data-error', err);
  109. console.log('Panel data error:', err);
  110. }
  111. // Updates the response with information from the stream
  112. panelDataObserver = {
  113. next: (data: PanelData) => {
  114. if (data.state === LoadingState.Error) {
  115. this.loading = false;
  116. this.processDataError(data.error);
  117. return;
  118. }
  119. this.loading = false;
  120. if (data.request) {
  121. const { range, timeInfo } = data.request;
  122. if (range) {
  123. this.range = range;
  124. }
  125. if (timeInfo) {
  126. this.timeInfo = timeInfo;
  127. }
  128. }
  129. if (this.dataFormat === PanelQueryRunnerFormat.legacy) {
  130. // The result should already be processed, but just in case
  131. if (!data.legacy) {
  132. data.legacy = data.series.map(v => {
  133. if (isSeriesData(v)) {
  134. return toLegacyResponseData(v);
  135. }
  136. return v;
  137. });
  138. }
  139. // Make the results look like they came directly from a <6.2 datasource request
  140. // NOTE: any object other than 'data' is no longer supported supported
  141. this.handleQueryResult({
  142. data: data.legacy,
  143. });
  144. } else {
  145. this.handleSeriesData(data.series);
  146. }
  147. },
  148. };
  149. updateTimeRange(datasource?: DataSourceApi) {
  150. this.datasource = datasource || this.datasource;
  151. this.range = this.timeSrv.timeRange();
  152. this.resolution = getResolution(this.panel);
  153. const newTimeData = applyPanelTimeOverrides(this.panel, this.range);
  154. this.timeInfo = newTimeData.timeInfo;
  155. this.range = newTimeData.timeRange;
  156. this.calculateInterval();
  157. return this.datasource;
  158. }
  159. calculateInterval() {
  160. let intervalOverride = this.panel.interval;
  161. // if no panel interval check datasource
  162. if (intervalOverride) {
  163. intervalOverride = this.templateSrv.replace(intervalOverride, this.panel.scopedVars);
  164. } else if (this.datasource && this.datasource.interval) {
  165. intervalOverride = this.datasource.interval;
  166. }
  167. const res = kbn.calculateInterval(this.range, this.resolution, intervalOverride);
  168. this.interval = res.interval;
  169. this.intervalMs = res.intervalMs;
  170. }
  171. issueQueries(datasource: DataSourceApi) {
  172. this.datasource = datasource;
  173. const panel = this.panel as PanelModel;
  174. const queryRunner = panel.getQueryRunner();
  175. if (!this.querySubscription) {
  176. this.querySubscription = queryRunner.subscribe(this.panelDataObserver, this.dataFormat);
  177. }
  178. return queryRunner.run({
  179. datasource: panel.datasource,
  180. queries: panel.targets,
  181. panelId: panel.id,
  182. dashboardId: this.dashboard.id,
  183. timezone: this.dashboard.timezone,
  184. timeRange: this.range,
  185. widthPixels: this.resolution, // The pixel width
  186. maxDataPoints: panel.maxDataPoints,
  187. minInterval: panel.interval,
  188. scopedVars: panel.scopedVars,
  189. cacheTimeout: panel.cacheTimeout,
  190. });
  191. }
  192. handleSeriesData(data: SeriesData[]) {
  193. this.loading = false;
  194. if (this.dashboard && this.dashboard.snapshot) {
  195. this.panel.snapshotData = data;
  196. }
  197. // Subclasses that asked for SeriesData 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 };