datasource.ts 9.1 KB

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