query_ctrl.ts 2.3 KB

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