datasource.ts 8.4 KB

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