MetricsPanelCtrl: use shared queryRunner to support query execution (#16659)

* move queryRunner to panelModel

* remove isEditing from PanelChrome

* move listener to QueriesTab

* use queryRunner on MetricsPanelCtrl

* Added interval back as prop, not used yet

* QueryRunner: worked on tests

* PanelQueryRunner: Refactoring, added getQueryRunner to PanelModel

* PanelQueryRunner: interpolatel min interval

* merge master and remove grafana-live
This commit is contained in:
Ryan McKinley 2019-05-09 22:09:48 -07:00 committed by Torkel Ödegaard
parent 30bf9bf00f
commit 3c733638ee
5 changed files with 101 additions and 165 deletions

View File

@ -6,12 +6,23 @@ import { PanelCtrl } from 'app/features/panel/panel_ctrl';
import { getExploreUrl } from 'app/core/utils/explore'; import { getExploreUrl } from 'app/core/utils/explore';
import { applyPanelTimeOverrides, getResolution } from 'app/features/dashboard/utils/panel'; import { applyPanelTimeOverrides, getResolution } from 'app/features/dashboard/utils/panel';
import { ContextSrv } from 'app/core/services/context_srv'; import { ContextSrv } from 'app/core/services/context_srv';
import { toLegacyResponseData, isSeriesData, LegacyResponseData, TimeRange } from '@grafana/ui'; import {
toLegacyResponseData,
isSeriesData,
LegacyResponseData,
TimeRange,
DataSourceApi,
PanelData,
LoadingState,
DataQueryResponse,
} from '@grafana/ui';
import { Unsubscribable } from 'rxjs'; import { Unsubscribable } from 'rxjs';
import { PanelModel } from 'app/features/dashboard/state';
import { PanelQueryRunnerFormat } from '../dashboard/state/PanelQueryRunner';
class MetricsPanelCtrl extends PanelCtrl { class MetricsPanelCtrl extends PanelCtrl {
scope: any; scope: any;
datasource: any; datasource: DataSourceApi;
$q: any; $q: any;
$timeout: any; $timeout: any;
contextSrv: ContextSrv; contextSrv: ContextSrv;
@ -24,11 +35,10 @@ class MetricsPanelCtrl extends PanelCtrl {
resolution: any; resolution: any;
timeInfo?: string; timeInfo?: string;
skipDataOnInit: boolean; skipDataOnInit: boolean;
dataStream: any;
dataSubscription?: Unsubscribable;
dataList: LegacyResponseData[]; dataList: LegacyResponseData[];
querySubscription?: Unsubscribable;
constructor($scope, $injector) { constructor($scope: any, $injector: any) {
super($scope, $injector); super($scope, $injector);
this.$q = $injector.get('$q'); this.$q = $injector.get('$q');
@ -44,9 +54,9 @@ class MetricsPanelCtrl extends PanelCtrl {
} }
private onPanelTearDown() { private onPanelTearDown() {
if (this.dataSubscription) { if (this.querySubscription) {
this.dataSubscription.unsubscribe(); this.querySubscription.unsubscribe();
this.dataSubscription = null; this.querySubscription = null;
} }
} }
@ -72,47 +82,76 @@ class MetricsPanelCtrl extends PanelCtrl {
}); });
} }
// // ignore if we have data stream
if (this.dataStream) {
return;
}
// clear loading/error state // clear loading/error state
delete this.error; delete this.error;
this.loading = true; this.loading = true;
// load datasource service // load datasource service
this.datasourceSrv return (
.get(this.panel.datasource, this.panel.scopedVars) this.datasourceSrv
.then(this.updateTimeRange.bind(this)) .get(this.panel.datasource, this.panel.scopedVars)
.then(this.issueQueries.bind(this)) .then(this.updateTimeRange.bind(this))
.then(this.handleQueryResult.bind(this)) .then(this.issueQueries.bind(this))
.catch(err => { // NOTE handleQueryResult is called by panelDataObserver
// if canceled keep loading set to true .catch((err: any) => {
if (err.cancelled) { this.processDataError(err);
console.log('Panel request cancelled', err); })
return; );
}
this.loading = false;
this.error = err.message || 'Request Error';
this.inspector = { error: err };
if (err.data) {
if (err.data.message) {
this.error = err.data.message;
}
if (err.data.error) {
this.error = err.data.error;
}
}
this.events.emit('data-error', err);
console.log('Panel data error:', err);
});
} }
updateTimeRange(datasource?) { processDataError(err: any) {
// if canceled keep loading set to true
if (err.cancelled) {
console.log('Panel request cancelled', err);
return;
}
this.loading = false;
this.error = err.message || 'Request Error';
this.inspector = { error: err };
if (err.data) {
if (err.data.message) {
this.error = err.data.message;
}
if (err.data.error) {
this.error = err.data.error;
}
}
this.events.emit('data-error', err);
console.log('Panel data error:', err);
}
// Updates the response with information from the stream
panelDataObserver = {
next: (data: PanelData) => {
if (data.state === LoadingState.Error) {
this.loading = false;
this.processDataError(data.error);
} else if (data.state === LoadingState.Done) {
this.loading = false;
// The result should already be processed, but just in case
if (!data.legacy) {
data.legacy = data.series.map(v => {
if (isSeriesData(v)) {
return toLegacyResponseData(v);
}
return v;
});
}
// Make the results look like they came directly from a <6.2 datasource request
// NOTE: any object other than 'data' is no longer supported supported
this.handleQueryResult({
data: data.legacy,
});
}
},
};
updateTimeRange(datasource?: DataSourceApi) {
this.datasource = datasource || this.datasource; this.datasource = datasource || this.datasource;
this.range = this.timeSrv.timeRange(); this.range = this.timeSrv.timeRange();
this.resolution = getResolution(this.panel); this.resolution = getResolution(this.panel);
@ -141,46 +180,34 @@ class MetricsPanelCtrl extends PanelCtrl {
this.intervalMs = res.intervalMs; this.intervalMs = res.intervalMs;
} }
issueQueries(datasource) { issueQueries(datasource: DataSourceApi) {
this.datasource = datasource; this.datasource = datasource;
if (!this.panel.targets || this.panel.targets.length === 0) { const panel = this.panel as PanelModel;
return this.$q.when([]); const queryRunner = panel.getQueryRunner();
if (!this.querySubscription) {
this.querySubscription = queryRunner.subscribe(this.panelDataObserver, PanelQueryRunnerFormat.legacy);
} }
// make shallow copy of scoped vars, return queryRunner.run({
// and add built in variables interval and interval_ms datasource: panel.datasource,
const scopedVars = Object.assign({}, this.panel.scopedVars, { queries: panel.targets,
__interval: { text: this.interval, value: this.interval }, panelId: panel.id,
__interval_ms: { text: this.intervalMs, value: this.intervalMs },
});
const metricsQuery = {
timezone: this.dashboard.getTimezone(),
panelId: this.panel.id,
dashboardId: this.dashboard.id, dashboardId: this.dashboard.id,
range: this.range, timezone: this.dashboard.timezone,
rangeRaw: this.range.raw, timeRange: this.range,
interval: this.interval, widthPixels: this.resolution, // The pixel width
intervalMs: this.intervalMs, maxDataPoints: panel.maxDataPoints,
targets: this.panel.targets, minInterval: panel.interval,
maxDataPoints: this.resolution, scopedVars: panel.scopedVars,
scopedVars: scopedVars, cacheTimeout: panel.cacheTimeout,
cacheTimeout: this.panel.cacheTimeout, });
};
return datasource.query(metricsQuery);
} }
handleQueryResult(result) { handleQueryResult(result: DataQueryResponse) {
this.loading = false; this.loading = false;
// check for if data source returns subject
if (result && result.subscribe) {
this.handleDataStream(result);
return;
}
if (this.dashboard.snapshot) { if (this.dashboard.snapshot) {
this.panel.snapshotData = result.data; this.panel.snapshotData = result.data;
} }
@ -190,41 +217,7 @@ class MetricsPanelCtrl extends PanelCtrl {
result = { data: [] }; result = { data: [] };
} }
// Make sure the data is TableData | TimeSeries this.events.emit('data-received', result.data);
const data = result.data.map(v => {
if (isSeriesData(v)) {
return toLegacyResponseData(v);
}
return v;
});
this.events.emit('data-received', data);
}
handleDataStream(stream) {
// if we already have a connection
if (this.dataStream) {
console.log('two stream observables!');
return;
}
this.dataStream = stream;
this.dataSubscription = stream.subscribe({
next: data => {
console.log('dataSubject next!');
if (data.range) {
this.range = data.range;
}
this.events.emit('data-received', data.data);
},
error: error => {
this.events.emit('data-error', error);
console.log('panel: observer got error');
},
complete: () => {
console.log('panel: observer got complete');
this.dataStream = null;
},
});
} }
getAdditionalMenuItems() { getAdditionalMenuItems() {

View File

@ -1,7 +0,0 @@
{
"type": "datasource",
"name": "Grafana Live",
"id": "grafana-live",
"metrics": true
}

View File

@ -1,34 +0,0 @@
import { liveSrv } from 'app/core/core';
class DataObservable {
target: any;
constructor(target) {
this.target = target;
}
subscribe(options) {
const observable = liveSrv.subscribe(this.target.stream);
return observable.subscribe(data => {
console.log('grafana stream ds data!', data);
});
}
}
export class GrafanaStreamDS {
subscription: any;
/** @ngInject */
constructor() {}
query(options): any {
if (options.targets.length === 0) {
return Promise.resolve({ data: [] });
}
const target = options.targets[0];
const observable = new DataObservable(target);
return Promise.resolve(observable);
}
}

View File

@ -1,8 +0,0 @@
import { GrafanaStreamDS } from './datasource';
import { QueryCtrl } from 'app/plugins/sdk';
class GrafanaQueryCtrl extends QueryCtrl {
static templateUrl = 'partials/query.editor.html';
}
export { GrafanaStreamDS as Datasource, GrafanaQueryCtrl as QueryCtrl };

View File

@ -1,8 +0,0 @@
<query-editor-row query-ctrl="ctrl" can-collapse="false">
<div class="gf-form-inline">
<div class="gf-form gf-form--grow">
<label class="gf-form-label width-8">Stream</label>
<input type="text" class="gf-form-input" ng-model="ctrl.target.stream" spellcheck='false' placeholder="metric">
</div>
</div>
</query-editor-row>