datasource.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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. const unit = this.resolvePanelUnitFromTargets(options.targets);
  110. queryRes.series.forEach(series => {
  111. let timeSerie: any = {
  112. target: series.name,
  113. datapoints: series.points,
  114. refId: queryRes.refId,
  115. meta: queryRes.meta,
  116. };
  117. if (unit) {
  118. timeSerie = { ...timeSerie, unit };
  119. }
  120. result.push(timeSerie);
  121. });
  122. });
  123. return { data: result };
  124. } else {
  125. return { data: [] };
  126. }
  127. }
  128. async annotationQuery(options) {
  129. const annotation = options.annotation;
  130. const queries = [
  131. {
  132. refId: 'annotationQuery',
  133. datasourceId: this.id,
  134. metricType: this.templateSrv.replace(annotation.target.metricType, options.scopedVars || {}),
  135. primaryAggregation: 'REDUCE_NONE',
  136. perSeriesAligner: 'ALIGN_NONE',
  137. title: this.templateSrv.replace(annotation.target.title, options.scopedVars || {}),
  138. text: this.templateSrv.replace(annotation.target.text, options.scopedVars || {}),
  139. tags: this.templateSrv.replace(annotation.target.tags, options.scopedVars || {}),
  140. view: 'FULL',
  141. filters: (annotation.target.filters || []).map(f => {
  142. return this.templateSrv.replace(f, options.scopedVars || {});
  143. }),
  144. type: 'annotationQuery',
  145. },
  146. ];
  147. const { data } = await this.backendSrv.datasourceRequest({
  148. url: '/api/tsdb/query',
  149. method: 'POST',
  150. data: {
  151. from: options.range.from.valueOf().toString(),
  152. to: options.range.to.valueOf().toString(),
  153. queries,
  154. },
  155. });
  156. const results = data.results['annotationQuery'].tables[0].rows.map(v => {
  157. return {
  158. annotation: annotation,
  159. time: Date.parse(v[0]),
  160. title: v[1],
  161. tags: [],
  162. text: v[3],
  163. };
  164. });
  165. return results;
  166. }
  167. metricFindQuery(query) {
  168. throw new Error('Template variables support is not yet imlemented');
  169. }
  170. async testDatasource() {
  171. let status, message;
  172. const defaultErrorMessage = 'Cannot connect to Stackdriver API';
  173. try {
  174. const projectName = await this.getDefaultProject();
  175. const path = `v3/projects/${projectName}/metricDescriptors`;
  176. const response = await this.doRequest(`${this.baseUrl}${path}`);
  177. if (response.status === 200) {
  178. status = 'success';
  179. message = 'Successfully queried the Stackdriver API.';
  180. } else {
  181. status = 'error';
  182. message = response.statusText ? response.statusText : defaultErrorMessage;
  183. }
  184. } catch (error) {
  185. status = 'error';
  186. if (_.isString(error)) {
  187. message = error;
  188. } else {
  189. message = 'Stackdriver: ';
  190. message += error.statusText ? error.statusText : defaultErrorMessage;
  191. if (error.data && error.data.error && error.data.error.code) {
  192. message += ': ' + error.data.error.code + '. ' + error.data.error.message;
  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. }