query_ctrl.ts 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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: { [key: string]: string[] };
  12. resourceLabels: { [key: string]: string[] };
  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)
  140. .filter(ml => {
  141. return this.target.aggregation.groupBys.indexOf('metric.label.' + ml) === -1;
  142. })
  143. .map(l => {
  144. return this.uiSegmentSrv.newSegment({
  145. value: `metric.label.${l}`,
  146. expandable: false,
  147. });
  148. });
  149. const resourceLabels = Object.keys(this.resourceLabels)
  150. .filter(ml => {
  151. return this.target.aggregation.groupBys.indexOf('resource.label.' + ml) === -1;
  152. })
  153. .map(l => {
  154. return this.uiSegmentSrv.newSegment({
  155. value: `resource.label.${l}`,
  156. expandable: false,
  157. });
  158. });
  159. return Promise.resolve([...metricLabels, ...resourceLabels]);
  160. }
  161. groupByChanged(segment) {
  162. segment.type = 'value';
  163. const reducer = (memo, seg) => {
  164. if (!seg.fake) {
  165. memo.push(seg.value);
  166. }
  167. return memo;
  168. };
  169. this.target.aggregation.groupBys = this.groupBySegments.reduce(reducer, []);
  170. this.ensurePlusButton(this.groupBySegments);
  171. this.refresh();
  172. }
  173. ensurePlusButton(segments) {
  174. const count = segments.length;
  175. const lastSegment = segments[Math.max(count - 1, 0)];
  176. if (!lastSegment || lastSegment.type !== 'plus-button') {
  177. segments.push(this.uiSegmentSrv.newPlusButton());
  178. }
  179. }
  180. onDataReceived(dataList) {
  181. this.lastQueryError = null;
  182. this.lastQueryMeta = null;
  183. const anySeriesFromQuery: any = _.find(dataList, { refId: this.target.refId });
  184. if (anySeriesFromQuery) {
  185. this.lastQueryMeta = anySeriesFromQuery.meta;
  186. this.lastQueryMeta.rawQueryString = decodeURIComponent(this.lastQueryMeta.rawQuery);
  187. }
  188. }
  189. onDataError(err) {
  190. if (err.data && err.data.results) {
  191. const queryRes = err.data.results[this.target.refId];
  192. if (queryRes) {
  193. this.lastQueryMeta = queryRes.meta;
  194. this.lastQueryMeta.rawQueryString = decodeURIComponent(this.lastQueryMeta.rawQuery);
  195. let jsonBody;
  196. try {
  197. jsonBody = JSON.parse(queryRes.error);
  198. } catch {
  199. this.lastQueryError = queryRes.error;
  200. }
  201. this.lastQueryError = jsonBody.error.message;
  202. }
  203. }
  204. }
  205. }