datasource.ts 9.1 KB

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