datasource.ts 9.2 KB

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