metrics_panel_ctrl.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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. 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. 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, 1, 'fa fa-database');
  54. this.addEditorTab('Time range', 'public/app/features/panel/partials/panelTime.html');
  55. }
  56. private onMetricsPanelRefresh() {
  57. console.log('metrics_panel_ctrl:onRefresh');
  58. // ignore fetching data if another panel is in fullscreen
  59. if (this.otherPanelInFullscreenMode()) {
  60. return;
  61. }
  62. // if we have snapshot data use that
  63. if (this.panel.snapshotData) {
  64. this.updateTimeRange();
  65. let data = this.panel.snapshotData;
  66. // backward compatibility
  67. if (!_.isArray(data)) {
  68. data = data.data;
  69. }
  70. // Defer panel rendering till the next digest cycle.
  71. // For some reason snapshot panels don't init at this time, so this helps to avoid rendering issues.
  72. return this.$timeout(() => {
  73. this.events.emit('data-snapshot-load', data);
  74. });
  75. }
  76. // // ignore if we have data stream
  77. if (this.dataStream) {
  78. return;
  79. }
  80. // clear loading/error state
  81. delete this.error;
  82. this.loading = true;
  83. // load datasource service
  84. this.setTimeQueryStart();
  85. this.datasourceSrv
  86. .get(this.panel.datasource)
  87. .then(this.updateTimeRange.bind(this))
  88. .then(this.issueQueries.bind(this))
  89. .then(this.handleQueryResult.bind(this))
  90. .catch(err => {
  91. // if cancelled keep loading set to true
  92. if (err.cancelled) {
  93. console.log('Panel request cancelled', err);
  94. return;
  95. }
  96. this.loading = false;
  97. this.error = err.message || 'Request Error';
  98. this.inspector = { error: err };
  99. if (err.data) {
  100. if (err.data.message) {
  101. this.error = err.data.message;
  102. }
  103. if (err.data.error) {
  104. this.error = err.data.error;
  105. }
  106. }
  107. this.events.emit('data-error', err);
  108. console.log('Panel data error:', err);
  109. });
  110. }
  111. setTimeQueryStart() {
  112. this.timing.queryStart = new Date().getTime();
  113. }
  114. setTimeQueryEnd() {
  115. this.timing.queryEnd = new Date().getTime();
  116. }
  117. updateTimeRange(datasource?) {
  118. this.datasource = datasource || this.datasource;
  119. this.range = this.timeSrv.timeRange();
  120. this.applyPanelTimeOverrides();
  121. if (this.panel.maxDataPoints) {
  122. this.resolution = this.panel.maxDataPoints;
  123. } else {
  124. this.resolution = Math.ceil($(window).width() * (this.panel.gridPos.w / 24));
  125. }
  126. this.calculateInterval();
  127. return this.datasource;
  128. }
  129. calculateInterval() {
  130. let intervalOverride = this.panel.interval;
  131. // if no panel interval check datasource
  132. if (intervalOverride) {
  133. intervalOverride = this.templateSrv.replace(intervalOverride, this.panel.scopedVars);
  134. } else if (this.datasource && this.datasource.interval) {
  135. intervalOverride = this.datasource.interval;
  136. }
  137. const res = kbn.calculateInterval(this.range, this.resolution, intervalOverride);
  138. this.interval = res.interval;
  139. this.intervalMs = res.intervalMs;
  140. }
  141. applyPanelTimeOverrides() {
  142. this.timeInfo = '';
  143. // check panel time overrrides
  144. if (this.panel.timeFrom) {
  145. const timeFromInterpolated = this.templateSrv.replace(this.panel.timeFrom, this.panel.scopedVars);
  146. const timeFromInfo = rangeUtil.describeTextRange(timeFromInterpolated);
  147. if (timeFromInfo.invalid) {
  148. this.timeInfo = 'invalid time override';
  149. return;
  150. }
  151. if (_.isString(this.range.raw.from)) {
  152. const timeFromDate = dateMath.parse(timeFromInfo.from);
  153. this.timeInfo = timeFromInfo.display;
  154. this.range.from = timeFromDate;
  155. this.range.to = dateMath.parse(timeFromInfo.to);
  156. this.range.raw.from = timeFromInfo.from;
  157. this.range.raw.to = timeFromInfo.to;
  158. }
  159. }
  160. if (this.panel.timeShift) {
  161. const timeShiftInterpolated = this.templateSrv.replace(this.panel.timeShift, this.panel.scopedVars);
  162. const timeShiftInfo = rangeUtil.describeTextRange(timeShiftInterpolated);
  163. if (timeShiftInfo.invalid) {
  164. this.timeInfo = 'invalid timeshift';
  165. return;
  166. }
  167. const timeShift = '-' + timeShiftInterpolated;
  168. this.timeInfo += ' timeshift ' + timeShift;
  169. this.range.from = dateMath.parseDateMath(timeShift, this.range.from, false);
  170. this.range.to = dateMath.parseDateMath(timeShift, this.range.to, true);
  171. this.range.raw = { from: this.range.from, to: this.range.to };
  172. }
  173. if (this.panel.hideTimeOverride) {
  174. this.timeInfo = '';
  175. }
  176. }
  177. issueQueries(datasource) {
  178. this.datasource = datasource;
  179. if (!this.panel.targets || this.panel.targets.length === 0) {
  180. return this.$q.when([]);
  181. }
  182. // make shallow copy of scoped vars,
  183. // and add built in variables interval and interval_ms
  184. const scopedVars = Object.assign({}, this.panel.scopedVars, {
  185. __interval: { text: this.interval, value: this.interval },
  186. __interval_ms: { text: this.intervalMs, value: this.intervalMs },
  187. });
  188. const metricsQuery = {
  189. timezone: this.dashboard.getTimezone(),
  190. panelId: this.panel.id,
  191. dashboardId: this.dashboard.id,
  192. range: this.range,
  193. rangeRaw: this.range.raw,
  194. interval: this.interval,
  195. intervalMs: this.intervalMs,
  196. targets: this.panel.targets,
  197. maxDataPoints: this.resolution,
  198. scopedVars: scopedVars,
  199. cacheTimeout: this.panel.cacheTimeout,
  200. };
  201. return datasource.query(metricsQuery);
  202. }
  203. handleQueryResult(result) {
  204. this.setTimeQueryEnd();
  205. this.loading = false;
  206. // check for if data source returns subject
  207. if (result && result.subscribe) {
  208. this.handleDataStream(result);
  209. return;
  210. }
  211. if (this.dashboard.snapshot) {
  212. this.panel.snapshotData = result.data;
  213. }
  214. if (!result || !result.data) {
  215. console.log('Data source query result invalid, missing data field:', result);
  216. result = { data: [] };
  217. }
  218. this.events.emit('data-received', result.data);
  219. }
  220. handleDataStream(stream) {
  221. // if we already have a connection
  222. if (this.dataStream) {
  223. console.log('two stream observables!');
  224. return;
  225. }
  226. this.dataStream = stream;
  227. this.dataSubscription = stream.subscribe({
  228. next: data => {
  229. console.log('dataSubject next!');
  230. if (data.range) {
  231. this.range = data.range;
  232. }
  233. this.events.emit('data-received', data.data);
  234. },
  235. error: error => {
  236. this.events.emit('data-error', error);
  237. console.log('panel: observer got error');
  238. },
  239. complete: () => {
  240. console.log('panel: observer got complete');
  241. this.dataStream = null;
  242. },
  243. });
  244. }
  245. setDatasource(datasource) {
  246. // switching to mixed
  247. if (datasource.meta.mixed) {
  248. _.each(this.panel.targets, target => {
  249. target.datasource = this.panel.datasource;
  250. if (!target.datasource) {
  251. target.datasource = config.defaultDatasource;
  252. }
  253. });
  254. } else if (this.datasource && this.datasource.meta.mixed) {
  255. _.each(this.panel.targets, target => {
  256. delete target.datasource;
  257. });
  258. }
  259. this.panel.datasource = datasource.value;
  260. this.datasourceName = datasource.name;
  261. this.datasource = null;
  262. this.refresh();
  263. }
  264. getAdditionalMenuItems() {
  265. const items = [];
  266. if (
  267. config.exploreEnabled &&
  268. this.contextSrv.isEditor &&
  269. this.datasource &&
  270. (this.datasource.meta.explore || this.datasource.meta.id === 'mixed')
  271. ) {
  272. items.push({
  273. text: 'Explore',
  274. click: 'ctrl.explore();',
  275. icon: 'fa fa-fw fa-rocket',
  276. shortcut: 'x',
  277. });
  278. }
  279. return items;
  280. }
  281. async explore() {
  282. const url = await getExploreUrl(this.panel, this.panel.targets, this.datasource, this.datasourceSrv, this.timeSrv);
  283. if (url) {
  284. this.$timeout(() => this.$location.url(url));
  285. }
  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 };