datasource.ts 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /** @ngInject */
  2. export default class StackdriverDatasource {
  3. id: number;
  4. url: string;
  5. baseUrl: string;
  6. constructor(instanceSettings, private backendSrv) {
  7. this.baseUrl = `/stackdriver/`;
  8. this.url = instanceSettings.url;
  9. this.doRequest = this.doRequest;
  10. this.id = instanceSettings.id;
  11. }
  12. async query(options) {
  13. const queries = options.targets.filter(target => !target.hide).map(t => ({
  14. queryType: 'raw',
  15. refId: t.refId,
  16. datasourceId: this.id,
  17. metric: t.metricType,
  18. }));
  19. try {
  20. const response = await this.backendSrv.datasourceRequest({
  21. url: '/api/tsdb/query',
  22. method: 'POST',
  23. data: {
  24. from: options.range.from.valueOf().toString(),
  25. to: options.range.to.valueOf().toString(),
  26. queries,
  27. },
  28. });
  29. return response;
  30. } catch (error) {
  31. console.log(error);
  32. }
  33. }
  34. testDatasource() {
  35. const path = `v3/projects/raintank-production/metricDescriptors`;
  36. return this.doRequest(`${this.baseUrl}${path}`)
  37. .then(response => {
  38. if (response.status === 200) {
  39. return {
  40. status: 'success',
  41. message: 'Successfully queried the Stackdriver API.',
  42. title: 'Success',
  43. };
  44. }
  45. return {
  46. status: 'error',
  47. message: 'Returned http status code ' + response.status,
  48. };
  49. })
  50. .catch(error => {
  51. let message = 'Stackdriver: ';
  52. message += error.statusText ? error.statusText + ': ' : '';
  53. if (error.data && error.data.error && error.data.error.code) {
  54. // 400, 401
  55. message += error.data.error.code + '. ' + error.data.error.message;
  56. } else {
  57. message += 'Cannot connect to Stackdriver API';
  58. }
  59. return {
  60. status: 'error',
  61. message: message,
  62. };
  63. });
  64. }
  65. async getProjects() {
  66. const response = await this.doRequest(`/cloudresourcemanager/v1/projects`);
  67. return response.data.projects.map(p => ({ id: p.projectId, name: p.name }));
  68. }
  69. async getMetricTypes(projectId: string) {
  70. try {
  71. const metricsApiPath = `v3/projects/${projectId}/metricDescriptors`;
  72. const { data } = await this.doRequest(`${this.baseUrl}${metricsApiPath}`);
  73. return data.metricDescriptors.map(m => ({ id: m.name, name: m.displayName }));
  74. } catch (error) {
  75. console.log(error);
  76. }
  77. }
  78. async doRequest(url, maxRetries = 1) {
  79. return this.backendSrv
  80. .datasourceRequest({
  81. url: this.url + url,
  82. method: 'GET',
  83. })
  84. .catch(error => {
  85. if (maxRetries > 0) {
  86. return this.doRequest(url, maxRetries - 1);
  87. }
  88. throw error;
  89. });
  90. }
  91. }