datasource.ts 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. /** @ngInject */
  2. export default class StackdriverDatasource {
  3. id: number;
  4. url: string;
  5. baseUrl: string;
  6. projectName: string;
  7. constructor(instanceSettings, private backendSrv, private templateSrv) {
  8. this.baseUrl = `/stackdriver/`;
  9. this.url = instanceSettings.url;
  10. this.doRequest = this.doRequest;
  11. this.id = instanceSettings.id;
  12. this.projectName = instanceSettings.jsonData.defaultProject || '';
  13. }
  14. async getTimeSeries(options) {
  15. const queries = options.targets
  16. .filter(target => {
  17. return !target.hide && target.metricType;
  18. })
  19. .map(t => {
  20. if (!t.hasOwnProperty('aggregation')) {
  21. t.aggregation = {
  22. crossSeriesReducer: 'REDUCE_MEAN',
  23. groupBys: [],
  24. };
  25. }
  26. return {
  27. refId: t.refId,
  28. datasourceId: this.id,
  29. metricType: this.templateSrv.replace(t.metricType, options.scopedVars || {}),
  30. primaryAggregation: this.templateSrv.replace(t.aggregation.crossSeriesReducer, options.scopedVars || {}),
  31. perSeriesAligner: this.templateSrv.replace(t.aggregation.perSeriesAligner, options.scopedVars || {}),
  32. alignmentPeriod: this.templateSrv.replace(t.aggregation.alignmentPeriod, options.scopedVars || {}),
  33. groupBys: this.interpolateGroupBys(t.aggregation.groupBys, options.scopedVars),
  34. view: t.view || 'FULL',
  35. filters: (t.filters || []).map(f => {
  36. return this.templateSrv.replace(f, options.scopedVars || {});
  37. }),
  38. aliasBy: this.templateSrv.replace(t.aliasBy, options.scopedVars || {}),
  39. };
  40. });
  41. const { data } = await this.backendSrv.datasourceRequest({
  42. url: '/api/tsdb/query',
  43. method: 'POST',
  44. data: {
  45. from: options.range.from.valueOf().toString(),
  46. to: options.range.to.valueOf().toString(),
  47. queries,
  48. },
  49. });
  50. return data;
  51. }
  52. interpolateGroupBys(groupBys: string[], scopedVars): string[] {
  53. let interpolatedGroupBys = [];
  54. (groupBys || []).forEach(gb => {
  55. const interpolated = this.templateSrv.replace(gb, scopedVars || {}, 'csv').split(',');
  56. if (Array.isArray(interpolated)) {
  57. interpolatedGroupBys = interpolatedGroupBys.concat(interpolated);
  58. } else {
  59. interpolatedGroupBys.push(interpolated);
  60. }
  61. });
  62. return interpolatedGroupBys;
  63. }
  64. async query(options) {
  65. const result = [];
  66. const data = await this.getTimeSeries(options);
  67. if (data.results) {
  68. Object['values'](data.results).forEach(queryRes => {
  69. if (!queryRes.series) {
  70. return;
  71. }
  72. queryRes.series.forEach(series => {
  73. result.push({
  74. target: series.name,
  75. datapoints: series.points,
  76. refId: queryRes.refId,
  77. meta: queryRes.meta,
  78. });
  79. });
  80. });
  81. }
  82. return { data: result };
  83. }
  84. testDatasource() {
  85. const path = `v3/projects/${this.projectName}/metricDescriptors`;
  86. return this.doRequest(`${this.baseUrl}${path}`)
  87. .then(response => {
  88. if (response.status === 200) {
  89. return {
  90. status: 'success',
  91. message: 'Successfully queried the Stackdriver API.',
  92. title: 'Success',
  93. };
  94. }
  95. return {
  96. status: 'error',
  97. message: 'Returned http status code ' + response.status,
  98. };
  99. })
  100. .catch(error => {
  101. let message = 'Stackdriver: ';
  102. message += error.statusText ? error.statusText + ': ' : '';
  103. if (error.data && error.data.error && error.data.error.code) {
  104. // 400, 401
  105. message += error.data.error.code + '. ' + error.data.error.message;
  106. } else {
  107. message += 'Cannot connect to Stackdriver API';
  108. }
  109. return {
  110. status: 'error',
  111. message: message,
  112. };
  113. });
  114. }
  115. async getProjects() {
  116. const response = await this.doRequest(`/cloudresourcemanager/v1/projects`);
  117. return response.data.projects.map(p => ({ id: p.projectId, name: p.name }));
  118. }
  119. async getMetricTypes(projectId: string) {
  120. try {
  121. const metricsApiPath = `v3/projects/${projectId}/metricDescriptors`;
  122. const { data } = await this.doRequest(`${this.baseUrl}${metricsApiPath}`);
  123. return data.metricDescriptors.map(m => ({ id: m.type, name: m.displayName }));
  124. } catch (error) {
  125. console.log(error);
  126. }
  127. }
  128. async doRequest(url, maxRetries = 1) {
  129. return this.backendSrv
  130. .datasourceRequest({
  131. url: this.url + url,
  132. method: 'GET',
  133. })
  134. .catch(error => {
  135. if (maxRetries > 0) {
  136. return this.doRequest(url, maxRetries - 1);
  137. }
  138. throw error;
  139. });
  140. }
  141. }