datasource.ts 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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. return {
  187. status: 'error',
  188. message: this.formatStackdriverError(error),
  189. };
  190. }
  191. }
  192. formatStackdriverError(error) {
  193. let message = 'Stackdriver: ';
  194. message += error.statusText ? error.statusText + ': ' : '';
  195. if (error.data && error.data.error) {
  196. try {
  197. const res = JSON.parse(error.data.error);
  198. message += res.error.code + '. ' + res.error.message;
  199. } catch (err) {
  200. message += error.data.error;
  201. }
  202. } else {
  203. message += 'Cannot connect to Stackdriver API';
  204. }
  205. return message;
  206. }
  207. async getDefaultProject() {
  208. try {
  209. if (!this.projectName) {
  210. const { data } = await this.backendSrv.datasourceRequest({
  211. url: '/api/tsdb/query',
  212. method: 'POST',
  213. data: {
  214. queries: [
  215. {
  216. refId: 'defaultProject',
  217. type: 'defaultProject',
  218. datasourceId: this.id,
  219. },
  220. ],
  221. },
  222. });
  223. this.projectName = data.results.defaultProject.meta.defaultProject;
  224. return this.projectName;
  225. } else {
  226. return this.projectName;
  227. }
  228. } catch (error) {
  229. appEvents.emit('ds-request-error', this.formatStackdriverError(error));
  230. return '';
  231. }
  232. }
  233. async getMetricTypes(projectName: string) {
  234. try {
  235. const metricsApiPath = `v3/projects/${projectName}/metricDescriptors`;
  236. const { data } = await this.doRequest(`${this.baseUrl}${metricsApiPath}`);
  237. const metrics = data.metricDescriptors.map(m => {
  238. const [service] = m.type.split('/');
  239. const [serviceShortName] = service.split('.');
  240. m.service = service;
  241. m.serviceShortName = serviceShortName;
  242. m.displayName = m.displayName || m.type;
  243. return m;
  244. });
  245. return metrics;
  246. } catch (error) {
  247. appEvents.emit('ds-request-error', this.formatStackdriverError(error));
  248. return [];
  249. }
  250. }
  251. async doRequest(url, maxRetries = 1) {
  252. return this.backendSrv
  253. .datasourceRequest({
  254. url: this.url + url,
  255. method: 'GET',
  256. })
  257. .catch(error => {
  258. if (maxRetries > 0) {
  259. return this.doRequest(url, maxRetries - 1);
  260. }
  261. throw error;
  262. });
  263. }
  264. }