datasource.ts 9.0 KB

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