datasource.ts 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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 = {
  104. target: series.name,
  105. datapoints: series.points,
  106. refId: queryRes.refId,
  107. meta: queryRes.meta,
  108. unit,
  109. };
  110. if (unit) {
  111. timeSerie = { ...timeSerie, unit };
  112. }
  113. result.push(timeSerie);
  114. });
  115. });
  116. }
  117. return { data: result };
  118. }
  119. async annotationQuery(options) {
  120. const annotation = options.annotation;
  121. const queries = [
  122. {
  123. refId: 'annotationQuery',
  124. datasourceId: this.id,
  125. metricType: this.templateSrv.replace(annotation.target.metricType, options.scopedVars || {}),
  126. primaryAggregation: 'REDUCE_NONE',
  127. perSeriesAligner: 'ALIGN_NONE',
  128. title: this.templateSrv.replace(annotation.target.title, options.scopedVars || {}),
  129. text: this.templateSrv.replace(annotation.target.text, options.scopedVars || {}),
  130. tags: this.templateSrv.replace(annotation.target.tags, options.scopedVars || {}),
  131. view: 'FULL',
  132. filters: (annotation.target.filters || []).map(f => {
  133. return this.templateSrv.replace(f, options.scopedVars || {});
  134. }),
  135. type: 'annotationQuery',
  136. },
  137. ];
  138. const { data } = await this.backendSrv.datasourceRequest({
  139. url: '/api/tsdb/query',
  140. method: 'POST',
  141. data: {
  142. from: options.range.from.valueOf().toString(),
  143. to: options.range.to.valueOf().toString(),
  144. queries,
  145. },
  146. });
  147. const results = data.results['annotationQuery'].tables[0].rows.map(v => {
  148. return {
  149. annotation: annotation,
  150. time: Date.parse(v[0]),
  151. title: v[1],
  152. tags: [],
  153. text: v[3],
  154. };
  155. });
  156. return results;
  157. }
  158. metricFindQuery(query) {
  159. throw new Error('Template variables support is not yet imlemented');
  160. }
  161. testDatasource() {
  162. const path = `v3/projects/${this.projectName}/metricDescriptors`;
  163. return this.doRequest(`${this.baseUrl}${path}`)
  164. .then(response => {
  165. if (response.status === 200) {
  166. return {
  167. status: 'success',
  168. message: 'Successfully queried the Stackdriver API.',
  169. title: 'Success',
  170. };
  171. }
  172. return {
  173. status: 'error',
  174. message: 'Returned http status code ' + response.status,
  175. };
  176. })
  177. .catch(error => {
  178. let message = 'Stackdriver: ';
  179. message += error.statusText ? error.statusText + ': ' : '';
  180. if (error.data && error.data.error && error.data.error.code) {
  181. // 400, 401
  182. message += error.data.error.code + '. ' + error.data.error.message;
  183. } else {
  184. message += 'Cannot connect to Stackdriver API';
  185. }
  186. return {
  187. status: 'error',
  188. message: message,
  189. };
  190. });
  191. }
  192. async getProjects() {
  193. const response = await this.doRequest(`/cloudresourcemanager/v1/projects`);
  194. return response.data.projects.map(p => ({ id: p.projectId, name: p.name }));
  195. }
  196. async getDefaultProject() {
  197. try {
  198. const projects = await this.getProjects();
  199. if (projects && projects.length > 0) {
  200. const test = projects.filter(p => p.id === this.projectName)[0];
  201. return test;
  202. } else {
  203. throw new Error('No projects found');
  204. }
  205. } catch (error) {
  206. let message = 'Projects cannot be fetched: ';
  207. message += error.statusText ? error.statusText + ': ' : '';
  208. if (error && error.data && error.data.error && error.data.error.message) {
  209. if (error.data.error.code === 403) {
  210. message += `
  211. A list of projects could not be fetched from the Google Cloud Resource Manager API.
  212. You might need to enable it first:
  213. https://console.developers.google.com/apis/library/cloudresourcemanager.googleapis.com`;
  214. } else {
  215. message += error.data.error.code + '. ' + error.data.error.message;
  216. }
  217. } else {
  218. message += 'Cannot connect to Stackdriver API';
  219. }
  220. appEvents.emit('ds-request-error', message);
  221. }
  222. }
  223. async getMetricTypes(projectId: string) {
  224. try {
  225. const metricsApiPath = `v3/projects/${projectId}/metricDescriptors`;
  226. const { data } = await this.doRequest(`${this.baseUrl}${metricsApiPath}`);
  227. const metrics = data.metricDescriptors.map(m => {
  228. const [service] = m.type.split('/');
  229. const [serviceShortName] = service.split('.');
  230. m.service = service;
  231. m.serviceShortName = serviceShortName;
  232. m.displayName = m.displayName || m.type;
  233. return m;
  234. });
  235. return metrics;
  236. } catch (error) {
  237. console.log(error);
  238. }
  239. }
  240. async doRequest(url, maxRetries = 1) {
  241. return this.backendSrv
  242. .datasourceRequest({
  243. url: this.url + url,
  244. method: 'GET',
  245. })
  246. .catch(error => {
  247. if (maxRetries > 0) {
  248. return this.doRequest(url, maxRetries - 1);
  249. }
  250. throw error;
  251. });
  252. }
  253. }