datasource.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. import { stackdriverUnitMappings } from './constants';
  2. import appEvents from 'app/core/app_events';
  3. import _ from 'lodash';
  4. import StackdriverMetricFindQuery from './StackdriverMetricFindQuery';
  5. export default class StackdriverDatasource {
  6. id: number;
  7. url: string;
  8. baseUrl: string;
  9. projectName: string;
  10. authenticationType: string;
  11. queryPromise: Promise<any>;
  12. metricTypes: any[];
  13. /** @ngInject */
  14. constructor(instanceSettings, private backendSrv, private templateSrv, private timeSrv) {
  15. this.baseUrl = `/stackdriver/`;
  16. this.url = instanceSettings.url;
  17. this.id = instanceSettings.id;
  18. this.projectName = instanceSettings.jsonData.defaultProject || '';
  19. this.authenticationType = instanceSettings.jsonData.authenticationType || 'jwt';
  20. this.metricTypes = [];
  21. }
  22. async getTimeSeries(options) {
  23. const queries = options.targets
  24. .filter(target => {
  25. return !target.hide && target.metricType;
  26. })
  27. .map(t => {
  28. return {
  29. refId: t.refId,
  30. intervalMs: options.intervalMs,
  31. datasourceId: this.id,
  32. metricType: this.templateSrv.replace(t.metricType, options.scopedVars || {}),
  33. primaryAggregation: this.templateSrv.replace(t.crossSeriesReducer || 'REDUCE_MEAN', options.scopedVars || {}),
  34. perSeriesAligner: this.templateSrv.replace(t.perSeriesAligner, options.scopedVars || {}),
  35. alignmentPeriod: this.templateSrv.replace(t.alignmentPeriod, options.scopedVars || {}),
  36. groupBys: this.interpolateGroupBys(t.groupBys, options.scopedVars),
  37. view: t.view || 'FULL',
  38. filters: (t.filters || []).map(f => {
  39. return this.templateSrv.replace(f, options.scopedVars || {});
  40. }),
  41. aliasBy: this.templateSrv.replace(t.aliasBy, options.scopedVars || {}),
  42. type: 'timeSeriesQuery',
  43. };
  44. });
  45. if (queries.length > 0) {
  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. } else {
  57. return { results: [] };
  58. }
  59. }
  60. async getLabels(metricType, refId) {
  61. const response = await this.getTimeSeries({
  62. targets: [
  63. {
  64. refId: refId,
  65. datasourceId: this.id,
  66. metricType: this.templateSrv.replace(metricType),
  67. crossSeriesReducer: 'REDUCE_NONE',
  68. view: 'HEADERS',
  69. },
  70. ],
  71. range: this.timeSrv.timeRange(),
  72. });
  73. return response.results[refId];
  74. }
  75. interpolateGroupBys(groupBys: string[], scopedVars): string[] {
  76. let interpolatedGroupBys = [];
  77. (groupBys || []).forEach(gb => {
  78. const interpolated = this.templateSrv.replace(gb, scopedVars || {}, 'csv').split(',');
  79. if (Array.isArray(interpolated)) {
  80. interpolatedGroupBys = interpolatedGroupBys.concat(interpolated);
  81. } else {
  82. interpolatedGroupBys.push(interpolated);
  83. }
  84. });
  85. return interpolatedGroupBys;
  86. }
  87. resolvePanelUnitFromTargets(targets: any[]) {
  88. let unit;
  89. if (targets.length > 0 && targets.every(t => t.unit === targets[0].unit)) {
  90. if (stackdriverUnitMappings.hasOwnProperty(targets[0].unit)) {
  91. unit = stackdriverUnitMappings[targets[0].unit];
  92. }
  93. }
  94. return unit;
  95. }
  96. async query(options) {
  97. const result = [];
  98. const data = await this.getTimeSeries(options);
  99. if (data.results) {
  100. Object['values'](data.results).forEach(queryRes => {
  101. if (!queryRes.series) {
  102. return;
  103. }
  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. return { data: result };
  119. } else {
  120. return { data: [] };
  121. }
  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. async metricFindQuery(query) {
  163. const stackdriverMetricFindQuery = new StackdriverMetricFindQuery(this);
  164. return stackdriverMetricFindQuery.execute(query);
  165. }
  166. async testDatasource() {
  167. let status, message;
  168. const defaultErrorMessage = 'Cannot connect to Stackdriver API';
  169. try {
  170. const projectName = await this.getDefaultProject();
  171. const path = `v3/projects/${projectName}/metricDescriptors`;
  172. const response = await this.doRequest(`${this.baseUrl}${path}`);
  173. if (response.status === 200) {
  174. status = 'success';
  175. message = 'Successfully queried the Stackdriver API.';
  176. } else {
  177. status = 'error';
  178. message = response.statusText ? response.statusText : defaultErrorMessage;
  179. }
  180. } catch (error) {
  181. status = 'error';
  182. if (_.isString(error)) {
  183. message = error;
  184. } else {
  185. message = 'Stackdriver: ';
  186. message += error.statusText ? error.statusText : defaultErrorMessage;
  187. if (error.data && error.data.error && error.data.error.code) {
  188. message += ': ' + error.data.error.code + '. ' + error.data.error.message;
  189. }
  190. }
  191. } finally {
  192. return {
  193. status,
  194. message,
  195. };
  196. }
  197. }
  198. formatStackdriverError(error) {
  199. let message = 'Stackdriver: ';
  200. message += error.statusText ? error.statusText + ': ' : '';
  201. if (error.data && error.data.error) {
  202. try {
  203. const res = JSON.parse(error.data.error);
  204. message += res.error.code + '. ' + res.error.message;
  205. } catch (err) {
  206. message += error.data.error;
  207. }
  208. } else {
  209. message += 'Cannot connect to Stackdriver API';
  210. }
  211. return message;
  212. }
  213. async getDefaultProject() {
  214. try {
  215. if (this.authenticationType === 'gce' || !this.projectName) {
  216. const { data } = await this.backendSrv.datasourceRequest({
  217. url: '/api/tsdb/query',
  218. method: 'POST',
  219. data: {
  220. queries: [
  221. {
  222. refId: 'ensureDefaultProjectQuery',
  223. type: 'ensureDefaultProjectQuery',
  224. datasourceId: this.id,
  225. },
  226. ],
  227. },
  228. });
  229. this.projectName = data.results.ensureDefaultProjectQuery.meta.defaultProject;
  230. return this.projectName;
  231. } else {
  232. return this.projectName;
  233. }
  234. } catch (error) {
  235. throw this.formatStackdriverError(error);
  236. }
  237. }
  238. async getMetricTypes(projectName: string) {
  239. try {
  240. if (this.metricTypes.length === 0) {
  241. const metricsApiPath = `v3/projects/${projectName}/metricDescriptors`;
  242. const { data } = await this.doRequest(`${this.baseUrl}${metricsApiPath}`);
  243. this.metricTypes = data.metricDescriptors.map(m => {
  244. const [service] = m.type.split('/');
  245. const [serviceShortName] = service.split('.');
  246. m.service = service;
  247. m.serviceShortName = serviceShortName;
  248. m.displayName = m.displayName || m.type;
  249. return m;
  250. });
  251. }
  252. return this.metricTypes;
  253. } catch (error) {
  254. appEvents.emit('ds-request-error', this.formatStackdriverError(error));
  255. return [];
  256. }
  257. }
  258. async doRequest(url, maxRetries = 1) {
  259. return this.backendSrv
  260. .datasourceRequest({
  261. url: this.url + url,
  262. method: 'GET',
  263. })
  264. .catch(error => {
  265. if (maxRetries > 0) {
  266. return this.doRequest(url, maxRetries - 1);
  267. }
  268. throw error;
  269. });
  270. }
  271. }