The open and composable observability and data visualization platform. Visualize metrics, logs, and traces from multiple sources like Prometheus, Loki, Elasticsearch, InfluxDB, Postgres and many more.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
grafana/public/app/angular/panel/metrics_panel_ctrl.ts

245 lines
6.5 KiB

import { isArray } from 'lodash';
import { Unsubscribable } from 'rxjs';
import {
DataFrame,
DataQueryResponse,
DataSourceApi,
LegacyResponseData,
LoadingState,
PanelData,
PanelEvents,
TimeRange,
toDataFrameDTO,
toLegacyResponseData,
} from '@grafana/data';
import { PanelCtrl } from 'app/angular/panel/panel_ctrl';
import { ContextSrv } from 'app/core/services/context_srv';
import { PanelModel } from 'app/features/dashboard/state/PanelModel';
import { applyPanelTimeOverrides } from 'app/features/dashboard/utils/panel';
import { PanelQueryRunner } from '../../features/query/state/PanelQueryRunner';
class MetricsPanelCtrl extends PanelCtrl {
declare datasource: DataSourceApi;
declare range: TimeRange;
contextSrv: ContextSrv;
datasourceSrv: any;
timeSrv: any;
templateSrv: any;
interval: any;
intervalMs: any;
resolution: any;
timeInfo?: string;
Grafana-UI: Update React Hook Form to v7 (#33328) * Update hook form * Update Form component * Update ChangePassword.tsx * Update custom types * Update SaveDashboardForm * Update form story * Update FieldArray.story.tsx * Bump hook form version * Update typescript to v4.2.4 * Update ForgottenPassword.tsx * Update LoginForm.tsx * Update SignupPage.tsx * Update VerifyEmail.tsx * Update AdminEditOrgPage.tsx * Update UserCreatePage.tsx * Update BasicSettings.tsx * Update NotificationChannelForm.tsx * Update NotificationChannelOptions.tsx * Update NotificationSettings.tsx * Update OptionElement.tsx * Update AlertRuleForm.tsx * Update AlertTypeStep.tsx * Update AnnotationsField.tsx * Update ConditionField.tsx * Update ConditionsStep.tsx * Update GroupAndNamespaceFields.tsx * Update LabelsField.tsx * Update QueryStep.tsx * Update RowOptionsForm.tsx * Update SaveDashboardAsForm.tsx * Update NewDashboardsFolder.tsx * Update ImportDashboardForm.tsx * Update DashboardImportPage.tsx * Update NewOrgPage.tsx * Update OrgProfile.tsx * Update UserInviteForm.tsx * Update PlaylistForm.tsx * Update ChangePasswordForm.tsx * Update UserProfileEditForm.tsx * Update TeamSettings.tsx * Update SignupInvited.tsx * Expose setValue from the Form * Update typescript to v4.2.4 * Remove ref from field props * Fix tests * Revert TS update * Use exact version * Update latest batch of changes * Reduce the number of strict TS errors * Fix defaults * more type error fixes * Update CreateTeam * fix folder picker in rule form * fixes for hook form 7 * Update docs Co-authored-by: Domas <domasx2@gmail.com>
4 years ago
skipDataOnInit = false;
dataList: LegacyResponseData[] = [];
querySubscription?: Unsubscribable | null;
QueryProcessing: Observable query interface and RxJS for query & stream processing (#18899) * I needed to learn some rxjs and understand this more, so just playing around * Updated * Removed all the complete calls * Refactoring * StreamHandler -> observable start * progress * simple singal works * Handle update time range * added error handling * wrap old function * minor changes * handle data format in the subscribe function * Use replay subject to return last value to subscribers * Set loading state after no response in 50ms * added missing file * updated comment * Added cancelation of network requests * runRequest: Added unit test scenario framework * Progress on tests * minor refactor of unit tests * updated test * removed some old code * Shared queries work again, and also became so much simplier * unified query and observe methods * implict any fix * Fixed closed subject issue * removed comment * Use last returned data for loading state * WIP: Explore to runRequest makover step1 * Minor progress * Minor progress on explore and runRequest * minor progress * Things are starting to work in explore * Updated prometheus to use new observable query response, greatly simplified code * Revert refId change * Found better solution for key/refId/requestId problem * use observable with loki * tests compile * fix loki query prep * Explore: correct first response handling * Refactorings * Refactoring * Explore: Fixes LoadingState and GraphResults between runs (#18986) * Refactor: Adds state to DataQueryResponse * Fix: Fixes so we do not empty results before new data arrives Fixes: #17409 * Transformations work * observable test data * remove single() from loki promise * Fixed comment * Explore: Fixes failing Loki and Prometheus unit tests (#18995) * Tests: Makes datasource tests work again * Fix: Fixes loki datasource so highligthing works * Chore: Runs Prettier * Fixed query runner tests * Delay loading state indication to 200ms * Fixed test * fixed unit tests * Clear cached calcs * Fixed bug getProcesedDataFrames * Fix the correct test is a better idea * Fix: Fixes so queries in Explore are only run if Graph/Table is shown (#19000) * Fix: Fixes so queries in Explore are only run if Graph/Table is shown Fixes: #18618 * Refactor: Removes unnecessary condition * PanelData: provide legacy data only when needed (#19018) * no legacy * invert logic... now compiles * merge getQueryResponseData and getDataRaw * update comment about query editor * use single getData() function * only send legacy when it is used in explore * pre process rather than post process * pre process rather than post process * Minor refactoring * Add missing tags to test datasource response * MixedDatasource: Adds query observable pattern to MixedDatasource (#19037) * start mixed datasource * Refactor: Refactors into observable parttern * Tests: Fixes tests * Tests: Removes console.log * Refactor: Adds unique requestId
6 years ago
useDataFrames = false;
panelData?: PanelData;
constructor($scope: any, $injector: any) {
super($scope, $injector);
this.contextSrv = $injector.get('contextSrv');
this.datasourceSrv = $injector.get('datasourceSrv');
this.timeSrv = $injector.get('timeSrv');
this.templateSrv = $injector.get('templateSrv');
this.panel.datasource = this.panel.datasource || null;
this.events.on(PanelEvents.refresh, this.onMetricsPanelRefresh.bind(this));
this.events.on(PanelEvents.panelTeardown, this.onPanelTearDown.bind(this));
this.events.on(PanelEvents.componentDidMount, this.onMetricsPanelMounted.bind(this));
}
private onMetricsPanelMounted() {
const queryRunner = this.panel.getQueryRunner() as PanelQueryRunner;
this.querySubscription = queryRunner
.getData({ withTransforms: true, withFieldConfig: true })
.subscribe(this.panelDataObserver);
}
private onPanelTearDown() {
if (this.querySubscription) {
this.querySubscription.unsubscribe();
this.querySubscription = null;
}
}
private onMetricsPanelRefresh() {
// ignore fetching data if another panel is in fullscreen
if (this.otherPanelInFullscreenMode()) {
return;
}
// if we have snapshot data use that
if (this.panel.snapshotData) {
this.updateTimeRange();
let data = this.panel.snapshotData;
// backward compatibility
if (!isArray(data)) {
data = data.data;
}
this.panelData = {
state: LoadingState.Done,
series: data,
timeRange: this.range,
};
// Defer panel rendering till the next digest cycle.
// For some reason snapshot panels don't init at this time, so this helps to avoid rendering issues.
return this.$timeout(() => {
this.events.emit(PanelEvents.dataSnapshotLoad, data);
});
}
// clear loading/error state
delete this.error;
this.loading = true;
// load datasource service
return this.datasourceSrv
.get(this.panel.datasource, this.panel.scopedVars)
.then(this.issueQueries.bind(this))
.catch((err: any) => {
this.processDataError(err);
});
}
processDataError(err: any) {
// if canceled keep loading set to true
if (err.cancelled) {
console.log('Panel request cancelled', err);
return;
}
this.error = err.message || 'Request Error';
if (err.data) {
if (err.data.message) {
this.error = err.data.message;
} else if (err.data.error) {
this.error = err.data.error;
}
}
this.angularDirtyCheck();
}
angularDirtyCheck() {
if (!this.$scope.$root.$$phase) {
this.$scope.$digest();
}
}
// Updates the response with information from the stream
panelDataObserver = {
next: (data: PanelData) => {
this.panelData = data;
if (data.state === LoadingState.Error) {
this.loading = false;
this.processDataError(data.error);
}
// Ignore data in loading state
if (data.state === LoadingState.Loading) {
this.loading = true;
this.angularDirtyCheck();
return;
}
if (data.request) {
const { timeInfo } = data.request;
if (timeInfo) {
this.timeInfo = timeInfo;
}
}
if (data.timeRange) {
this.range = data.timeRange;
}
QueryProcessing: Observable query interface and RxJS for query & stream processing (#18899) * I needed to learn some rxjs and understand this more, so just playing around * Updated * Removed all the complete calls * Refactoring * StreamHandler -> observable start * progress * simple singal works * Handle update time range * added error handling * wrap old function * minor changes * handle data format in the subscribe function * Use replay subject to return last value to subscribers * Set loading state after no response in 50ms * added missing file * updated comment * Added cancelation of network requests * runRequest: Added unit test scenario framework * Progress on tests * minor refactor of unit tests * updated test * removed some old code * Shared queries work again, and also became so much simplier * unified query and observe methods * implict any fix * Fixed closed subject issue * removed comment * Use last returned data for loading state * WIP: Explore to runRequest makover step1 * Minor progress * Minor progress on explore and runRequest * minor progress * Things are starting to work in explore * Updated prometheus to use new observable query response, greatly simplified code * Revert refId change * Found better solution for key/refId/requestId problem * use observable with loki * tests compile * fix loki query prep * Explore: correct first response handling * Refactorings * Refactoring * Explore: Fixes LoadingState and GraphResults between runs (#18986) * Refactor: Adds state to DataQueryResponse * Fix: Fixes so we do not empty results before new data arrives Fixes: #17409 * Transformations work * observable test data * remove single() from loki promise * Fixed comment * Explore: Fixes failing Loki and Prometheus unit tests (#18995) * Tests: Makes datasource tests work again * Fix: Fixes loki datasource so highligthing works * Chore: Runs Prettier * Fixed query runner tests * Delay loading state indication to 200ms * Fixed test * fixed unit tests * Clear cached calcs * Fixed bug getProcesedDataFrames * Fix the correct test is a better idea * Fix: Fixes so queries in Explore are only run if Graph/Table is shown (#19000) * Fix: Fixes so queries in Explore are only run if Graph/Table is shown Fixes: #18618 * Refactor: Removes unnecessary condition * PanelData: provide legacy data only when needed (#19018) * no legacy * invert logic... now compiles * merge getQueryResponseData and getDataRaw * update comment about query editor * use single getData() function * only send legacy when it is used in explore * pre process rather than post process * pre process rather than post process * Minor refactoring * Add missing tags to test datasource response * MixedDatasource: Adds query observable pattern to MixedDatasource (#19037) * start mixed datasource * Refactor: Refactors into observable parttern * Tests: Fixes tests * Tests: Removes console.log * Refactor: Adds unique requestId
6 years ago
if (this.useDataFrames) {
this.handleDataFrames(data.series);
QueryProcessing: Observable query interface and RxJS for query & stream processing (#18899) * I needed to learn some rxjs and understand this more, so just playing around * Updated * Removed all the complete calls * Refactoring * StreamHandler -> observable start * progress * simple singal works * Handle update time range * added error handling * wrap old function * minor changes * handle data format in the subscribe function * Use replay subject to return last value to subscribers * Set loading state after no response in 50ms * added missing file * updated comment * Added cancelation of network requests * runRequest: Added unit test scenario framework * Progress on tests * minor refactor of unit tests * updated test * removed some old code * Shared queries work again, and also became so much simplier * unified query and observe methods * implict any fix * Fixed closed subject issue * removed comment * Use last returned data for loading state * WIP: Explore to runRequest makover step1 * Minor progress * Minor progress on explore and runRequest * minor progress * Things are starting to work in explore * Updated prometheus to use new observable query response, greatly simplified code * Revert refId change * Found better solution for key/refId/requestId problem * use observable with loki * tests compile * fix loki query prep * Explore: correct first response handling * Refactorings * Refactoring * Explore: Fixes LoadingState and GraphResults between runs (#18986) * Refactor: Adds state to DataQueryResponse * Fix: Fixes so we do not empty results before new data arrives Fixes: #17409 * Transformations work * observable test data * remove single() from loki promise * Fixed comment * Explore: Fixes failing Loki and Prometheus unit tests (#18995) * Tests: Makes datasource tests work again * Fix: Fixes loki datasource so highligthing works * Chore: Runs Prettier * Fixed query runner tests * Delay loading state indication to 200ms * Fixed test * fixed unit tests * Clear cached calcs * Fixed bug getProcesedDataFrames * Fix the correct test is a better idea * Fix: Fixes so queries in Explore are only run if Graph/Table is shown (#19000) * Fix: Fixes so queries in Explore are only run if Graph/Table is shown Fixes: #18618 * Refactor: Removes unnecessary condition * PanelData: provide legacy data only when needed (#19018) * no legacy * invert logic... now compiles * merge getQueryResponseData and getDataRaw * update comment about query editor * use single getData() function * only send legacy when it is used in explore * pre process rather than post process * pre process rather than post process * Minor refactoring * Add missing tags to test datasource response * MixedDatasource: Adds query observable pattern to MixedDatasource (#19037) * start mixed datasource * Refactor: Refactors into observable parttern * Tests: Fixes tests * Tests: Removes console.log * Refactor: Adds unique requestId
6 years ago
} else {
// Make the results look as if they came directly from a <6.2 datasource request
const legacy = data.series.map((v) => toLegacyResponseData(v));
QueryProcessing: Observable query interface and RxJS for query & stream processing (#18899) * I needed to learn some rxjs and understand this more, so just playing around * Updated * Removed all the complete calls * Refactoring * StreamHandler -> observable start * progress * simple singal works * Handle update time range * added error handling * wrap old function * minor changes * handle data format in the subscribe function * Use replay subject to return last value to subscribers * Set loading state after no response in 50ms * added missing file * updated comment * Added cancelation of network requests * runRequest: Added unit test scenario framework * Progress on tests * minor refactor of unit tests * updated test * removed some old code * Shared queries work again, and also became so much simplier * unified query and observe methods * implict any fix * Fixed closed subject issue * removed comment * Use last returned data for loading state * WIP: Explore to runRequest makover step1 * Minor progress * Minor progress on explore and runRequest * minor progress * Things are starting to work in explore * Updated prometheus to use new observable query response, greatly simplified code * Revert refId change * Found better solution for key/refId/requestId problem * use observable with loki * tests compile * fix loki query prep * Explore: correct first response handling * Refactorings * Refactoring * Explore: Fixes LoadingState and GraphResults between runs (#18986) * Refactor: Adds state to DataQueryResponse * Fix: Fixes so we do not empty results before new data arrives Fixes: #17409 * Transformations work * observable test data * remove single() from loki promise * Fixed comment * Explore: Fixes failing Loki and Prometheus unit tests (#18995) * Tests: Makes datasource tests work again * Fix: Fixes loki datasource so highligthing works * Chore: Runs Prettier * Fixed query runner tests * Delay loading state indication to 200ms * Fixed test * fixed unit tests * Clear cached calcs * Fixed bug getProcesedDataFrames * Fix the correct test is a better idea * Fix: Fixes so queries in Explore are only run if Graph/Table is shown (#19000) * Fix: Fixes so queries in Explore are only run if Graph/Table is shown Fixes: #18618 * Refactor: Removes unnecessary condition * PanelData: provide legacy data only when needed (#19018) * no legacy * invert logic... now compiles * merge getQueryResponseData and getDataRaw * update comment about query editor * use single getData() function * only send legacy when it is used in explore * pre process rather than post process * pre process rather than post process * Minor refactoring * Add missing tags to test datasource response * MixedDatasource: Adds query observable pattern to MixedDatasource (#19037) * start mixed datasource * Refactor: Refactors into observable parttern * Tests: Fixes tests * Tests: Removes console.log * Refactor: Adds unique requestId
6 years ago
this.handleQueryResult({ data: legacy });
}
this.angularDirtyCheck();
},
};
updateTimeRange(datasource?: DataSourceApi) {
this.datasource = datasource || this.datasource;
this.range = this.timeSrv.timeRange();
const newTimeData = applyPanelTimeOverrides(this.panel, this.range);
this.timeInfo = newTimeData.timeInfo;
this.range = newTimeData.timeRange;
}
issueQueries(datasource: DataSourceApi) {
this.updateTimeRange(datasource);
this.datasource = datasource;
const panel = this.panel as PanelModel;
const queryRunner = panel.getQueryRunner();
return queryRunner.run({
datasource: panel.datasource,
queries: panel.targets,
panelId: panel.id,
dashboardUID: this.dashboard.uid,
DateTime: adding support to select preferred timezone for presentation of date and time values. (#23586) * added moment timezone package. * added a qnd way of selecting timezone. * added a first draft to display how it can be used. * fixed failing tests. * made moment.local to be in utc when running tests. * added tests to verify that the timeZone support works as expected. * Fixed so we use the formatter in the graph context menu. * changed so we will format d3 according to timeZone. * changed from class base to function based for easier consumption. * fixed so tests got green. * renamed to make it shorter. * fixed formatting in logRow. * removed unused value. * added time formatter to flot. * fixed failing tests. * changed so history will use the formatting with support for timezone. * added todo. * added so we append the correct abbrivation behind time. * added time zone abbrevation in timepicker. * adding timezone in rangeutil tool. * will use timezone when formatting range. * changed so we use new functions to format date so timezone is respected. * wip - dashboard settings. * changed so the time picker settings is in react. * added force update. * wip to get the react graph to work. * fixed formatting and parsing on the timepicker. * updated snap to be correct. * fixed so we format values properly in time picker. * make sure we pass timezone on all the proper places. * fixed so we use correct timeZone in explore. * fixed failing tests. * fixed so we always parse from local to selected timezone. * removed unused variable. * reverted back. * trying to fix issue with directive. * fixed issue. * fixed strict null errors. * fixed so we still can select default. * make sure we reads the time zone from getTimezone
5 years ago
timezone: this.dashboard.getTimezone(),
timeInfo: this.timeInfo,
timeRange: this.range,
maxDataPoints: panel.maxDataPoints || this.width,
minInterval: panel.interval,
scopedVars: panel.scopedVars,
cacheTimeout: panel.cacheTimeout,
queryCachingTTL: panel.queryCachingTTL,
transformations: panel.transformations,
});
}
handleDataFrames(data: DataFrame[]) {
this.loading = false;
if (this.dashboard && this.dashboard.snapshot) {
this.panel.snapshotData = data.map((frame) => toDataFrameDTO(frame));
}
try {
this.events.emit(PanelEvents.dataFramesReceived, data);
} catch (err) {
this.processDataError(err);
}
}
handleQueryResult(result: DataQueryResponse) {
this.loading = false;
if (this.dashboard.snapshot) {
this.panel.snapshotData = result.data;
}
if (!result || !result.data) {
console.log('Data source query result invalid, missing data field:', result);
result = { data: [] };
}
try {
this.events.emit(PanelEvents.dataReceived, result.data);
} catch (err) {
this.processDataError(err);
}
}
}
export { MetricsPanelCtrl };