metrics_panel_ctrl.ts 9.9 KB

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