query_ctrl.ts 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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 timeSrv, 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.getTimeSeries({
  125. targets: [
  126. {
  127. refId: this.target.refId,
  128. datasourceId: this.datasource.id,
  129. metricType: this.templateSrv.replace(this.target.metricType),
  130. aggregation: {
  131. crossSeriesReducer: 'REDUCE_NONE',
  132. },
  133. view: 'HEADERS',
  134. },
  135. ],
  136. range: this.timeSrv.timeRange(),
  137. });
  138. this.metricLabels = data.results[this.target.refId].meta.metricLabels;
  139. this.resourceLabels = data.results[this.target.refId].meta.resourceLabels;
  140. this.target.valueType = data.results[this.target.refId].meta.valueType;
  141. this.target.metricKind = data.results[this.target.refId].meta.metricKind;
  142. resolve();
  143. } catch (error) {
  144. resolve();
  145. }
  146. });
  147. }
  148. async onMetricTypeChange() {
  149. this.refresh();
  150. this.getLabels();
  151. }
  152. async getGroupBys(segment, index, removeText?: string, removeUsed = true) {
  153. await this.loadLabelsPromise;
  154. const metricLabels = Object.keys(this.metricLabels)
  155. .filter(ml => {
  156. if (!removeUsed) {
  157. return true;
  158. }
  159. return this.target.aggregation.groupBys.indexOf('metric.label.' + ml) === -1;
  160. })
  161. .map(l => {
  162. return this.uiSegmentSrv.newSegment({
  163. value: `metric.label.${l}`,
  164. expandable: false,
  165. });
  166. });
  167. const resourceLabels = Object.keys(this.resourceLabels)
  168. .filter(ml => {
  169. if (!removeUsed) {
  170. return true;
  171. }
  172. return this.target.aggregation.groupBys.indexOf('resource.label.' + ml) === -1;
  173. })
  174. .map(l => {
  175. return this.uiSegmentSrv.newSegment({
  176. value: `resource.label.${l}`,
  177. expandable: false,
  178. });
  179. });
  180. const noValueOrPlusButton = !segment || segment.type === 'plus-button';
  181. if (noValueOrPlusButton && metricLabels.length === 0 && resourceLabels.length === 0) {
  182. return Promise.resolve([]);
  183. }
  184. this.removeSegment.value = removeText || this.defaultRemoveGroupByValue;
  185. return Promise.resolve([...metricLabels, ...resourceLabels, this.removeSegment]);
  186. }
  187. groupByChanged(segment, index) {
  188. if (segment.value === this.removeSegment.value) {
  189. this.groupBySegments.splice(index, 1);
  190. } else {
  191. segment.type = 'value';
  192. }
  193. const reducer = (memo, seg) => {
  194. if (!seg.fake) {
  195. memo.push(seg.value);
  196. }
  197. return memo;
  198. };
  199. this.target.aggregation.groupBys = this.groupBySegments.reduce(reducer, []);
  200. this.ensurePlusButton(this.groupBySegments);
  201. this.refresh();
  202. }
  203. async getFilters(segment, index) {
  204. const hasNoFilterKeys = this.metricLabels && Object.keys(this.metricLabels).length === 0;
  205. return this.filterSegments.getFilters(segment, index, hasNoFilterKeys);
  206. }
  207. getFilterValues(index) {
  208. const filterKey = this.templateSrv.replace(this.filterSegments.filterSegments[index - 2].value);
  209. if (!filterKey || !this.metricLabels || Object.keys(this.metricLabels).length === 0) {
  210. return [];
  211. }
  212. const shortKey = filterKey.substring(filterKey.indexOf('.label.') + 7);
  213. if (filterKey.startsWith('metric.label.') && this.metricLabels.hasOwnProperty(shortKey)) {
  214. return this.metricLabels[shortKey];
  215. }
  216. if (filterKey.startsWith('resource.label.') && this.resourceLabels.hasOwnProperty(shortKey)) {
  217. return this.resourceLabels[shortKey];
  218. }
  219. return [];
  220. }
  221. filterSegmentUpdated(segment, index) {
  222. this.target.filters = this.filterSegments.filterSegmentUpdated(segment, index);
  223. this.refresh();
  224. }
  225. ensurePlusButton(segments) {
  226. const count = segments.length;
  227. const lastSegment = segments[Math.max(count - 1, 0)];
  228. if (!lastSegment || lastSegment.type !== 'plus-button') {
  229. segments.push(this.uiSegmentSrv.newPlusButton());
  230. }
  231. }
  232. onDataReceived(dataList) {
  233. this.lastQueryError = null;
  234. this.lastQueryMeta = null;
  235. const anySeriesFromQuery: any = _.find(dataList, { refId: this.target.refId });
  236. if (anySeriesFromQuery) {
  237. this.lastQueryMeta = anySeriesFromQuery.meta;
  238. this.lastQueryMeta.rawQueryString = decodeURIComponent(this.lastQueryMeta.rawQuery);
  239. }
  240. }
  241. onDataError(err) {
  242. if (err.data && err.data.results) {
  243. const queryRes = err.data.results[this.target.refId];
  244. if (queryRes && queryRes.error) {
  245. this.lastQueryMeta = queryRes.meta;
  246. this.lastQueryMeta.rawQueryString = decodeURIComponent(this.lastQueryMeta.rawQuery);
  247. let jsonBody;
  248. try {
  249. jsonBody = JSON.parse(queryRes.error);
  250. } catch {
  251. this.lastQueryError = queryRes.error;
  252. }
  253. this.lastQueryError = jsonBody.error.message;
  254. }
  255. }
  256. console.error(err);
  257. }
  258. }