metrics_panel_ctrl.ts 9.0 KB

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