metrics_panel_ctrl.ts 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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. class MetricsPanelCtrl extends PanelCtrl {
  8. scope: any;
  9. datasource: any;
  10. $q: any;
  11. $timeout: any;
  12. contextSrv: ContextSrv;
  13. datasourceSrv: any;
  14. timeSrv: any;
  15. templateSrv: any;
  16. timing: 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.setTimeQueryStart();
  72. this.datasourceSrv
  73. .get(this.panel.datasource)
  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. setTimeQueryStart() {
  99. this.timing.queryStart = new Date().getTime();
  100. }
  101. setTimeQueryEnd() {
  102. this.timing.queryEnd = new Date().getTime();
  103. }
  104. updateTimeRange(datasource?) {
  105. this.datasource = datasource || this.datasource;
  106. this.range = this.timeSrv.timeRange();
  107. this.resolution = getResolution(this.panel);
  108. const newTimeData = applyPanelTimeOverrides(this.panel, this.range);
  109. this.timeInfo = newTimeData.timeInfo;
  110. this.range = newTimeData.timeRange;
  111. this.calculateInterval();
  112. return this.datasource;
  113. }
  114. calculateInterval() {
  115. let intervalOverride = this.panel.interval;
  116. // if no panel interval check datasource
  117. if (intervalOverride) {
  118. intervalOverride = this.templateSrv.replace(intervalOverride, this.panel.scopedVars);
  119. } else if (this.datasource && this.datasource.interval) {
  120. intervalOverride = this.datasource.interval;
  121. }
  122. const res = kbn.calculateInterval(this.range, this.resolution, intervalOverride);
  123. this.interval = res.interval;
  124. this.intervalMs = res.intervalMs;
  125. }
  126. issueQueries(datasource) {
  127. this.datasource = datasource;
  128. if (!this.panel.targets || this.panel.targets.length === 0) {
  129. return this.$q.when([]);
  130. }
  131. // make shallow copy of scoped vars,
  132. // and add built in variables interval and interval_ms
  133. const scopedVars = Object.assign({}, this.panel.scopedVars, {
  134. __interval: { text: this.interval, value: this.interval },
  135. __interval_ms: { text: this.intervalMs, value: this.intervalMs },
  136. });
  137. const metricsQuery = {
  138. timezone: this.dashboard.getTimezone(),
  139. panelId: this.panel.id,
  140. dashboardId: this.dashboard.id,
  141. range: this.range,
  142. rangeRaw: this.range.raw,
  143. interval: this.interval,
  144. intervalMs: this.intervalMs,
  145. targets: this.panel.targets,
  146. maxDataPoints: this.resolution,
  147. scopedVars: scopedVars,
  148. cacheTimeout: this.panel.cacheTimeout,
  149. };
  150. return datasource.query(metricsQuery);
  151. }
  152. handleQueryResult(result) {
  153. this.setTimeQueryEnd();
  154. this.loading = false;
  155. // check for if data source returns subject
  156. if (result && result.subscribe) {
  157. this.handleDataStream(result);
  158. return;
  159. }
  160. if (this.dashboard.snapshot) {
  161. this.panel.snapshotData = result.data;
  162. }
  163. if (!result || !result.data) {
  164. console.log('Data source query result invalid, missing data field:', result);
  165. result = { data: [] };
  166. }
  167. this.events.emit('data-received', result.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: 'fa fa-fw fa-rocket',
  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 };