query_ctrl.ts 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. import _ from 'lodash';
  2. import { QueryCtrl } from 'app/plugins/sdk';
  3. import appEvents from 'app/core/app_events';
  4. import { FilterSegments, DefaultRemoveFilterValue } from './filter_segments';
  5. import './query_aggregation_ctrl';
  6. export interface QueryMeta {
  7. rawQuery: string;
  8. rawQueryString: string;
  9. metricLabels: { [key: string]: string[] };
  10. resourceLabels: { [key: string]: string[] };
  11. }
  12. export class StackdriverQueryCtrl extends QueryCtrl {
  13. static templateUrl = 'partials/query.editor.html';
  14. target: {
  15. project: {
  16. id: string;
  17. name: string;
  18. };
  19. metricType: string;
  20. refId: string;
  21. aggregation: {
  22. crossSeriesReducer: string;
  23. alignmentPeriod: string;
  24. perSeriesAligner: string;
  25. groupBys: string[];
  26. };
  27. filters: string[];
  28. aliasBy: string;
  29. metricKind: any;
  30. valueType: any;
  31. };
  32. defaultDropdownValue = 'select metric';
  33. defaultRemoveGroupByValue = '-- remove group by --';
  34. loadLabelsPromise: Promise<any>;
  35. stackdriverConstants;
  36. defaults = {
  37. project: {
  38. id: 'default',
  39. name: 'loading project...',
  40. },
  41. metricType: this.defaultDropdownValue,
  42. aggregation: {
  43. crossSeriesReducer: 'REDUCE_MEAN',
  44. alignmentPeriod: 'auto',
  45. perSeriesAligner: 'ALIGN_MEAN',
  46. groupBys: [],
  47. },
  48. filters: [],
  49. showAggregationOptions: false,
  50. aliasBy: '',
  51. metricKind: '',
  52. valueType: '',
  53. };
  54. groupBySegments: any[];
  55. removeSegment: any;
  56. showHelp: boolean;
  57. showLastQuery: boolean;
  58. lastQueryMeta: QueryMeta;
  59. lastQueryError?: string;
  60. metricLabels: { [key: string]: string[] };
  61. resourceLabels: { [key: string]: string[] };
  62. filterSegments: any;
  63. /** @ngInject */
  64. constructor($scope, $injector, private uiSegmentSrv, private templateSrv) {
  65. super($scope, $injector);
  66. _.defaultsDeep(this.target, this.defaults);
  67. this.panelCtrl.events.on('data-received', this.onDataReceived.bind(this), $scope);
  68. this.panelCtrl.events.on('data-error', this.onDataError.bind(this), $scope);
  69. this.getCurrentProject()
  70. .then(this.getMetricTypes.bind(this))
  71. .then(this.getLabels.bind(this));
  72. this.initSegments();
  73. }
  74. initSegments() {
  75. this.groupBySegments = this.target.aggregation.groupBys.map(groupBy => {
  76. return this.uiSegmentSrv.getSegmentForValue(groupBy);
  77. });
  78. this.removeSegment = this.uiSegmentSrv.newSegment({ fake: true, value: '-- remove group by --' });
  79. this.ensurePlusButton(this.groupBySegments);
  80. this.filterSegments = new FilterSegments(
  81. this.uiSegmentSrv,
  82. this.target,
  83. this.getGroupBys.bind(this, null, null, DefaultRemoveFilterValue, false),
  84. this.getFilterValues.bind(this)
  85. );
  86. this.filterSegments.buildSegmentModel();
  87. }
  88. async getCurrentProject() {
  89. try {
  90. this.target.project = await this.datasource.getDefaultProject();
  91. } catch (error) {
  92. let message = 'Projects cannot be fetched: ';
  93. message += error.statusText ? error.statusText + ': ' : '';
  94. if (error && error.data && error.data.error && error.data.error.message) {
  95. if (error.data.error.code === 403) {
  96. message += `
  97. A list of projects could not be fetched from the Google Cloud Resource Manager API.
  98. You might need to enable it first:
  99. https://console.developers.google.com/apis/library/cloudresourcemanager.googleapis.com`;
  100. } else {
  101. message += error.data.error.code + '. ' + error.data.error.message;
  102. }
  103. } else {
  104. message += 'Cannot connect to Stackdriver API';
  105. }
  106. appEvents.emit('ds-request-error', message);
  107. }
  108. }
  109. async getMetricTypes() {
  110. //projects/your-project-name/metricDescriptors/agent.googleapis.com/agent/api_request_count
  111. if (this.target.project.id !== 'default') {
  112. const metricTypes = await this.datasource.getMetricTypes(this.target.project.id);
  113. if (this.target.metricType === this.defaultDropdownValue && metricTypes.length > 0) {
  114. this.$scope.$apply(() => (this.target.metricType = metricTypes[0].id));
  115. }
  116. return metricTypes.map(mt => ({ value: mt.id, text: mt.id }));
  117. } else {
  118. return [];
  119. }
  120. }
  121. async getLabels() {
  122. this.loadLabelsPromise = new Promise(async resolve => {
  123. try {
  124. const data = await this.datasource.getLabels(this.target.metricType, this.target.refId);
  125. this.metricLabels = data.results[this.target.refId].meta.metricLabels;
  126. this.resourceLabels = data.results[this.target.refId].meta.resourceLabels;
  127. this.target.valueType = data.results[this.target.refId].meta.valueType;
  128. this.target.metricKind = data.results[this.target.refId].meta.metricKind;
  129. resolve();
  130. } catch (error) {
  131. console.log(error.data.message);
  132. appEvents.emit('alert-error', ['Error', 'Error loading metric labels for ' + this.target.metricType]);
  133. resolve();
  134. }
  135. });
  136. }
  137. async onMetricTypeChange() {
  138. this.refresh();
  139. this.getLabels();
  140. }
  141. async getGroupBys(segment, index, removeText?: string, removeUsed = true) {
  142. await this.loadLabelsPromise;
  143. const metricLabels = Object.keys(this.metricLabels || {})
  144. .filter(ml => {
  145. if (!removeUsed) {
  146. return true;
  147. }
  148. return this.target.aggregation.groupBys.indexOf('metric.label.' + ml) === -1;
  149. })
  150. .map(l => {
  151. return this.uiSegmentSrv.newSegment({
  152. value: `metric.label.${l}`,
  153. expandable: false,
  154. });
  155. });
  156. const resourceLabels = Object.keys(this.resourceLabels || {})
  157. .filter(ml => {
  158. if (!removeUsed) {
  159. return true;
  160. }
  161. return this.target.aggregation.groupBys.indexOf('resource.label.' + ml) === -1;
  162. })
  163. .map(l => {
  164. return this.uiSegmentSrv.newSegment({
  165. value: `resource.label.${l}`,
  166. expandable: false,
  167. });
  168. });
  169. const noValueOrPlusButton = !segment || segment.type === 'plus-button';
  170. if (noValueOrPlusButton && metricLabels.length === 0 && resourceLabels.length === 0) {
  171. return Promise.resolve([]);
  172. }
  173. this.removeSegment.value = removeText || this.defaultRemoveGroupByValue;
  174. return Promise.resolve([...metricLabels, ...resourceLabels, this.removeSegment]);
  175. }
  176. groupByChanged(segment, index) {
  177. if (segment.value === this.removeSegment.value) {
  178. this.groupBySegments.splice(index, 1);
  179. } else {
  180. segment.type = 'value';
  181. }
  182. const reducer = (memo, seg) => {
  183. if (!seg.fake) {
  184. memo.push(seg.value);
  185. }
  186. return memo;
  187. };
  188. this.target.aggregation.groupBys = this.groupBySegments.reduce(reducer, []);
  189. this.ensurePlusButton(this.groupBySegments);
  190. this.refresh();
  191. }
  192. async getFilters(segment, index) {
  193. const hasNoFilterKeys = this.metricLabels && Object.keys(this.metricLabels).length === 0;
  194. return this.filterSegments.getFilters(segment, index, hasNoFilterKeys);
  195. }
  196. getFilterValues(index) {
  197. const filterKey = this.templateSrv.replace(this.filterSegments.filterSegments[index - 2].value);
  198. if (!filterKey || !this.metricLabels || Object.keys(this.metricLabels).length === 0) {
  199. return [];
  200. }
  201. const shortKey = filterKey.substring(filterKey.indexOf('.label.') + 7);
  202. if (filterKey.startsWith('metric.label.') && this.metricLabels.hasOwnProperty(shortKey)) {
  203. return this.metricLabels[shortKey];
  204. }
  205. if (filterKey.startsWith('resource.label.') && this.resourceLabels.hasOwnProperty(shortKey)) {
  206. return this.resourceLabels[shortKey];
  207. }
  208. return [];
  209. }
  210. filterSegmentUpdated(segment, index) {
  211. this.target.filters = this.filterSegments.filterSegmentUpdated(segment, index);
  212. this.refresh();
  213. }
  214. ensurePlusButton(segments) {
  215. const count = segments.length;
  216. const lastSegment = segments[Math.max(count - 1, 0)];
  217. if (!lastSegment || lastSegment.type !== 'plus-button') {
  218. segments.push(this.uiSegmentSrv.newPlusButton());
  219. }
  220. }
  221. onDataReceived(dataList) {
  222. this.lastQueryError = null;
  223. this.lastQueryMeta = null;
  224. const anySeriesFromQuery: any = _.find(dataList, { refId: this.target.refId });
  225. if (anySeriesFromQuery) {
  226. this.lastQueryMeta = anySeriesFromQuery.meta;
  227. this.lastQueryMeta.rawQueryString = decodeURIComponent(this.lastQueryMeta.rawQuery);
  228. }
  229. }
  230. onDataError(err) {
  231. if (err.data && err.data.results) {
  232. const queryRes = err.data.results[this.target.refId];
  233. if (queryRes && queryRes.error) {
  234. this.lastQueryMeta = queryRes.meta;
  235. this.lastQueryMeta.rawQueryString = decodeURIComponent(this.lastQueryMeta.rawQuery);
  236. let jsonBody;
  237. try {
  238. jsonBody = JSON.parse(queryRes.error);
  239. } catch {
  240. this.lastQueryError = queryRes.error;
  241. }
  242. this.lastQueryError = jsonBody.error.message;
  243. }
  244. }
  245. console.error(err);
  246. }
  247. }