query_ctrl.ts 2.1 KB

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