metrics_panel_ctrl.ts 7.2 KB

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