query_ctrl.ts 9.0 KB

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