datasource.ts 5.8 KB

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