datasource.ts 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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. async testDatasource() {
  161. try {
  162. await this.backendSrv.datasourceRequest({
  163. url: '/api/tsdb/query',
  164. method: 'POST',
  165. data: {
  166. queries: [
  167. {
  168. refId: 'metricDescriptors',
  169. datasourceId: this.id,
  170. type: 'metricDescriptors',
  171. },
  172. ],
  173. },
  174. });
  175. return {
  176. status: 'success',
  177. message: 'Successfully queried the Stackdriver API.',
  178. title: 'Success',
  179. };
  180. } catch (error) {
  181. console.log(error.data.error);
  182. let message = 'Stackdriver: ';
  183. message += error.statusText ? error.statusText + ': ' : '';
  184. if (error.data && error.data.error && error.data.error) {
  185. try {
  186. const res = JSON.parse(error.data.error);
  187. message += res.error.code + '. ' + res.error.message;
  188. } catch (err) {
  189. message += error.data.error;
  190. }
  191. } else {
  192. message += 'Cannot connect to Stackdriver API';
  193. }
  194. return {
  195. status: 'error',
  196. message: message,
  197. };
  198. }
  199. }
  200. async getProjects() {
  201. const response = await this.doRequest(`/cloudresourcemanager/v1/projects`);
  202. return response.data.projects.map(p => ({ id: p.projectId, name: p.name }));
  203. }
  204. async getDefaultProject() {
  205. try {
  206. const projects = await this.getProjects();
  207. if (projects && projects.length > 0) {
  208. const test = projects.filter(p => p.id === this.projectName)[0];
  209. return test;
  210. } else {
  211. throw new Error('No projects found');
  212. }
  213. } catch (error) {
  214. let message = 'Projects cannot be fetched: ';
  215. message += error.statusText ? error.statusText + ': ' : '';
  216. if (error && error.data && error.data.error && error.data.error.message) {
  217. if (error.data.error.code === 403) {
  218. message += `
  219. A list of projects could not be fetched from the Google Cloud Resource Manager API.
  220. You might need to enable it first:
  221. https://console.developers.google.com/apis/library/cloudresourcemanager.googleapis.com`;
  222. } else {
  223. message += error.data.error.code + '. ' + error.data.error.message;
  224. }
  225. } else {
  226. message += 'Cannot connect to Stackdriver API';
  227. }
  228. appEvents.emit('ds-request-error', message);
  229. }
  230. }
  231. async getMetricTypes(projectId: string) {
  232. try {
  233. const metricsApiPath = `v3/projects/${projectId}/metricDescriptors`;
  234. const { data } = await this.doRequest(`${this.baseUrl}${metricsApiPath}`);
  235. const metrics = data.metricDescriptors.map(m => {
  236. const [service] = m.type.split('/');
  237. const [serviceShortName] = service.split('.');
  238. m.service = service;
  239. m.serviceShortName = serviceShortName;
  240. m.displayName = m.displayName || m.type;
  241. return m;
  242. });
  243. return metrics;
  244. } catch (error) {
  245. console.log(error);
  246. }
  247. }
  248. async doRequest(url, maxRetries = 1) {
  249. return this.backendSrv
  250. .datasourceRequest({
  251. url: this.url + url,
  252. method: 'GET',
  253. })
  254. .catch(error => {
  255. if (maxRetries > 0) {
  256. return this.doRequest(url, maxRetries - 1);
  257. }
  258. throw error;
  259. });
  260. }
  261. }