metrics_panel_ctrl.ts 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. import _ from 'lodash';
  2. import config from 'app/core/config';
  3. // import kbn from 'app/core/utils/kbn';
  4. import { PanelCtrl } from 'app/features/panel/panel_ctrl';
  5. import { getExploreUrl } from 'app/core/utils/explore';
  6. import { metricsTabDirective } from './metrics_tab';
  7. import {
  8. applyPanelTimeOverrides as applyPanelTimeOverridesUtil,
  9. calculateInterval as calculateIntervalUtil,
  10. getResolution,
  11. } from 'app/features/dashboard/utils/panel';
  12. class MetricsPanelCtrl extends PanelCtrl {
  13. scope: any;
  14. datasource: any;
  15. $q: any;
  16. $timeout: any;
  17. contextSrv: any;
  18. datasourceSrv: any;
  19. timeSrv: any;
  20. templateSrv: any;
  21. timing: any;
  22. range: any;
  23. interval: any;
  24. intervalMs: any;
  25. resolution: any;
  26. timeInfo: any;
  27. skipDataOnInit: boolean;
  28. dataStream: any;
  29. dataSubscription: any;
  30. dataList: any;
  31. nextRefId: string;
  32. constructor($scope, $injector) {
  33. super($scope, $injector);
  34. // make metrics tab the default
  35. this.editorTabIndex = 1;
  36. this.$q = $injector.get('$q');
  37. this.contextSrv = $injector.get('contextSrv');
  38. this.datasourceSrv = $injector.get('datasourceSrv');
  39. this.timeSrv = $injector.get('timeSrv');
  40. this.templateSrv = $injector.get('templateSrv');
  41. this.scope = $scope;
  42. this.panel.datasource = this.panel.datasource || null;
  43. this.events.on('refresh', this.onMetricsPanelRefresh.bind(this));
  44. this.events.on('init-edit-mode', this.onInitMetricsPanelEditMode.bind(this));
  45. this.events.on('panel-teardown', this.onPanelTearDown.bind(this));
  46. }
  47. private onPanelTearDown() {
  48. if (this.dataSubscription) {
  49. this.dataSubscription.unsubscribe();
  50. this.dataSubscription = null;
  51. }
  52. }
  53. private onInitMetricsPanelEditMode() {
  54. this.addEditorTab('Metrics', metricsTabDirective, 1, 'fa fa-database');
  55. this.addEditorTab('Time range', 'public/app/features/panel/partials/panelTime.html');
  56. }
  57. private onMetricsPanelRefresh() {
  58. // ignore fetching data if another panel is in fullscreen
  59. if (this.otherPanelInFullscreenMode()) {
  60. return;
  61. }
  62. // if we have snapshot data use that
  63. if (this.panel.snapshotData) {
  64. this.updateTimeRange();
  65. let data = this.panel.snapshotData;
  66. // backward compatibility
  67. if (!_.isArray(data)) {
  68. data = data.data;
  69. }
  70. // Defer panel rendering till the next digest cycle.
  71. // For some reason snapshot panels don't init at this time, so this helps to avoid rendering issues.
  72. return this.$timeout(() => {
  73. this.events.emit('data-snapshot-load', data);
  74. });
  75. }
  76. // // ignore if we have data stream
  77. if (this.dataStream) {
  78. return;
  79. }
  80. // clear loading/error state
  81. delete this.error;
  82. this.loading = true;
  83. // load datasource service
  84. this.setTimeQueryStart();
  85. this.datasourceSrv
  86. .get(this.panel.datasource)
  87. .then(this.updateTimeRange.bind(this))
  88. .then(this.issueQueries.bind(this))
  89. .then(this.handleQueryResult.bind(this))
  90. .catch(err => {
  91. // if cancelled 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. setTimeQueryStart() {
  112. this.timing.queryStart = new Date().getTime();
  113. }
  114. setTimeQueryEnd() {
  115. this.timing.queryEnd = new Date().getTime();
  116. }
  117. updateTimeRange(datasource?) {
  118. this.datasource = datasource || this.datasource;
  119. this.range = this.timeSrv.timeRange();
  120. this.applyPanelTimeOverrides();
  121. this.resolution = getResolution(this.panel);
  122. this.calculateInterval();
  123. return this.datasource;
  124. }
  125. calculateInterval() {
  126. const interval = calculateIntervalUtil(this.panel, this.datasource, this.range, this.resolution);
  127. this.interval = interval.interval;
  128. this.intervalMs = this.intervalMs;
  129. }
  130. applyPanelTimeOverrides() {
  131. const newTimeData = applyPanelTimeOverridesUtil(this.panel, this.range);
  132. this.timeInfo = newTimeData.timeInfo;
  133. this.range = newTimeData.timeRange;
  134. }
  135. issueQueries(datasource) {
  136. this.datasource = datasource;
  137. if (!this.panel.targets || this.panel.targets.length === 0) {
  138. return this.$q.when([]);
  139. }
  140. // make shallow copy of scoped vars,
  141. // and add built in variables interval and interval_ms
  142. const scopedVars = Object.assign({}, this.panel.scopedVars, {
  143. __interval: { text: this.interval, value: this.interval },
  144. __interval_ms: { text: this.intervalMs, value: this.intervalMs },
  145. });
  146. const metricsQuery = {
  147. timezone: this.dashboard.getTimezone(),
  148. panelId: this.panel.id,
  149. dashboardId: this.dashboard.id,
  150. range: this.range,
  151. rangeRaw: this.range.raw,
  152. interval: this.interval,
  153. intervalMs: this.intervalMs,
  154. targets: this.panel.targets,
  155. maxDataPoints: this.resolution,
  156. scopedVars: scopedVars,
  157. cacheTimeout: this.panel.cacheTimeout,
  158. };
  159. return datasource.query(metricsQuery);
  160. }
  161. handleQueryResult(result) {
  162. this.setTimeQueryEnd();
  163. this.loading = false;
  164. // check for if data source returns subject
  165. if (result && result.subscribe) {
  166. this.handleDataStream(result);
  167. return;
  168. }
  169. if (this.dashboard.snapshot) {
  170. this.panel.snapshotData = result.data;
  171. }
  172. if (!result || !result.data) {
  173. console.log('Data source query result invalid, missing data field:', result);
  174. result = { data: [] };
  175. }
  176. this.events.emit('data-received', result.data);
  177. }
  178. handleDataStream(stream) {
  179. // if we already have a connection
  180. if (this.dataStream) {
  181. console.log('two stream observables!');
  182. return;
  183. }
  184. this.dataStream = stream;
  185. this.dataSubscription = stream.subscribe({
  186. next: data => {
  187. console.log('dataSubject next!');
  188. if (data.range) {
  189. this.range = data.range;
  190. }
  191. this.events.emit('data-received', data.data);
  192. },
  193. error: error => {
  194. this.events.emit('data-error', error);
  195. console.log('panel: observer got error');
  196. },
  197. complete: () => {
  198. console.log('panel: observer got complete');
  199. this.dataStream = null;
  200. },
  201. });
  202. }
  203. getAdditionalMenuItems() {
  204. const items = [];
  205. if (
  206. config.exploreEnabled &&
  207. this.contextSrv.isEditor &&
  208. this.datasource &&
  209. (this.datasource.meta.explore || this.datasource.meta.id === 'mixed')
  210. ) {
  211. items.push({
  212. text: 'Explore',
  213. click: 'ctrl.explore();',
  214. icon: 'fa fa-fw fa-rocket',
  215. shortcut: 'x',
  216. });
  217. }
  218. return items;
  219. }
  220. async explore() {
  221. const url = await getExploreUrl(this.panel, this.panel.targets, this.datasource, this.datasourceSrv, this.timeSrv);
  222. if (url) {
  223. this.$timeout(() => this.$location.url(url));
  224. }
  225. }
  226. addQuery(target) {
  227. target.refId = this.dashboard.getNextQueryLetter(this.panel);
  228. this.panel.targets.push(target);
  229. this.nextRefId = this.dashboard.getNextQueryLetter(this.panel);
  230. }
  231. removeQuery(target) {
  232. const index = _.indexOf(this.panel.targets, target);
  233. this.panel.targets.splice(index, 1);
  234. this.nextRefId = this.dashboard.getNextQueryLetter(this.panel);
  235. this.refresh();
  236. }
  237. moveQuery(target, direction) {
  238. const index = _.indexOf(this.panel.targets, target);
  239. _.move(this.panel.targets, index, index + direction);
  240. }
  241. }
  242. export { MetricsPanelCtrl };