datasource.ts 8.4 KB

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