query_ctrl.ts 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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. removeSegment: any;
  65. /** @ngInject */
  66. constructor($scope, $injector, private uiSegmentSrv, private timeSrv) {
  67. super($scope, $injector);
  68. _.defaultsDeep(this.target, this.defaults);
  69. this.panelCtrl.events.on('data-received', this.onDataReceived.bind(this), $scope);
  70. this.panelCtrl.events.on('data-error', this.onDataError.bind(this), $scope);
  71. this.getCurrentProject()
  72. .then(this.getMetricTypes.bind(this))
  73. .then(this.getLabels.bind(this));
  74. this.groupBySegments = this.target.aggregation.groupBys.map(groupBy => {
  75. return uiSegmentSrv.getSegmentForValue(groupBy);
  76. });
  77. this.removeSegment = uiSegmentSrv.newSegment({ fake: true, value: '-- remove group by --' });
  78. this.ensurePlusButton(this.groupBySegments);
  79. }
  80. async getCurrentProject() {
  81. try {
  82. const projects = await this.datasource.getProjects();
  83. if (projects && projects.length > 0) {
  84. this.target.project = projects[0];
  85. } else {
  86. throw new Error('No projects found');
  87. }
  88. } catch (error) {
  89. let message = 'Projects cannot be fetched: ';
  90. message += error.statusText ? error.statusText + ': ' : '';
  91. if (error && error.data && error.data.error && error.data.error.message) {
  92. if (error.data.error.code === 403) {
  93. message += `
  94. A list of projects could not be fetched from the Google Cloud Resource Manager API.
  95. You might need to enable it first:
  96. https://console.developers.google.com/apis/library/cloudresourcemanager.googleapis.com`;
  97. } else {
  98. message += error.data.error.code + '. ' + error.data.error.message;
  99. }
  100. } else {
  101. message += 'Cannot connect to Stackdriver API';
  102. }
  103. appEvents.emit('ds-request-error', message);
  104. }
  105. }
  106. async getMetricTypes() {
  107. //projects/raintank-production/metricDescriptors/agent.googleapis.com/agent/api_request_count
  108. if (this.target.project.id !== 'default') {
  109. const metricTypes = await this.datasource.getMetricTypes(this.target.project.id);
  110. if (this.target.metricType === this.defaultDropdownValue && metricTypes.length > 0) {
  111. this.$scope.$apply(() => (this.target.metricType = metricTypes[0].name));
  112. }
  113. return metricTypes.map(mt => ({ value: mt.id, text: mt.id }));
  114. } else {
  115. return [];
  116. }
  117. }
  118. async getLabels() {
  119. const data = await this.datasource.getTimeSeries({
  120. targets: [
  121. {
  122. refId: this.target.refId,
  123. datasourceId: this.datasource.id,
  124. metricType: this.target.metricType,
  125. aggregation: {
  126. crossSeriesReducer: 'REDUCE_NONE',
  127. },
  128. view: 'HEADERS',
  129. },
  130. ],
  131. range: this.timeSrv.timeRange(),
  132. });
  133. this.metricLabels = data.results[this.target.refId].meta.metricLabels;
  134. this.resourceLabels = data.results[this.target.refId].meta.resourceLabels;
  135. }
  136. async onMetricTypeChange() {
  137. this.refresh();
  138. this.getLabels();
  139. }
  140. getGroupBys() {
  141. const metricLabels = Object.keys(this.metricLabels)
  142. .filter(ml => {
  143. return this.target.aggregation.groupBys.indexOf('metric.label.' + ml) === -1;
  144. })
  145. .map(l => {
  146. return this.uiSegmentSrv.newSegment({
  147. value: `metric.label.${l}`,
  148. expandable: false,
  149. });
  150. });
  151. const resourceLabels = Object.keys(this.resourceLabels)
  152. .filter(ml => {
  153. return this.target.aggregation.groupBys.indexOf('resource.label.' + ml) === -1;
  154. })
  155. .map(l => {
  156. return this.uiSegmentSrv.newSegment({
  157. value: `resource.label.${l}`,
  158. expandable: false,
  159. });
  160. });
  161. return Promise.resolve([...metricLabels, ...resourceLabels, this.removeSegment]);
  162. }
  163. groupByChanged(segment, index) {
  164. if (segment.value === this.removeSegment.value) {
  165. this.groupBySegments.splice(index, 1);
  166. } else {
  167. segment.type = 'value';
  168. }
  169. const reducer = (memo, seg) => {
  170. if (!seg.fake) {
  171. memo.push(seg.value);
  172. }
  173. return memo;
  174. };
  175. this.target.aggregation.groupBys = this.groupBySegments.reduce(reducer, []);
  176. this.ensurePlusButton(this.groupBySegments);
  177. this.refresh();
  178. }
  179. ensurePlusButton(segments) {
  180. const count = segments.length;
  181. const lastSegment = segments[Math.max(count - 1, 0)];
  182. if (!lastSegment || lastSegment.type !== 'plus-button') {
  183. segments.push(this.uiSegmentSrv.newPlusButton());
  184. }
  185. }
  186. onDataReceived(dataList) {
  187. this.lastQueryError = null;
  188. this.lastQueryMeta = null;
  189. const anySeriesFromQuery: any = _.find(dataList, { refId: this.target.refId });
  190. if (anySeriesFromQuery) {
  191. this.lastQueryMeta = anySeriesFromQuery.meta;
  192. this.lastQueryMeta.rawQueryString = decodeURIComponent(this.lastQueryMeta.rawQuery);
  193. }
  194. }
  195. onDataError(err) {
  196. if (err.data && err.data.results) {
  197. const queryRes = err.data.results[this.target.refId];
  198. if (queryRes) {
  199. this.lastQueryMeta = queryRes.meta;
  200. this.lastQueryMeta.rawQueryString = decodeURIComponent(this.lastQueryMeta.rawQuery);
  201. let jsonBody;
  202. try {
  203. jsonBody = JSON.parse(queryRes.error);
  204. } catch {
  205. this.lastQueryError = queryRes.error;
  206. }
  207. this.lastQueryError = jsonBody.error.message;
  208. }
  209. }
  210. }
  211. }