datasource.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /** @ngInject */
  2. export default class StackdriverDatasource {
  3. url: string;
  4. baseUrl: string;
  5. constructor(instanceSettings, private backendSrv) {
  6. this.baseUrl = `/stackdriver/`;
  7. this.url = instanceSettings.url;
  8. this.doRequest = this.doRequest;
  9. }
  10. query() {
  11. return Promise.resolve();
  12. }
  13. testDatasource() {
  14. const path = `v3/projects/raintank-production/metricDescriptors`;
  15. return this.doRequest(`${this.baseUrl}${path}`)
  16. .then(response => {
  17. if (response.status === 200) {
  18. return {
  19. status: 'success',
  20. message: 'Successfully queried the Stackdriver API.',
  21. title: 'Success',
  22. };
  23. }
  24. return {
  25. status: 'error',
  26. message: 'Returned http status code ' + response.status,
  27. };
  28. })
  29. .catch(error => {
  30. let message = 'Stackdriver: ';
  31. message += error.statusText ? error.statusText + ': ' : '';
  32. if (error.data && error.data.error && error.data.error.code) {
  33. // 400, 401
  34. message += error.data.error.code + '. ' + error.data.error.message;
  35. } else {
  36. message += 'Cannot connect to Stackdriver API';
  37. }
  38. return {
  39. status: 'error',
  40. message: message,
  41. };
  42. });
  43. }
  44. async getProjects() {
  45. const response = await this.doRequest(`/cloudresourcemanager/v1/projects`);
  46. return response.data.projects.map(p => ({ id: p.projectId, name: p.name }));
  47. }
  48. async getMetricTypes(projectId: string) {
  49. try {
  50. const metricsApiPath = `v3/projects/${projectId}/metricDescriptors`;
  51. const { data } = await this.doRequest(`${this.baseUrl}${metricsApiPath}`);
  52. return data.metricDescriptors.map(m => ({ id: m.name, name: m.displayName }));
  53. } catch (error) {
  54. console.log(error);
  55. }
  56. }
  57. async doRequest(url, maxRetries = 1) {
  58. return this.backendSrv
  59. .datasourceRequest({
  60. url: this.url + url,
  61. method: 'GET',
  62. })
  63. .catch(error => {
  64. if (maxRetries > 0) {
  65. return this.doRequest(url, maxRetries - 1);
  66. }
  67. throw error;
  68. });
  69. }
  70. }