grafana/public/app/plugins/datasource/stackdriver/datasource.ts

101 lines
2.7 KiB
TypeScript
Raw Normal View History

2018-09-04 06:21:02 -05:00
/** @ngInject */
2018-09-05 07:14:34 -05:00
export default class StackdriverDatasource {
2018-09-09 15:55:12 -05:00
id: number;
2018-09-05 07:14:34 -05:00
url: string;
baseUrl: string;
constructor(instanceSettings, private backendSrv) {
2018-09-05 09:18:03 -05:00
this.baseUrl = `/stackdriver/`;
2018-09-05 07:14:34 -05:00
this.url = instanceSettings.url;
this.doRequest = this.doRequest;
2018-09-09 15:55:12 -05:00
this.id = instanceSettings.id;
2018-09-05 07:14:34 -05:00
}
2018-09-09 15:55:12 -05:00
async query(options) {
const queries = options.targets.filter(target => !target.hide).map(t => ({
queryType: 'raw',
refId: t.refId,
datasourceId: this.id,
metric: t.metricType,
}));
try {
const response = await this.backendSrv.datasourceRequest({
url: '/api/tsdb/query',
method: 'POST',
data: {
from: options.range.from.valueOf().toString(),
to: options.range.to.valueOf().toString(),
queries,
},
});
return response;
} catch (error) {
console.log(error);
}
}
2018-09-05 07:14:34 -05:00
testDatasource() {
2018-09-05 09:18:03 -05:00
const path = `v3/projects/raintank-production/metricDescriptors`;
2018-09-05 07:14:34 -05:00
return this.doRequest(`${this.baseUrl}${path}`)
.then(response => {
if (response.status === 200) {
return {
status: 'success',
message: 'Successfully queried the Stackdriver API.',
2018-09-05 07:14:34 -05:00
title: 'Success',
};
}
return {
status: 'error',
message: 'Returned http status code ' + response.status,
};
2018-09-05 07:14:34 -05:00
})
.catch(error => {
2018-09-05 09:18:03 -05:00
let message = 'Stackdriver: ';
2018-09-05 07:14:34 -05:00
message += error.statusText ? error.statusText + ': ' : '';
if (error.data && error.data.error && error.data.error.code) {
2018-09-05 09:18:03 -05:00
// 400, 401
2018-09-05 07:14:34 -05:00
message += error.data.error.code + '. ' + error.data.error.message;
} else {
2018-09-05 09:18:03 -05:00
message += 'Cannot connect to Stackdriver API';
2018-09-05 07:14:34 -05:00
}
return {
status: 'error',
message: message,
};
});
}
async getProjects() {
const response = await this.doRequest(`/cloudresourcemanager/v1/projects`);
return response.data.projects.map(p => ({ id: p.projectId, name: p.name }));
}
async getMetricTypes(projectId: string) {
try {
const metricsApiPath = `v3/projects/${projectId}/metricDescriptors`;
const { data } = await this.doRequest(`${this.baseUrl}${metricsApiPath}`);
return data.metricDescriptors.map(m => ({ id: m.name, name: m.displayName }));
} catch (error) {
console.log(error);
}
}
async doRequest(url, maxRetries = 1) {
2018-09-05 07:14:34 -05:00
return this.backendSrv
.datasourceRequest({
url: this.url + url,
method: 'GET',
})
.catch(error => {
if (maxRetries > 0) {
return this.doRequest(url, maxRetries - 1);
}
throw error;
});
}
2018-09-04 06:21:02 -05:00
}