datasource.ts 5.3 KB

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