metrics_panel_ctrl.ts 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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, isSeriesData, LegacyResponseData, TimeRange } from '@grafana/ui';
  8. import { Unsubscribable } from 'rxjs';
  9. class MetricsPanelCtrl extends PanelCtrl {
  10. scope: any;
  11. datasource: any;
  12. $q: any;
  13. $timeout: any;
  14. contextSrv: ContextSrv;
  15. datasourceSrv: any;
  16. timeSrv: any;
  17. templateSrv: any;
  18. range: TimeRange;
  19. interval: any;
  20. intervalMs: any;
  21. resolution: any;
  22. timeInfo?: string;
  23. skipDataOnInit: boolean;
  24. dataStream: any;
  25. dataSubscription?: Unsubscribable;
  26. dataList: LegacyResponseData[];
  27. constructor($scope, $injector) {
  28. super($scope, $injector);
  29. this.$q = $injector.get('$q');
  30. this.contextSrv = $injector.get('contextSrv');
  31. this.datasourceSrv = $injector.get('datasourceSrv');
  32. this.timeSrv = $injector.get('timeSrv');
  33. this.templateSrv = $injector.get('templateSrv');
  34. this.scope = $scope;
  35. this.panel.datasource = this.panel.datasource || null;
  36. this.events.on('refresh', this.onMetricsPanelRefresh.bind(this));
  37. this.events.on('panel-teardown', this.onPanelTearDown.bind(this));
  38. }
  39. private onPanelTearDown() {
  40. if (this.dataSubscription) {
  41. this.dataSubscription.unsubscribe();
  42. this.dataSubscription = null;
  43. }
  44. }
  45. private onMetricsPanelRefresh() {
  46. // ignore fetching data if another panel is in fullscreen
  47. if (this.otherPanelInFullscreenMode()) {
  48. return;
  49. }
  50. // if we have snapshot data use that
  51. if (this.panel.snapshotData) {
  52. this.updateTimeRange();
  53. let data = this.panel.snapshotData;
  54. // backward compatibility
  55. if (!_.isArray(data)) {
  56. data = data.data;
  57. }
  58. // Defer panel rendering till the next digest cycle.
  59. // For some reason snapshot panels don't init at this time, so this helps to avoid rendering issues.
  60. return this.$timeout(() => {
  61. this.events.emit('data-snapshot-load', data);
  62. });
  63. }
  64. // // ignore if we have data stream
  65. if (this.dataStream) {
  66. return;
  67. }
  68. // clear loading/error state
  69. delete this.error;
  70. this.loading = true;
  71. // load datasource service
  72. this.datasourceSrv
  73. .get(this.panel.datasource, this.panel.scopedVars)
  74. .then(this.updateTimeRange.bind(this))
  75. .then(this.issueQueries.bind(this))
  76. .then(this.handleQueryResult.bind(this))
  77. .catch(err => {
  78. // if canceled keep loading set to true
  79. if (err.cancelled) {
  80. console.log('Panel request cancelled', err);
  81. return;
  82. }
  83. this.loading = false;
  84. this.error = err.message || 'Request Error';
  85. this.inspector = { error: err };
  86. if (err.data) {
  87. if (err.data.message) {
  88. this.error = err.data.message;
  89. }
  90. if (err.data.error) {
  91. this.error = err.data.error;
  92. }
  93. }
  94. this.events.emit('data-error', err);
  95. console.log('Panel data error:', err);
  96. });
  97. }
  98. updateTimeRange(datasource?) {
  99. this.datasource = datasource || this.datasource;
  100. this.range = this.timeSrv.timeRange();
  101. this.resolution = getResolution(this.panel);
  102. const newTimeData = applyPanelTimeOverrides(this.panel, this.range);
  103. this.timeInfo = newTimeData.timeInfo;
  104. this.range = newTimeData.timeRange;
  105. this.calculateInterval();
  106. return this.datasource;
  107. }
  108. calculateInterval() {
  109. let intervalOverride = this.panel.interval;
  110. // if no panel interval check datasource
  111. if (intervalOverride) {
  112. intervalOverride = this.templateSrv.replace(intervalOverride, this.panel.scopedVars);
  113. } else if (this.datasource && this.datasource.interval) {
  114. intervalOverride = this.datasource.interval;
  115. }
  116. const res = kbn.calculateInterval(this.range, this.resolution, intervalOverride);
  117. this.interval = res.interval;
  118. this.intervalMs = res.intervalMs;
  119. }
  120. issueQueries(datasource) {
  121. this.datasource = datasource;
  122. if (!this.panel.targets || this.panel.targets.length === 0) {
  123. return this.$q.when([]);
  124. }
  125. // make shallow copy of scoped vars,
  126. // and add built in variables interval and interval_ms
  127. const scopedVars = Object.assign({}, this.panel.scopedVars, {
  128. __interval: { text: this.interval, value: this.interval },
  129. __interval_ms: { text: this.intervalMs, value: this.intervalMs },
  130. });
  131. const metricsQuery = {
  132. timezone: this.dashboard.getTimezone(),
  133. panelId: this.panel.id,
  134. dashboardId: this.dashboard.id,
  135. range: this.range,
  136. rangeRaw: this.range.raw,
  137. interval: this.interval,
  138. intervalMs: this.intervalMs,
  139. targets: this.panel.targets,
  140. maxDataPoints: this.resolution,
  141. scopedVars: scopedVars,
  142. cacheTimeout: this.panel.cacheTimeout,
  143. };
  144. return datasource.query(metricsQuery);
  145. }
  146. handleQueryResult(result) {
  147. this.loading = false;
  148. // check for if data source returns subject
  149. if (result && result.subscribe) {
  150. this.handleDataStream(result);
  151. return;
  152. }
  153. if (this.dashboard.snapshot) {
  154. this.panel.snapshotData = result.data;
  155. }
  156. if (!result || !result.data) {
  157. console.log('Data source query result invalid, missing data field:', result);
  158. result = { data: [] };
  159. }
  160. // Make sure the data is TableData | TimeSeries
  161. const data = result.data.map(v => {
  162. if (isSeriesData(v)) {
  163. return toLegacyResponseData(v);
  164. }
  165. return v;
  166. });
  167. this.events.emit('data-received', data);
  168. }
  169. handleDataStream(stream) {
  170. // if we already have a connection
  171. if (this.dataStream) {
  172. console.log('two stream observables!');
  173. return;
  174. }
  175. this.dataStream = stream;
  176. this.dataSubscription = stream.subscribe({
  177. next: data => {
  178. console.log('dataSubject next!');
  179. if (data.range) {
  180. this.range = data.range;
  181. }
  182. this.events.emit('data-received', data.data);
  183. },
  184. error: error => {
  185. this.events.emit('data-error', error);
  186. console.log('panel: observer got error');
  187. },
  188. complete: () => {
  189. console.log('panel: observer got complete');
  190. this.dataStream = null;
  191. },
  192. });
  193. }
  194. getAdditionalMenuItems() {
  195. const items = [];
  196. if (this.contextSrv.hasAccessToExplore() && this.datasource) {
  197. items.push({
  198. text: 'Explore',
  199. click: 'ctrl.explore();',
  200. icon: 'gicon gicon-explore',
  201. shortcut: 'x',
  202. });
  203. }
  204. return items;
  205. }
  206. async explore() {
  207. const url = await getExploreUrl(this.panel, this.panel.targets, this.datasource, this.datasourceSrv, this.timeSrv);
  208. if (url) {
  209. this.$timeout(() => this.$location.url(url));
  210. }
  211. }
  212. }
  213. export { MetricsPanelCtrl };