datasource.ts 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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. type: 'timeSeriesQuery',
  40. };
  41. });
  42. const { data } = await this.backendSrv.datasourceRequest({
  43. url: '/api/tsdb/query',
  44. method: 'POST',
  45. data: {
  46. from: options.range.from.valueOf().toString(),
  47. to: options.range.to.valueOf().toString(),
  48. queries,
  49. },
  50. });
  51. return data;
  52. }
  53. interpolateGroupBys(groupBys: string[], scopedVars): string[] {
  54. let interpolatedGroupBys = [];
  55. (groupBys || []).forEach(gb => {
  56. const interpolated = this.templateSrv.replace(gb, scopedVars || {}, 'csv').split(',');
  57. if (Array.isArray(interpolated)) {
  58. interpolatedGroupBys = interpolatedGroupBys.concat(interpolated);
  59. } else {
  60. interpolatedGroupBys.push(interpolated);
  61. }
  62. });
  63. return interpolatedGroupBys;
  64. }
  65. async query(options) {
  66. const result = [];
  67. const data = await this.getTimeSeries(options);
  68. if (data.results) {
  69. Object['values'](data.results).forEach(queryRes => {
  70. if (!queryRes.series) {
  71. return;
  72. }
  73. queryRes.series.forEach(series => {
  74. result.push({
  75. target: series.name,
  76. datapoints: series.points,
  77. refId: queryRes.refId,
  78. meta: queryRes.meta,
  79. });
  80. });
  81. });
  82. }
  83. return { data: result };
  84. }
  85. testDatasource() {
  86. const path = `v3/projects/${this.projectName}/metricDescriptors`;
  87. return this.doRequest(`${this.baseUrl}${path}`)
  88. .then(response => {
  89. if (response.status === 200) {
  90. return {
  91. status: 'success',
  92. message: 'Successfully queried the Stackdriver API.',
  93. title: 'Success',
  94. };
  95. }
  96. return {
  97. status: 'error',
  98. message: 'Returned http status code ' + response.status,
  99. };
  100. })
  101. .catch(error => {
  102. let message = 'Stackdriver: ';
  103. message += error.statusText ? error.statusText + ': ' : '';
  104. if (error.data && error.data.error && error.data.error.code) {
  105. // 400, 401
  106. message += error.data.error.code + '. ' + error.data.error.message;
  107. } else {
  108. message += 'Cannot connect to Stackdriver API';
  109. }
  110. return {
  111. status: 'error',
  112. message: message,
  113. };
  114. });
  115. }
  116. async getProjects() {
  117. const response = await this.doRequest(`/cloudresourcemanager/v1/projects`);
  118. return response.data.projects.map(p => ({ id: p.projectId, name: p.name }));
  119. }
  120. async getDefaultProject() {
  121. const projects = await this.getProjects();
  122. if (projects && projects.length > 0) {
  123. const test = projects.filter(p => p.id === this.projectName)[0];
  124. return test;
  125. } else {
  126. throw new Error('No projects found');
  127. }
  128. }
  129. async getMetricTypes(projectId: string) {
  130. try {
  131. const metricsApiPath = `v3/projects/${projectId}/metricDescriptors`;
  132. const { data } = await this.doRequest(`${this.baseUrl}${metricsApiPath}`);
  133. return data.metricDescriptors.map(m => ({ id: m.type, name: m.displayName }));
  134. } catch (error) {
  135. console.log(error);
  136. }
  137. }
  138. async doRequest(url, maxRetries = 1) {
  139. return this.backendSrv
  140. .datasourceRequest({
  141. url: this.url + url,
  142. method: 'GET',
  143. })
  144. .catch(error => {
  145. if (maxRetries > 0) {
  146. return this.doRequest(url, maxRetries - 1);
  147. }
  148. throw error;
  149. });
  150. }
  151. }