query_ctrl.ts 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. import _ from 'lodash';
  2. import { QueryCtrl } from 'app/plugins/sdk';
  3. import appEvents from 'app/core/app_events';
  4. export interface LabelType {
  5. key: string;
  6. value: string;
  7. }
  8. export interface QueryMeta {
  9. rawQuery: string;
  10. rawQueryString: string;
  11. metricLabels: LabelType[];
  12. resourceLabels: LabelType[];
  13. }
  14. export class StackdriverQueryCtrl extends QueryCtrl {
  15. static templateUrl = 'partials/query.editor.html';
  16. target: {
  17. project: {
  18. id: string;
  19. name: string;
  20. };
  21. metricType: string;
  22. refId: string;
  23. aggregation: {
  24. crossSeriesReducer: string;
  25. alignmentPeriod: string;
  26. perSeriesAligner: string;
  27. groupBys: string[];
  28. };
  29. };
  30. defaultDropdownValue = 'Select metric';
  31. defaults = {
  32. project: {
  33. id: 'default',
  34. name: 'loading project...',
  35. },
  36. metricType: this.defaultDropdownValue,
  37. aggregation: {
  38. crossSeriesReducer: 'REDUCE_MEAN',
  39. alignmentPeriod: '',
  40. perSeriesAligner: '',
  41. groupBys: [],
  42. },
  43. };
  44. groupBySegments: any[];
  45. aggOptions = [
  46. { text: 'none', value: 'REDUCE_NONE' },
  47. { text: 'mean', value: 'REDUCE_MEAN' },
  48. { text: 'min', value: 'REDUCE_MIN' },
  49. { text: 'max', value: 'REDUCE_MAX' },
  50. { text: 'sum', value: 'REDUCE_SUM' },
  51. { text: 'std. dev.', value: 'REDUCE_STDDEV' },
  52. { text: 'count', value: 'REDUCE_COUNT' },
  53. { text: '99th percentile', value: 'REDUCE_PERCENTILE_99' },
  54. { text: '95th percentile', value: 'REDUCE_PERCENTILE_95' },
  55. { text: '50th percentile', value: 'REDUCE_PERCENTILE_50' },
  56. { text: '5th percentile', value: 'REDUCE_PERCENTILE_05' },
  57. ];
  58. showHelp: boolean;
  59. showLastQuery: boolean;
  60. lastQueryMeta: QueryMeta;
  61. lastQueryError?: string;
  62. metricLabels: LabelType[];
  63. resourceLabels: LabelType[];
  64. /** @ngInject */
  65. constructor($scope, $injector, private uiSegmentSrv, private timeSrv) {
  66. super($scope, $injector);
  67. _.defaultsDeep(this.target, this.defaults);
  68. this.panelCtrl.events.on('data-received', this.onDataReceived.bind(this), $scope);
  69. this.panelCtrl.events.on('data-error', this.onDataError.bind(this), $scope);
  70. this.getCurrentProject()
  71. .then(this.getMetricTypes.bind(this))
  72. .then(this.getLabels.bind(this));
  73. this.groupBySegments = this.target.aggregation.groupBys.map(groupBy => {
  74. return uiSegmentSrv.getSegmentForValue(groupBy);
  75. });
  76. this.ensurePlusButton(this.groupBySegments);
  77. }
  78. async getCurrentProject() {
  79. try {
  80. const projects = await this.datasource.getProjects();
  81. if (projects && projects.length > 0) {
  82. this.target.project = projects[0];
  83. } else {
  84. throw new Error('No projects found');
  85. }
  86. } catch (error) {
  87. let message = 'Projects cannot be fetched: ';
  88. message += error.statusText ? error.statusText + ': ' : '';
  89. if (error && error.data && error.data.error && error.data.error.message) {
  90. if (error.data.error.code === 403) {
  91. message += `
  92. A list of projects could not be fetched from the Google Cloud Resource Manager API.
  93. You might need to enable it first:
  94. https://console.developers.google.com/apis/library/cloudresourcemanager.googleapis.com`;
  95. } else {
  96. message += error.data.error.code + '. ' + error.data.error.message;
  97. }
  98. } else {
  99. message += 'Cannot connect to Stackdriver API';
  100. }
  101. appEvents.emit('ds-request-error', message);
  102. }
  103. }
  104. async getMetricTypes() {
  105. //projects/raintank-production/metricDescriptors/agent.googleapis.com/agent/api_request_count
  106. if (this.target.project.id !== 'default') {
  107. const metricTypes = await this.datasource.getMetricTypes(this.target.project.id);
  108. if (this.target.metricType === this.defaultDropdownValue && metricTypes.length > 0) {
  109. this.$scope.$apply(() => (this.target.metricType = metricTypes[0].name));
  110. }
  111. return metricTypes.map(mt => ({ value: mt.id, text: mt.id }));
  112. } else {
  113. return [];
  114. }
  115. }
  116. async getLabels() {
  117. const data = await this.datasource.getTimeSeries({
  118. targets: [
  119. {
  120. refId: this.target.refId,
  121. datasourceId: this.datasource.id,
  122. metricType: this.target.metricType,
  123. aggregation: {
  124. crossSeriesReducer: 'REDUCE_NONE',
  125. },
  126. view: 'HEADERS',
  127. },
  128. ],
  129. range: this.timeSrv.timeRange(),
  130. });
  131. this.metricLabels = data.results[this.target.refId].meta.metricLabels;
  132. this.resourceLabels = data.results[this.target.refId].meta.resourceLabels;
  133. }
  134. async onMetricTypeChange() {
  135. this.refresh();
  136. this.getLabels();
  137. }
  138. getGroupBys() {
  139. const metricLabels = Object.keys(this.metricLabels).map(l => {
  140. return this.uiSegmentSrv.newSegment({
  141. value: `metric.label.${l}`,
  142. expandable: false,
  143. });
  144. });
  145. const resourceLabels = Object.keys(this.resourceLabels).map(l => {
  146. return this.uiSegmentSrv.newSegment({
  147. value: `resource.label.${l}`,
  148. expandable: false,
  149. });
  150. });
  151. return Promise.resolve([...metricLabels, ...resourceLabels]);
  152. }
  153. groupByChanged(segment, index) {
  154. this.target.aggregation.groupBys = _.reduce(
  155. this.groupBySegments,
  156. function(memo, seg) {
  157. if (!seg.fake) {
  158. memo.push(seg.value);
  159. }
  160. return memo;
  161. },
  162. []
  163. );
  164. this.ensurePlusButton(this.groupBySegments);
  165. this.refresh();
  166. }
  167. ensurePlusButton(segments) {
  168. const count = segments.length;
  169. const lastSegment = segments[Math.max(count - 1, 0)];
  170. if (!lastSegment || lastSegment.type !== 'plus-button') {
  171. segments.push(this.uiSegmentSrv.newPlusButton());
  172. }
  173. }
  174. onDataReceived(dataList) {
  175. this.lastQueryError = null;
  176. this.lastQueryMeta = null;
  177. const anySeriesFromQuery: any = _.find(dataList, { refId: this.target.refId });
  178. if (anySeriesFromQuery) {
  179. this.lastQueryMeta = anySeriesFromQuery.meta;
  180. this.lastQueryMeta.rawQueryString = decodeURIComponent(this.lastQueryMeta.rawQuery);
  181. }
  182. }
  183. onDataError(err) {
  184. if (err.data && err.data.results) {
  185. const queryRes = err.data.results[this.target.refId];
  186. if (queryRes) {
  187. this.lastQueryMeta = queryRes.meta;
  188. this.lastQueryMeta.rawQueryString = decodeURIComponent(this.lastQueryMeta.rawQuery);
  189. let jsonBody;
  190. try {
  191. jsonBody = JSON.parse(queryRes.error);
  192. } catch {
  193. this.lastQueryError = queryRes.error;
  194. }
  195. this.lastQueryError = jsonBody.error.message;
  196. }
  197. }
  198. }
  199. }