metrics_panel_ctrl.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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 { encodePathComponent } from 'app/core/utils/location_util';
  9. import { metricsTabDirective } from './metrics_tab';
  10. class MetricsPanelCtrl extends PanelCtrl {
  11. scope: any;
  12. datasource: any;
  13. datasourceName: any;
  14. $q: any;
  15. $timeout: any;
  16. contextSrv: any;
  17. datasourceSrv: any;
  18. timeSrv: any;
  19. templateSrv: any;
  20. timing: any;
  21. range: any;
  22. interval: any;
  23. intervalMs: any;
  24. resolution: any;
  25. timeInfo: any;
  26. skipDataOnInit: boolean;
  27. dataStream: any;
  28. dataSubscription: any;
  29. dataList: any;
  30. nextRefId: string;
  31. constructor($scope, $injector) {
  32. super($scope, $injector);
  33. // make metrics tab the default
  34. this.editorTabIndex = 1;
  35. this.$q = $injector.get('$q');
  36. this.contextSrv = $injector.get('contextSrv');
  37. this.datasourceSrv = $injector.get('datasourceSrv');
  38. this.timeSrv = $injector.get('timeSrv');
  39. this.templateSrv = $injector.get('templateSrv');
  40. this.scope = $scope;
  41. this.panel.datasource = this.panel.datasource || null;
  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()) {
  62. return;
  63. }
  64. // if we have snapshot data use that
  65. if (this.panel.snapshotData) {
  66. this.updateTimeRange();
  67. let data = this.panel.snapshotData;
  68. // backward compatibility
  69. if (!_.isArray(data)) {
  70. data = data.data;
  71. }
  72. // Defer panel rendering till the next digest cycle.
  73. // For some reason snapshot panels don't init at this time, so this helps to avoid rendering issues.
  74. return this.$timeout(() => {
  75. this.events.emit('data-snapshot-load', data);
  76. });
  77. }
  78. // // ignore if we have data stream
  79. if (this.dataStream) {
  80. return;
  81. }
  82. // clear loading/error state
  83. delete this.error;
  84. this.loading = true;
  85. // load datasource service
  86. this.setTimeQueryStart();
  87. this.datasourceSrv
  88. .get(this.panel.datasource)
  89. .then(this.updateTimeRange.bind(this))
  90. .then(this.issueQueries.bind(this))
  91. .then(this.handleQueryResult.bind(this))
  92. .catch(err => {
  93. // if cancelled keep loading set to true
  94. if (err.cancelled) {
  95. console.log('Panel request cancelled', err);
  96. return;
  97. }
  98. this.loading = false;
  99. this.error = err.message || 'Request Error';
  100. this.inspector = { error: err };
  101. if (err.data) {
  102. if (err.data.message) {
  103. this.error = err.data.message;
  104. }
  105. if (err.data.error) {
  106. this.error = err.data.error;
  107. }
  108. }
  109. this.events.emit('data-error', err);
  110. console.log('Panel data error:', err);
  111. });
  112. }
  113. setTimeQueryStart() {
  114. this.timing.queryStart = new Date().getTime();
  115. }
  116. setTimeQueryEnd() {
  117. this.timing.queryEnd = new Date().getTime();
  118. }
  119. updateTimeRange(datasource?) {
  120. this.datasource = datasource || this.datasource;
  121. this.range = this.timeSrv.timeRange();
  122. this.applyPanelTimeOverrides();
  123. if (this.panel.maxDataPoints) {
  124. this.resolution = this.panel.maxDataPoints;
  125. } else {
  126. this.resolution = Math.ceil($(window).width() * (this.panel.gridPos.w / 24));
  127. }
  128. this.calculateInterval();
  129. return this.datasource;
  130. }
  131. calculateInterval() {
  132. let intervalOverride = this.panel.interval;
  133. // if no panel interval check datasource
  134. if (intervalOverride) {
  135. intervalOverride = this.templateSrv.replace(intervalOverride, this.panel.scopedVars);
  136. } else if (this.datasource && this.datasource.interval) {
  137. intervalOverride = this.datasource.interval;
  138. }
  139. const res = kbn.calculateInterval(this.range, this.resolution, intervalOverride);
  140. this.interval = res.interval;
  141. this.intervalMs = res.intervalMs;
  142. }
  143. applyPanelTimeOverrides() {
  144. this.timeInfo = '';
  145. // check panel time overrrides
  146. if (this.panel.timeFrom) {
  147. const timeFromInterpolated = this.templateSrv.replace(this.panel.timeFrom, this.panel.scopedVars);
  148. const timeFromInfo = rangeUtil.describeTextRange(timeFromInterpolated);
  149. if (timeFromInfo.invalid) {
  150. this.timeInfo = 'invalid time override';
  151. return;
  152. }
  153. if (_.isString(this.range.raw.from)) {
  154. const timeFromDate = dateMath.parse(timeFromInfo.from);
  155. this.timeInfo = timeFromInfo.display;
  156. this.range.from = timeFromDate;
  157. this.range.to = dateMath.parse(timeFromInfo.to);
  158. this.range.raw.from = timeFromInfo.from;
  159. this.range.raw.to = timeFromInfo.to;
  160. }
  161. }
  162. if (this.panel.timeShift) {
  163. const timeShiftInterpolated = this.templateSrv.replace(this.panel.timeShift, this.panel.scopedVars);
  164. const timeShiftInfo = rangeUtil.describeTextRange(timeShiftInterpolated);
  165. if (timeShiftInfo.invalid) {
  166. this.timeInfo = 'invalid timeshift';
  167. return;
  168. }
  169. const timeShift = '-' + timeShiftInterpolated;
  170. this.timeInfo += ' timeshift ' + timeShift;
  171. this.range.from = dateMath.parseDateMath(timeShift, this.range.from, false);
  172. this.range.to = dateMath.parseDateMath(timeShift, this.range.to, true);
  173. this.range.raw = { from: this.range.from, to: this.range.to };
  174. }
  175. if (this.panel.hideTimeOverride) {
  176. this.timeInfo = '';
  177. }
  178. }
  179. issueQueries(datasource) {
  180. this.datasource = datasource;
  181. if (!this.panel.targets || this.panel.targets.length === 0) {
  182. return this.$q.when([]);
  183. }
  184. // make shallow copy of scoped vars,
  185. // and add built in variables interval and interval_ms
  186. const scopedVars = Object.assign({}, this.panel.scopedVars, {
  187. __interval: { text: this.interval, value: this.interval },
  188. __interval_ms: { text: this.intervalMs, value: this.intervalMs },
  189. });
  190. const metricsQuery = {
  191. timezone: this.dashboard.getTimezone(),
  192. panelId: this.panel.id,
  193. dashboardId: this.dashboard.id,
  194. range: this.range,
  195. rangeRaw: this.range.raw,
  196. interval: this.interval,
  197. intervalMs: this.intervalMs,
  198. targets: this.panel.targets,
  199. maxDataPoints: this.resolution,
  200. scopedVars: scopedVars,
  201. cacheTimeout: this.panel.cacheTimeout,
  202. };
  203. return datasource.query(metricsQuery);
  204. }
  205. handleQueryResult(result) {
  206. this.setTimeQueryEnd();
  207. this.loading = false;
  208. // check for if data source returns subject
  209. if (result && result.subscribe) {
  210. this.handleDataStream(result);
  211. return;
  212. }
  213. if (this.dashboard.snapshot) {
  214. this.panel.snapshotData = result.data;
  215. }
  216. if (!result || !result.data) {
  217. console.log('Data source query result invalid, missing data field:', result);
  218. result = { data: [] };
  219. }
  220. this.events.emit('data-received', result.data);
  221. }
  222. handleDataStream(stream) {
  223. // if we already have a connection
  224. if (this.dataStream) {
  225. console.log('two stream observables!');
  226. return;
  227. }
  228. this.dataStream = stream;
  229. this.dataSubscription = stream.subscribe({
  230. next: data => {
  231. console.log('dataSubject next!');
  232. if (data.range) {
  233. this.range = data.range;
  234. }
  235. this.events.emit('data-received', data.data);
  236. },
  237. error: error => {
  238. this.events.emit('data-error', error);
  239. console.log('panel: observer got error');
  240. },
  241. complete: () => {
  242. console.log('panel: observer got complete');
  243. this.dataStream = null;
  244. },
  245. });
  246. }
  247. setDatasource(datasource) {
  248. // switching to mixed
  249. if (datasource.meta.mixed) {
  250. _.each(this.panel.targets, target => {
  251. target.datasource = this.panel.datasource;
  252. if (!target.datasource) {
  253. target.datasource = config.defaultDatasource;
  254. }
  255. });
  256. } else if (this.datasource && this.datasource.meta.mixed) {
  257. _.each(this.panel.targets, target => {
  258. delete target.datasource;
  259. });
  260. }
  261. this.panel.datasource = datasource.value;
  262. this.datasourceName = datasource.name;
  263. this.datasource = null;
  264. this.refresh();
  265. }
  266. getAdditionalMenuItems() {
  267. const items = [];
  268. if (config.exploreEnabled && this.contextSrv.isEditor && this.datasource && this.datasource.supportsExplore) {
  269. items.push({
  270. text: 'Explore',
  271. click: 'ctrl.explore();',
  272. icon: 'fa fa-fw fa-rocket',
  273. shortcut: 'x',
  274. });
  275. }
  276. return items;
  277. }
  278. explore() {
  279. const range = this.timeSrv.timeRangeForUrl();
  280. const state = {
  281. ...this.datasource.getExploreState(this.panel),
  282. range,
  283. };
  284. const exploreState = encodePathComponent(JSON.stringify(state));
  285. this.$location.url(`/explore?state=${exploreState}`);
  286. }
  287. addQuery(target) {
  288. target.refId = this.dashboard.getNextQueryLetter(this.panel);
  289. this.panel.targets.push(target);
  290. this.nextRefId = this.dashboard.getNextQueryLetter(this.panel);
  291. }
  292. removeQuery(target) {
  293. const index = _.indexOf(this.panel.targets, target);
  294. this.panel.targets.splice(index, 1);
  295. this.nextRefId = this.dashboard.getNextQueryLetter(this.panel);
  296. this.refresh();
  297. }
  298. moveQuery(target, direction) {
  299. const index = _.indexOf(this.panel.targets, target);
  300. _.move(this.panel.targets, index, index + direction);
  301. }
  302. }
  303. export { MetricsPanelCtrl };