datasource.ts 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. import { stackdriverUnitMappings } from './constants';
  2. import appEvents from 'app/core/app_events';
  3. export default class StackdriverDatasource {
  4. id: number;
  5. url: string;
  6. baseUrl: string;
  7. projectName: string;
  8. /** @ngInject */
  9. constructor(instanceSettings, private backendSrv, private templateSrv, private timeSrv) {
  10. this.baseUrl = `/stackdriver/`;
  11. this.url = instanceSettings.url;
  12. this.doRequest = this.doRequest;
  13. this.id = instanceSettings.id;
  14. this.projectName = instanceSettings.jsonData.defaultProject || '';
  15. }
  16. async getTimeSeries(options) {
  17. const queries = options.targets
  18. .filter(target => {
  19. return !target.hide && target.metricType;
  20. })
  21. .map(t => {
  22. if (!t.hasOwnProperty('aggregation')) {
  23. t.aggregation = {
  24. crossSeriesReducer: 'REDUCE_MEAN',
  25. groupBys: [],
  26. };
  27. }
  28. return {
  29. refId: t.refId,
  30. intervalMs: options.intervalMs,
  31. datasourceId: this.id,
  32. metricType: this.templateSrv.replace(t.metricType, options.scopedVars || {}),
  33. primaryAggregation: this.templateSrv.replace(t.aggregation.crossSeriesReducer, options.scopedVars || {}),
  34. perSeriesAligner: this.templateSrv.replace(t.aggregation.perSeriesAligner, options.scopedVars || {}),
  35. alignmentPeriod: this.templateSrv.replace(t.aggregation.alignmentPeriod, options.scopedVars || {}),
  36. groupBys: this.interpolateGroupBys(t.aggregation.groupBys, options.scopedVars),
  37. view: t.view || 'FULL',
  38. filters: (t.filters || []).map(f => {
  39. return this.templateSrv.replace(f, options.scopedVars || {});
  40. }),
  41. aliasBy: this.templateSrv.replace(t.aliasBy, options.scopedVars || {}),
  42. type: 'timeSeriesQuery',
  43. };
  44. });
  45. const { data } = await this.backendSrv.datasourceRequest({
  46. url: '/api/tsdb/query',
  47. method: 'POST',
  48. data: {
  49. from: options.range.from.valueOf().toString(),
  50. to: options.range.to.valueOf().toString(),
  51. queries,
  52. },
  53. });
  54. return data;
  55. }
  56. async getLabels(metricType, refId) {
  57. return await this.getTimeSeries({
  58. targets: [
  59. {
  60. refId: refId,
  61. datasourceId: this.id,
  62. metricType: this.templateSrv.replace(metricType),
  63. aggregation: {
  64. crossSeriesReducer: 'REDUCE_NONE',
  65. },
  66. view: 'HEADERS',
  67. },
  68. ],
  69. range: this.timeSrv.timeRange(),
  70. });
  71. }
  72. interpolateGroupBys(groupBys: string[], scopedVars): string[] {
  73. let interpolatedGroupBys = [];
  74. (groupBys || []).forEach(gb => {
  75. const interpolated = this.templateSrv.replace(gb, scopedVars || {}, 'csv').split(',');
  76. if (Array.isArray(interpolated)) {
  77. interpolatedGroupBys = interpolatedGroupBys.concat(interpolated);
  78. } else {
  79. interpolatedGroupBys.push(interpolated);
  80. }
  81. });
  82. return interpolatedGroupBys;
  83. }
  84. resolvePanelUnitFromTargets(targets: any[]) {
  85. let unit;
  86. if (targets.length > 0 && targets.every(t => t.unit === targets[0].unit)) {
  87. if (stackdriverUnitMappings.hasOwnProperty(targets[0].unit)) {
  88. unit = stackdriverUnitMappings[targets[0].unit];
  89. }
  90. }
  91. return unit;
  92. }
  93. async query(options) {
  94. const result = [];
  95. const data = await this.getTimeSeries(options);
  96. if (data.results) {
  97. Object['values'](data.results).forEach(queryRes => {
  98. if (!queryRes.series) {
  99. return;
  100. }
  101. const unit = this.resolvePanelUnitFromTargets(options.targets);
  102. queryRes.series.forEach(series => {
  103. let timeSerie: any = {
  104. target: series.name,
  105. datapoints: series.points,
  106. refId: queryRes.refId,
  107. meta: queryRes.meta,
  108. };
  109. if (unit) {
  110. timeSerie = { ...timeSerie, unit };
  111. }
  112. result.push(timeSerie);
  113. });
  114. });
  115. }
  116. return { data: result };
  117. }
  118. async annotationQuery(options) {
  119. const annotation = options.annotation;
  120. const queries = [
  121. {
  122. refId: 'annotationQuery',
  123. datasourceId: this.id,
  124. metricType: this.templateSrv.replace(annotation.target.metricType, options.scopedVars || {}),
  125. primaryAggregation: 'REDUCE_NONE',
  126. perSeriesAligner: 'ALIGN_NONE',
  127. title: this.templateSrv.replace(annotation.target.title, options.scopedVars || {}),
  128. text: this.templateSrv.replace(annotation.target.text, options.scopedVars || {}),
  129. tags: this.templateSrv.replace(annotation.target.tags, options.scopedVars || {}),
  130. view: 'FULL',
  131. filters: (annotation.target.filters || []).map(f => {
  132. return this.templateSrv.replace(f, options.scopedVars || {});
  133. }),
  134. type: 'annotationQuery',
  135. },
  136. ];
  137. const { data } = await this.backendSrv.datasourceRequest({
  138. url: '/api/tsdb/query',
  139. method: 'POST',
  140. data: {
  141. from: options.range.from.valueOf().toString(),
  142. to: options.range.to.valueOf().toString(),
  143. queries,
  144. },
  145. });
  146. const results = data.results['annotationQuery'].tables[0].rows.map(v => {
  147. return {
  148. annotation: annotation,
  149. time: Date.parse(v[0]),
  150. title: v[1],
  151. tags: [],
  152. text: v[3],
  153. };
  154. });
  155. return results;
  156. }
  157. metricFindQuery(query) {
  158. throw new Error('Template variables support is not yet imlemented');
  159. }
  160. testDatasource() {
  161. const path = `v3/projects/${this.projectName}/metricDescriptors`;
  162. return this.doRequest(`${this.baseUrl}${path}`)
  163. .then(response => {
  164. if (response.status === 200) {
  165. return {
  166. status: 'success',
  167. message: 'Successfully queried the Stackdriver API.',
  168. title: 'Success',
  169. };
  170. }
  171. return {
  172. status: 'error',
  173. message: 'Returned http status code ' + response.status,
  174. };
  175. })
  176. .catch(error => {
  177. let message = 'Stackdriver: ';
  178. message += error.statusText ? error.statusText + ': ' : '';
  179. if (error.data && error.data.error && error.data.error.code) {
  180. // 400, 401
  181. message += error.data.error.code + '. ' + error.data.error.message;
  182. } else {
  183. message += 'Cannot connect to Stackdriver API';
  184. }
  185. return {
  186. status: 'error',
  187. message: message,
  188. };
  189. });
  190. }
  191. async getProjects() {
  192. const response = await this.doRequest(`/cloudresourcemanager/v1/projects`);
  193. return response.data.projects.map(p => ({ id: p.projectId, name: p.name }));
  194. }
  195. async getDefaultProject() {
  196. try {
  197. const projects = await this.getProjects();
  198. if (projects && projects.length > 0) {
  199. const test = projects.filter(p => p.id === this.projectName)[0];
  200. return test;
  201. } else {
  202. throw new Error('No projects found');
  203. }
  204. } catch (error) {
  205. let message = 'Projects cannot be fetched: ';
  206. message += error.statusText ? error.statusText + ': ' : '';
  207. if (error && error.data && error.data.error && error.data.error.message) {
  208. if (error.data.error.code === 403) {
  209. message += `
  210. A list of projects could not be fetched from the Google Cloud Resource Manager API.
  211. You might need to enable it first:
  212. https://console.developers.google.com/apis/library/cloudresourcemanager.googleapis.com`;
  213. } else {
  214. message += error.data.error.code + '. ' + error.data.error.message;
  215. }
  216. } else {
  217. message += 'Cannot connect to Stackdriver API';
  218. }
  219. appEvents.emit('ds-request-error', message);
  220. }
  221. }
  222. async getMetricTypes(projectId: string) {
  223. try {
  224. const metricsApiPath = `v3/projects/${projectId}/metricDescriptors`;
  225. const { data } = await this.doRequest(`${this.baseUrl}${metricsApiPath}`);
  226. const metrics = data.metricDescriptors.map(m => {
  227. const [service] = m.type.split('/');
  228. const [serviceShortName] = service.split('.');
  229. m.service = service;
  230. m.serviceShortName = serviceShortName;
  231. m.displayName = m.displayName || m.type;
  232. return m;
  233. });
  234. return metrics;
  235. } catch (error) {
  236. console.log(error);
  237. }
  238. }
  239. async doRequest(url, maxRetries = 1) {
  240. return this.backendSrv
  241. .datasourceRequest({
  242. url: this.url + url,
  243. method: 'GET',
  244. })
  245. .catch(error => {
  246. if (maxRetries > 0) {
  247. return this.doRequest(url, maxRetries - 1);
  248. }
  249. throw error;
  250. });
  251. }
  252. }