datasource.ts 9.3 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.query(query);
  174. // throw new Error('Template variables support is not yet imlemented');
  175. }
  176. async testDatasource() {
  177. let status, message;
  178. const defaultErrorMessage = 'Cannot connect to Stackdriver API';
  179. try {
  180. const projectName = await this.getDefaultProject();
  181. const path = `v3/projects/${projectName}/metricDescriptors`;
  182. const response = await this.doRequest(`${this.baseUrl}${path}`);
  183. if (response.status === 200) {
  184. status = 'success';
  185. message = 'Successfully queried the Stackdriver API.';
  186. } else {
  187. status = 'error';
  188. message = response.statusText ? response.statusText : defaultErrorMessage;
  189. }
  190. } catch (error) {
  191. status = 'error';
  192. if (_.isString(error)) {
  193. message = error;
  194. } else {
  195. message = 'Stackdriver: ';
  196. message += error.statusText ? error.statusText : defaultErrorMessage;
  197. if (error.data && error.data.error && error.data.error.code) {
  198. message += ': ' + error.data.error.code + '. ' + error.data.error.message;
  199. }
  200. }
  201. } finally {
  202. return {
  203. status,
  204. message,
  205. };
  206. }
  207. }
  208. formatStackdriverError(error) {
  209. let message = 'Stackdriver: ';
  210. message += error.statusText ? error.statusText + ': ' : '';
  211. if (error.data && error.data.error) {
  212. try {
  213. const res = JSON.parse(error.data.error);
  214. message += res.error.code + '. ' + res.error.message;
  215. } catch (err) {
  216. message += error.data.error;
  217. }
  218. } else {
  219. message += 'Cannot connect to Stackdriver API';
  220. }
  221. return message;
  222. }
  223. async getDefaultProject() {
  224. try {
  225. if (this.authenticationType === 'gce' || !this.projectName) {
  226. const { data } = await this.backendSrv.datasourceRequest({
  227. url: '/api/tsdb/query',
  228. method: 'POST',
  229. data: {
  230. queries: [
  231. {
  232. refId: 'ensureDefaultProjectQuery',
  233. type: 'ensureDefaultProjectQuery',
  234. datasourceId: this.id,
  235. },
  236. ],
  237. },
  238. });
  239. this.projectName = data.results.ensureDefaultProjectQuery.meta.defaultProject;
  240. return this.projectName;
  241. } else {
  242. return this.projectName;
  243. }
  244. } catch (error) {
  245. throw this.formatStackdriverError(error);
  246. }
  247. }
  248. async getMetricTypes(projectName: string) {
  249. try {
  250. if (this.metricTypes.length === 0) {
  251. const metricsApiPath = `v3/projects/${projectName}/metricDescriptors`;
  252. const { data } = await this.doRequest(`${this.baseUrl}${metricsApiPath}`);
  253. this.metricTypes = data.metricDescriptors.map(m => {
  254. const [service] = m.type.split('/');
  255. const [serviceShortName] = service.split('.');
  256. m.service = service;
  257. m.serviceShortName = serviceShortName;
  258. m.displayName = m.displayName || m.type;
  259. return m;
  260. });
  261. }
  262. return this.metricTypes;
  263. } catch (error) {
  264. appEvents.emit('ds-request-error', this.formatStackdriverError(error));
  265. return [];
  266. }
  267. }
  268. async doRequest(url, maxRetries = 1) {
  269. return this.backendSrv
  270. .datasourceRequest({
  271. url: this.url + url,
  272. method: 'GET',
  273. })
  274. .catch(error => {
  275. if (maxRetries > 0) {
  276. return this.doRequest(url, maxRetries - 1);
  277. }
  278. throw error;
  279. });
  280. }
  281. }