datasource.ts 5.4 KB

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