metrics_panel_ctrl.ts 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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 * as rangeUtil from 'app/core/utils/rangeutil';
  7. import * as dateMath from 'app/core/utils/datemath';
  8. import { getExploreUrl } from 'app/core/utils/explore';
  9. import { metricsTabDirective } from './metrics_tab';
  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 canceled 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. this.timeInfo = '';
  141. // check panel time overrrides
  142. if (this.panel.timeFrom) {
  143. const timeFromInterpolated = this.templateSrv.replace(this.panel.timeFrom, this.panel.scopedVars);
  144. const timeFromInfo = rangeUtil.describeTextRange(timeFromInterpolated);
  145. if (timeFromInfo.invalid) {
  146. this.timeInfo = 'invalid time override';
  147. return;
  148. }
  149. if (_.isString(this.range.raw.from)) {
  150. const timeFromDate = dateMath.parse(timeFromInfo.from);
  151. this.timeInfo = timeFromInfo.display;
  152. this.range.from = timeFromDate;
  153. this.range.to = dateMath.parse(timeFromInfo.to);
  154. this.range.raw.from = timeFromInfo.from;
  155. this.range.raw.to = timeFromInfo.to;
  156. }
  157. }
  158. if (this.panel.timeShift) {
  159. const timeShiftInterpolated = this.templateSrv.replace(this.panel.timeShift, this.panel.scopedVars);
  160. const timeShiftInfo = rangeUtil.describeTextRange(timeShiftInterpolated);
  161. if (timeShiftInfo.invalid) {
  162. this.timeInfo = 'invalid timeshift';
  163. return;
  164. }
  165. const timeShift = '-' + timeShiftInterpolated;
  166. this.timeInfo += ' timeshift ' + timeShift;
  167. this.range.from = dateMath.parseDateMath(timeShift, this.range.from, false);
  168. this.range.to = dateMath.parseDateMath(timeShift, this.range.to, true);
  169. this.range.raw = { from: this.range.from, to: this.range.to };
  170. }
  171. if (this.panel.hideTimeOverride) {
  172. this.timeInfo = '';
  173. }
  174. }
  175. issueQueries(datasource) {
  176. this.datasource = datasource;
  177. if (!this.panel.targets || this.panel.targets.length === 0) {
  178. return this.$q.when([]);
  179. }
  180. // make shallow copy of scoped vars,
  181. // and add built in variables interval and interval_ms
  182. const scopedVars = Object.assign({}, this.panel.scopedVars, {
  183. __interval: { text: this.interval, value: this.interval },
  184. __interval_ms: { text: this.intervalMs, value: this.intervalMs },
  185. });
  186. const metricsQuery = {
  187. timezone: this.dashboard.getTimezone(),
  188. panelId: this.panel.id,
  189. dashboardId: this.dashboard.id,
  190. range: this.range,
  191. rangeRaw: this.range.raw,
  192. interval: this.interval,
  193. intervalMs: this.intervalMs,
  194. targets: this.panel.targets,
  195. maxDataPoints: this.resolution,
  196. scopedVars: scopedVars,
  197. cacheTimeout: this.panel.cacheTimeout,
  198. };
  199. return datasource.query(metricsQuery);
  200. }
  201. handleQueryResult(result) {
  202. this.setTimeQueryEnd();
  203. this.loading = false;
  204. // check for if data source returns subject
  205. if (result && result.subscribe) {
  206. this.handleDataStream(result);
  207. return;
  208. }
  209. if (this.dashboard.snapshot) {
  210. this.panel.snapshotData = result.data;
  211. }
  212. if (!result || !result.data) {
  213. console.log('Data source query result invalid, missing data field:', result);
  214. result = { data: [] };
  215. }
  216. this.events.emit('data-received', result.data);
  217. }
  218. handleDataStream(stream) {
  219. // if we already have a connection
  220. if (this.dataStream) {
  221. console.log('two stream observables!');
  222. return;
  223. }
  224. this.dataStream = stream;
  225. this.dataSubscription = stream.subscribe({
  226. next: data => {
  227. console.log('dataSubject next!');
  228. if (data.range) {
  229. this.range = data.range;
  230. }
  231. this.events.emit('data-received', data.data);
  232. },
  233. error: error => {
  234. this.events.emit('data-error', error);
  235. console.log('panel: observer got error');
  236. },
  237. complete: () => {
  238. console.log('panel: observer got complete');
  239. this.dataStream = null;
  240. },
  241. });
  242. }
  243. getAdditionalMenuItems() {
  244. const items = [];
  245. if (
  246. config.exploreEnabled &&
  247. this.contextSrv.isEditor &&
  248. this.datasource &&
  249. (this.datasource.meta.explore || this.datasource.meta.id === 'mixed')
  250. ) {
  251. items.push({
  252. text: 'Explore',
  253. click: 'ctrl.explore();',
  254. icon: 'fa fa-fw fa-rocket',
  255. shortcut: 'x',
  256. });
  257. }
  258. return items;
  259. }
  260. async explore() {
  261. const url = await getExploreUrl(this.panel, this.panel.targets, this.datasource, this.datasourceSrv, this.timeSrv);
  262. if (url) {
  263. this.$timeout(() => this.$location.url(url));
  264. }
  265. }
  266. addQuery(target) {
  267. target.refId = this.dashboard.getNextQueryLetter(this.panel);
  268. this.panel.targets.push(target);
  269. this.nextRefId = this.dashboard.getNextQueryLetter(this.panel);
  270. }
  271. removeQuery(target) {
  272. const index = _.indexOf(this.panel.targets, target);
  273. this.panel.targets.splice(index, 1);
  274. this.nextRefId = this.dashboard.getNextQueryLetter(this.panel);
  275. this.refresh();
  276. }
  277. moveQuery(target, direction) {
  278. const index = _.indexOf(this.panel.targets, target);
  279. _.move(this.panel.targets, index, index + direction);
  280. }
  281. }
  282. export { MetricsPanelCtrl };