datasource.ts 8.9 KB

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