query_ctrl.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import _ from 'lodash';
  2. import { QueryCtrl } from 'app/plugins/sdk';
  3. import appEvents from 'app/core/app_events';
  4. export class StackdriverQueryCtrl extends QueryCtrl {
  5. static templateUrl = 'partials/query.editor.html';
  6. target: {
  7. project: {
  8. id: string;
  9. name: string;
  10. };
  11. metricType: string;
  12. };
  13. defaultDropdownValue = 'select';
  14. /** @ngInject */
  15. constructor($scope, $injector) {
  16. super($scope, $injector);
  17. this.target = {
  18. project: {
  19. id: 'default',
  20. name: 'loading project...',
  21. },
  22. metricType: this.defaultDropdownValue,
  23. };
  24. this.getCurrentProject().then(this.getMetricTypes.bind(this));
  25. }
  26. async getCurrentProject() {
  27. try {
  28. const projects = await this.datasource.getProjects();
  29. if (projects && projects.length > 0) {
  30. this.target.project = this.target.project = projects[0];
  31. } else {
  32. throw new Error('No projects found');
  33. }
  34. } catch (error) {
  35. let message = 'Projects cannot be fetched: ';
  36. message += error.statusText ? error.statusText + ': ' : '';
  37. if (error && error.data && error.data.error && error.data.error.message) {
  38. if (error.data.error.code === 403) {
  39. message += `
  40. A list of projects could not be fetched from the Google Cloud Resource Manager API.
  41. You might need to enable it first:
  42. https://console.developers.google.com/apis/library/cloudresourcemanager.googleapis.com`;
  43. } else {
  44. message += error.data.error.code + '. ' + error.data.error.message;
  45. }
  46. } else {
  47. message += 'Cannot connect to Stackdriver API';
  48. }
  49. appEvents.emit('ds-request-error', message);
  50. }
  51. }
  52. async getMetricTypes() {
  53. //projects/raintank-production/metricDescriptors/agent.googleapis.com/agent/api_request_count
  54. if (this.target.project.id !== 'default') {
  55. const metricTypes = await this.datasource.getMetricTypes(this.target.project.id);
  56. if (this.target.metricType === this.defaultDropdownValue && metricTypes.length > 0) {
  57. this.$scope.$apply(() => (this.target.metricType = metricTypes[0].name));
  58. }
  59. return metricTypes.map(mt => ({ value: mt.id, text: mt.id }));
  60. } else {
  61. return [];
  62. }
  63. }
  64. }