metrics_panel_ctrl.ts 8.2 KB

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