metrics_panel_ctrl.ts 6.8 KB

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