Browse Source

Better hastic datasource logic in code and messages #209 (#211)

* some refactorings + types

* hasticServerURL better usage

* more renaming + fixes
master
Alexey Velikiy 6 years ago committed by GitHub
parent
commit
39a1101cad
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 19
      src/panel/graph_panel/controllers/analytic_controller.ts
  2. 43
      src/panel/graph_panel/graph_ctrl.ts
  3. 46
      src/panel/graph_panel/services/analytic_service.ts

19
src/panel/graph_panel/controllers/analytic_controller.ts

@ -218,7 +218,7 @@ export class AnalyticController {
this.analyticUnits.forEach(a => this._runStatusWaiter(a)); this.analyticUnits.forEach(a => this._runStatusWaiter(a));
} }
async fetchAnalyticUnitsSegments(from: number, to: number) { async fetchAnalyticUnitsSegments(from: number, to: number): Promise<void[]> {
if(!_.isNumber(+from)) { if(!_.isNumber(+from)) {
throw new Error('from isn`t number'); throw new Error('from isn`t number');
} }
@ -258,7 +258,6 @@ export class AnalyticController {
return []; return [];
} }
await this._analyticService.updateMetric(unit.id, this._currentMetric, this._currentDatasource); await this._analyticService.updateMetric(unit.id, this._currentMetric, this._currentDatasource);
const newIds = await this._analyticService.updateSegments( const newIds = await this._analyticService.updateSegments(
unit.id, this._labelingDataAddedSegments, this._labelingDataRemovedSegments unit.id, this._labelingDataAddedSegments, this._labelingDataRemovedSegments
@ -270,7 +269,7 @@ export class AnalyticController {
} }
// TODO: move to renderer // TODO: move to renderer
updateFlotEvents(isEditMode: boolean, options: any) { updateFlotEvents(isEditMode: boolean, options: any): void {
if(options.grid.markings === undefined) { if(options.grid.markings === undefined) {
options.markings = []; options.markings = [];
} }
@ -332,7 +331,7 @@ export class AnalyticController {
} }
deleteLabelingAnalyticUnitSegmentsInRange(from: number, to: number) { deleteLabelingAnalyticUnitSegmentsInRange(from: number, to: number): void {
const allRemovedSegs = this.labelingUnit.removeSegmentsInRange(from, to); const allRemovedSegs = this.labelingUnit.removeSegmentsInRange(from, to);
allRemovedSegs.forEach(s => { allRemovedSegs.forEach(s => {
if(!this._labelingDataAddedSegments.has(s.id)) { if(!this._labelingDataAddedSegments.has(s.id)) {
@ -342,7 +341,7 @@ export class AnalyticController {
this._labelingDataAddedSegments.removeInRange(from, to); this._labelingDataAddedSegments.removeInRange(from, to);
} }
toggleLabelingMode(labelingMode: LabelingMode) { toggleLabelingMode(labelingMode: LabelingMode): void {
if(!this.inLabelingMode) { if(!this.inLabelingMode) {
throw new Error(`Can't enter ${labelingMode} mode when labeling mode is disabled`); throw new Error(`Can't enter ${labelingMode} mode when labeling mode is disabled`);
} }
@ -353,7 +352,7 @@ export class AnalyticController {
} }
} }
async removeAnalyticUnit(id: AnalyticUnitId, silent: boolean = false) { async removeAnalyticUnit(id: AnalyticUnitId, silent: boolean = false): Promise<void> {
if(id === this._selectedAnalyticUnitId) { if(id === this._selectedAnalyticUnitId) {
this.dropLabeling(); this.dropLabeling();
} }
@ -363,12 +362,12 @@ export class AnalyticController {
} }
} }
async toggleAnalyticUnitAlert(analyticUnit: AnalyticUnit) { async toggleAnalyticUnitAlert(analyticUnit: AnalyticUnit): Promise<void> {
analyticUnit.alert = analyticUnit.alert ? true : false; analyticUnit.alert = analyticUnit.alert ? true : false;
await this._analyticService.setAnalyticUnitAlert(analyticUnit); await this._analyticService.setAnalyticUnitAlert(analyticUnit);
} }
async fetchAnalyticUnitName(analyticUnit: AnalyticUnit) { async fetchAnalyticUnitName(analyticUnit: AnalyticUnit): Promise<void> {
let updateObj = { let updateObj = {
id: analyticUnit.id, id: analyticUnit.id,
name: analyticUnit.name name: analyticUnit.name
@ -376,13 +375,13 @@ export class AnalyticController {
await this._analyticService.updateAnalyticUnit(analyticUnit.id, updateObj); await this._analyticService.updateAnalyticUnit(analyticUnit.id, updateObj);
} }
async updateThresholds() { async updateThresholds(): Promise<void> {
const ids = _.map(this._panelObject.analyticUnits, (analyticUnit: any) => analyticUnit.id); const ids = _.map(this._panelObject.analyticUnits, (analyticUnit: any) => analyticUnit.id);
const thresholds = await this._analyticService.getThresholds(ids); const thresholds = await this._analyticService.getThresholds(ids);
this._thresholds = thresholds; this._thresholds = thresholds;
} }
getThreshold(id: AnalyticUnitId) { getThreshold(id: AnalyticUnitId): Threshold {
let threshold = _.find(this._thresholds, { id }); let threshold = _.find(this._thresholds, { id });
if(threshold === undefined) { if(threshold === undefined) {
threshold = { threshold = {

43
src/panel/graph_panel/graph_ctrl.ts

@ -144,7 +144,6 @@ class GraphCtrl extends MetricsPanelCtrl {
constructor( constructor(
$scope, $injector, private $http, $scope, $injector, private $http,
private annotationsSrv, private annotationsSrv,
private keybindingSrv,
private backendSrv: BackendSrv, private backendSrv: BackendSrv,
private popoverSrv, private popoverSrv,
private contextSrv private contextSrv
@ -184,14 +183,14 @@ class GraphCtrl extends MetricsPanelCtrl {
this.rebindKeys(); this.rebindKeys();
} }
getBackendURL(): string { getHasticDatasourceURL(): string {
const datasourceId = this.panel.hasticDatasource; const hasticDatasourceId = this.panel.hasticDatasource;
if(datasourceId !== undefined && datasourceId !== null) { if(hasticDatasourceId !== undefined && hasticDatasourceId !== null) {
const datasource = _.find(this._hasticDatasources, { id: datasourceId }); const hasticDatasource = _.find(this._hasticDatasources, { id: hasticDatasourceId });
if(datasource.access === 'proxy') { if(hasticDatasource.access === 'proxy') {
return `/api/datasources/proxy/${datasource.id}`; return `/api/datasources/proxy/${hasticDatasource.id}`;
} }
return datasource.url; return hasticDatasource.url;
} }
return undefined; return undefined;
} }
@ -210,18 +209,16 @@ class GraphCtrl extends MetricsPanelCtrl {
return _.keys(this._analyticUnitTypes); return _.keys(this._analyticUnitTypes);
} }
async runBackendConnectivityCheck() { async runDatasourceConnectivityCheck() {
const backendURL = this.getBackendURL();
try { try {
const connected = await this.analyticService.isBackendOk(); const connected = await this.analyticService.isDatasourceOk();
if(connected) { if(connected) {
this.updateAnalyticUnitTypes(); this.updateAnalyticUnitTypes();
appEvents.emit( appEvents.emit(
'alert-success', 'alert-success',
[ [
'Connected to Hastic server', 'Connected to Hastic Datasource',
`Hastic server: "${backendURL}"` `Hastic datasource URL: "${this.analyticService.hasticDatasourceURL}"`
] ]
); );
} }
@ -299,12 +296,12 @@ class GraphCtrl extends MetricsPanelCtrl {
this.processor = new DataProcessor(this.panel); this.processor = new DataProcessor(this.panel);
await this._fetchHasticDatasources(); await this._fetchHasticDatasources();
const backendURL = this.getBackendURL(); const hasticDatasourceURL = this.getHasticDatasourceURL();
this.analyticService = new AnalyticService(backendURL, this.$http); this.analyticService = new AnalyticService(hasticDatasourceURL, this.$http);
this.runBackendConnectivityCheck(); this.runDatasourceConnectivityCheck();
this.analyticsController = new AnalyticController(this.panel, this.analyticService, this.events);
this.analyticsController = new AnalyticController(this.panel, this.analyticService, this.events);
this.analyticsController.fetchAnalyticUnitsStatuses(); this.analyticsController.fetchAnalyticUnitsStatuses();
this._graphRenderer = new GraphRenderer( this._graphRenderer = new GraphRenderer(
@ -645,8 +642,12 @@ class GraphCtrl extends MetricsPanelCtrl {
} }
private async _updatePanelInfo() { private async _updatePanelInfo() {
const datasource = await this._getDatasourceByName(this.panel.datasource); let datasource = undefined;
const backendUrl = this.getBackendURL(); if(this.panel.datasource) {
datasource = await this._getDatasourceByName(this.panel.datasource);
}
const backendUrl = this.getHasticDatasourceURL();
let grafanaVersion = 'unknown'; let grafanaVersion = 'unknown';
if(_.has(window, 'grafanaBootData.settings.buildInfo.version')) { if(_.has(window, 'grafanaBootData.settings.buildInfo.version')) {
@ -655,7 +656,7 @@ class GraphCtrl extends MetricsPanelCtrl {
this._panelInfo = { this._panelInfo = {
grafanaVersion, grafanaVersion,
grafanaUrl: window.location.host, grafanaUrl: window.location.host,
datasourceType: datasource.type, datasourceType: datasource === undefined ? 'unknown' : datasource.type,
hasticServerUrl: backendUrl hasticServerUrl: backendUrl
}; };
} }

46
src/panel/graph_panel/services/analytic_service.ts

@ -1,10 +1,11 @@
import { Segment, SegmentId } from '../models/segment'; import { SegmentId } from '../models/segment';
import { MetricExpanded } from '../models/metric'; import { MetricExpanded } from '../models/metric';
import { DatasourceRequest } from '../models/datasource'; import { DatasourceRequest } from '../models/datasource';
import { SegmentsSet } from '../models/segment_set'; import { SegmentsSet } from '../models/segment_set';
import { AnalyticUnitId, AnalyticUnit, AnalyticSegment } from '../models/analytic_unit'; import { AnalyticUnitId, AnalyticUnit, AnalyticSegment } from '../models/analytic_unit';
import { ServerInfo } from '../models/info'; import { ServerInfo } from '../models/info';
import { Threshold } from '../models/threshold'; import { Threshold } from '../models/threshold';
import { appEvents } from 'grafana/app/core/core'; import { appEvents } from 'grafana/app/core/core';
@ -12,12 +13,12 @@ export class AnalyticService {
private _isUp = false; private _isUp = false;
constructor( constructor(
private _backendURL: string, private _hasticDatasourceURL: string,
private $http private $http
) { } ) { }
async getAnalyticUnitTypes() { async getAnalyticUnitTypes() {
return await this.get('/analyticUnits/types'); return this.get('/analyticUnits/types');
} }
async getThresholds(ids: AnalyticUnitId[]) { async getThresholds(ids: AnalyticUnitId[]) {
@ -28,8 +29,8 @@ export class AnalyticService {
return resp.thresholds.filter(t => t !== null); return resp.thresholds.filter(t => t !== null);
} }
async updateThreshold(threshold: Threshold) { async updateThreshold(threshold: Threshold): Promise<void> {
return await this.patch('/threshold', threshold); return this.patch('/threshold', threshold);
} }
async postNewItem( async postNewItem(
@ -49,7 +50,11 @@ export class AnalyticService {
return response.id as AnalyticUnitId; return response.id as AnalyticUnitId;
} }
async updateMetric(analyticUnitId: AnalyticUnitId, metric: MetricExpanded, datasource: DatasourceRequest) { async updateMetric(
analyticUnitId: AnalyticUnitId,
metric: MetricExpanded,
datasource: DatasourceRequest
) {
await this.patch('/analyticUnits/metric', { await this.patch('/analyticUnits/metric', {
analyticUnitId, analyticUnitId,
metric: metric.toJSON(), metric: metric.toJSON(),
@ -61,8 +66,8 @@ export class AnalyticService {
return this.delete('/analyticUnits', { id }); return this.delete('/analyticUnits', { id });
} }
async isBackendOk(): Promise<boolean> { async isDatasourceOk(): Promise<boolean> {
if(!this._checkBackendUrl()) { if(!this._checkDatasourceConfig()) {
this._isUp = false; this._isUp = false;
return false; return false;
} }
@ -71,7 +76,9 @@ export class AnalyticService {
} }
async updateSegments( async updateSegments(
id: AnalyticUnitId, addedSegments: SegmentsSet<AnalyticSegment>, removedSegments: SegmentsSet<AnalyticSegment> id: AnalyticUnitId,
addedSegments: SegmentsSet<AnalyticSegment>,
removedSegments: SegmentsSet<AnalyticSegment>
): Promise<SegmentId[]> { ): Promise<SegmentId[]> {
const getJSONs = (segs: SegmentsSet<AnalyticSegment>) => segs.getSegments().map(segment => ({ const getJSONs = (segs: SegmentsSet<AnalyticSegment>) => segs.getSegments().map(segment => ({
from: segment.from, from: segment.from,
@ -184,7 +191,7 @@ export class AnalyticService {
private async _analyticRequest(method: string, url: string, data?: any) { private async _analyticRequest(method: string, url: string, data?: any) {
try { try {
method = method.toUpperCase(); method = method.toUpperCase();
url = this._backendURL + url; url = this._hasticDatasourceURL + url;
let requestObject: any = { method, url }; let requestObject: any = { method, url };
if(method === 'GET' || method === 'DELETE') { if(method === 'GET' || method === 'DELETE') {
requestObject.params = data; requestObject.params = data;
@ -196,7 +203,7 @@ export class AnalyticService {
return response.data; return response.data;
} catch(error) { } catch(error) {
if(error.xhrStatus === 'error') { if(error.xhrStatus === 'error') {
this.displayConnectionAlert(); this.displayConnectionErrorAlert();
this._isUp = false; this._isUp = false;
} else { } else {
this._isUp = true; this._isUp = true;
@ -205,14 +212,17 @@ export class AnalyticService {
} }
} }
get hasticDatasourceURL(): string {
return this._hasticDatasourceURL;
}
private _checkBackendUrl(): boolean { private _checkDatasourceConfig(): boolean {
if(this._backendURL === null || this._backendURL === undefined || this._backendURL === '') { if(this._hasticDatasourceURL === null || this._hasticDatasourceURL === undefined || this._hasticDatasourceURL === '') {
appEvents.emit( appEvents.emit(
'alert-warning', 'alert-warning',
[ [
`Datasource (or URL in datasource) is missing`, `Hastic Datasource is missing`,
`Please set it in datasource config. More info: https://github.com/hastic/hastic-grafana-app/wiki/Getting-started` `Please setup Hastic Datasource. More info: https://github.com/hastic/hastic-grafana-app/wiki/Getting-started`
] ]
); );
return false; return false;
@ -236,12 +246,12 @@ export class AnalyticService {
return this._analyticRequest('DELETE', url, data); return this._analyticRequest('DELETE', url, data);
} }
private displayConnectionAlert() { private displayConnectionErrorAlert() {
appEvents.emit( appEvents.emit(
'alert-error', 'alert-error',
[ [
'No connection to Hastic server', 'No connection to Hastic Datasource',
`Hastic server: "${this._backendURL}"`, `Hastic Datasource URL: "${this._hasticDatasourceURL}"`,
] ]
); );
} }

Loading…
Cancel
Save