metrics_panel_ctrl.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. import config from 'app/core/config';
  2. import $ from 'jquery';
  3. import _ from 'lodash';
  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 {metricsTabDirective} from './metrics_tab';
  9. class MetricsPanelCtrl extends PanelCtrl {
  10. scope: any;
  11. loading: boolean;
  12. datasource: any;
  13. datasourceName: any;
  14. $q: any;
  15. $timeout: 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.datasourceSrv = $injector.get('datasourceSrv');
  36. this.timeSrv = $injector.get('timeSrv');
  37. this.templateSrv = $injector.get('templateSrv');
  38. this.scope = $scope;
  39. if (!this.panel.targets) {
  40. this.panel.targets = [{}];
  41. }
  42. this.events.on('refresh', this.onMetricsPanelRefresh.bind(this));
  43. this.events.on('init-edit-mode', this.onInitMetricsPanelEditMode.bind(this));
  44. this.events.on('panel-teardown', this.onPanelTearDown.bind(this));
  45. }
  46. private onPanelTearDown() {
  47. if (this.dataSubscription) {
  48. this.dataSubscription.unsubscribe();
  49. this.dataSubscription = null;
  50. }
  51. }
  52. private onInitMetricsPanelEditMode() {
  53. this.addEditorTab('Metrics', metricsTabDirective);
  54. this.addEditorTab('Time range', 'public/app/features/panel/partials/panelTime.html');
  55. }
  56. private onMetricsPanelRefresh() {
  57. // ignore fetching data if another panel is in fullscreen
  58. if (this.otherPanelInFullscreenMode()) { return; }
  59. // if we have snapshot data use that
  60. if (this.panel.snapshotData) {
  61. this.updateTimeRange();
  62. var data = this.panel.snapshotData;
  63. // backward compatability
  64. if (!_.isArray(data)) {
  65. data = data.data;
  66. }
  67. this.events.emit('data-snapshot-load', data);
  68. return;
  69. }
  70. // // ignore if we have data stream
  71. if (this.dataStream) {
  72. return;
  73. }
  74. // clear loading/error state
  75. delete this.error;
  76. this.loading = true;
  77. // load datasource service
  78. this.setTimeQueryStart();
  79. this.datasourceSrv.get(this.panel.datasource)
  80. .then(this.updateTimeRange.bind(this))
  81. .then(this.issueQueries.bind(this))
  82. .then(this.handleQueryResult.bind(this))
  83. .catch(err => {
  84. // if cancelled keep loading set to true
  85. if (err.cancelled) {
  86. console.log('Panel request cancelled', err);
  87. return;
  88. }
  89. this.loading = false;
  90. this.error = err.message || "Request Error";
  91. this.inspector = {error: err};
  92. if (err.data) {
  93. if (err.data.message) {
  94. this.error = err.data.message;
  95. }
  96. if (err.data.error) {
  97. this.error = err.data.error;
  98. }
  99. }
  100. this.events.emit('data-error', err);
  101. console.log('Panel data error:', err);
  102. });
  103. }
  104. setTimeQueryStart() {
  105. this.timing.queryStart = new Date().getTime();
  106. }
  107. setTimeQueryEnd() {
  108. this.timing.queryEnd = new Date().getTime();
  109. }
  110. updateTimeRange(datasource?) {
  111. this.datasource = datasource || this.datasource;
  112. this.range = this.timeSrv.timeRange();
  113. this.applyPanelTimeOverrides();
  114. if (this.panel.maxDataPoints) {
  115. this.resolution = this.panel.maxDataPoints;
  116. } else {
  117. this.resolution = Math.ceil($(window).width() * (this.panel.span / 12));
  118. }
  119. this.calculateInterval();
  120. return this.datasource;
  121. }
  122. calculateInterval() {
  123. var intervalOverride = this.panel.interval;
  124. // if no panel interval check datasource
  125. if (intervalOverride) {
  126. intervalOverride = this.templateSrv.replace(intervalOverride, this.panel.scopedVars);
  127. } else if (this.datasource && this.datasource.interval) {
  128. intervalOverride = this.datasource.interval;
  129. }
  130. var res = kbn.calculateInterval(this.range, this.resolution, intervalOverride);
  131. this.interval = res.interval;
  132. this.intervalMs = res.intervalMs;
  133. }
  134. applyPanelTimeOverrides() {
  135. this.timeInfo = '';
  136. // check panel time overrrides
  137. if (this.panel.timeFrom) {
  138. var timeFromInterpolated = this.templateSrv.replace(this.panel.timeFrom, this.panel.scopedVars);
  139. var timeFromInfo = rangeUtil.describeTextRange(timeFromInterpolated);
  140. if (timeFromInfo.invalid) {
  141. this.timeInfo = 'invalid time override';
  142. return;
  143. }
  144. if (_.isString(this.range.raw.from)) {
  145. var timeFromDate = dateMath.parse(timeFromInfo.from);
  146. this.timeInfo = timeFromInfo.display;
  147. this.range.from = timeFromDate;
  148. this.range.to = dateMath.parse(timeFromInfo.to);
  149. this.range.raw.from = timeFromInfo.from;
  150. this.range.raw.to = timeFromInfo.to;
  151. }
  152. }
  153. if (this.panel.timeShift) {
  154. var timeShiftInterpolated = this.templateSrv.replace(this.panel.timeShift, this.panel.scopedVars);
  155. var timeShiftInfo = rangeUtil.describeTextRange(timeShiftInterpolated);
  156. if (timeShiftInfo.invalid) {
  157. this.timeInfo = 'invalid timeshift';
  158. return;
  159. }
  160. var timeShift = '-' + timeShiftInterpolated;
  161. this.timeInfo += ' timeshift ' + timeShift;
  162. this.range.from = dateMath.parseDateMath(timeShift, this.range.from, false);
  163. this.range.to = dateMath.parseDateMath(timeShift, this.range.to, true);
  164. this.range.raw = {from: this.range.from, to: this.range.to};
  165. }
  166. if (this.panel.hideTimeOverride) {
  167. this.timeInfo = '';
  168. }
  169. }
  170. issueQueries(datasource) {
  171. this.datasource = datasource;
  172. if (!this.panel.targets || this.panel.targets.length === 0) {
  173. return this.$q.when([]);
  174. }
  175. // make shallow copy of scoped vars,
  176. // and add built in variables interval and interval_ms
  177. var scopedVars = Object.assign({}, this.panel.scopedVars, {
  178. "__interval": {text: this.interval, value: this.interval},
  179. "__interval_ms": {text: this.intervalMs, value: this.intervalMs},
  180. });
  181. var metricsQuery = {
  182. panelId: this.panel.id,
  183. range: this.range,
  184. rangeRaw: this.range.raw,
  185. interval: this.interval,
  186. intervalMs: this.intervalMs,
  187. targets: this.panel.targets,
  188. format: this.panel.renderer === 'png' ? 'png' : 'json',
  189. maxDataPoints: this.resolution,
  190. scopedVars: scopedVars,
  191. cacheTimeout: this.panel.cacheTimeout
  192. };
  193. return datasource.query(metricsQuery);
  194. }
  195. handleQueryResult(result) {
  196. this.setTimeQueryEnd();
  197. this.loading = false;
  198. // check for if data source returns subject
  199. if (result && result.subscribe) {
  200. this.handleDataStream(result);
  201. return;
  202. }
  203. if (this.dashboard.snapshot) {
  204. this.panel.snapshotData = result.data;
  205. }
  206. if (!result || !result.data) {
  207. console.log('Data source query result invalid, missing data field:', result);
  208. result = {data: []};
  209. }
  210. this.events.emit('data-received', result.data);
  211. }
  212. handleDataStream(stream) {
  213. // if we already have a connection
  214. if (this.dataStream) {
  215. console.log('two stream observables!');
  216. return;
  217. }
  218. this.dataStream = stream;
  219. this.dataSubscription = stream.subscribe({
  220. next: (data) => {
  221. console.log('dataSubject next!');
  222. if (data.range) {
  223. this.range = data.range;
  224. }
  225. this.events.emit('data-received', data.data);
  226. },
  227. error: (error) => {
  228. this.events.emit('data-error', error);
  229. console.log('panel: observer got error');
  230. },
  231. complete: () => {
  232. console.log('panel: observer got complete');
  233. this.dataStream = null;
  234. }
  235. });
  236. }
  237. setDatasource(datasource) {
  238. // switching to mixed
  239. if (datasource.meta.mixed) {
  240. _.each(this.panel.targets, target => {
  241. target.datasource = this.panel.datasource;
  242. if (!target.datasource) {
  243. target.datasource = config.defaultDatasource;
  244. }
  245. });
  246. } else if (this.datasource && this.datasource.meta.mixed) {
  247. _.each(this.panel.targets, target => {
  248. delete target.datasource;
  249. });
  250. }
  251. this.panel.datasource = datasource.value;
  252. this.datasourceName = datasource.name;
  253. this.datasource = null;
  254. this.refresh();
  255. }
  256. addQuery(target) {
  257. target.refId = this.dashboard.getNextQueryLetter(this.panel);
  258. this.panel.targets.push(target);
  259. this.nextRefId = this.dashboard.getNextQueryLetter(this.panel);
  260. }
  261. removeQuery(target) {
  262. var index = _.indexOf(this.panel.targets, target);
  263. this.panel.targets.splice(index, 1);
  264. this.nextRefId = this.dashboard.getNextQueryLetter(this.panel);
  265. this.refresh();
  266. }
  267. moveQuery(target, direction) {
  268. var index = _.indexOf(this.panel.targets, target);
  269. _.move(this.panel.targets, index, index + direction);
  270. }
  271. }
  272. export {MetricsPanelCtrl};