metrics_panel_ctrl.ts 6.9 KB

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