datasource.ts 9.0 KB

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