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