query_ctrl.ts 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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. defaultRemoveGroupByValue = '-- remove group by --';
  32. loadLabelsPromise: Promise<any>;
  33. stackdriverConstants;
  34. defaults = {
  35. project: {
  36. id: 'default',
  37. name: 'loading project...',
  38. },
  39. metricType: this.defaultDropdownValue,
  40. aggregation: {
  41. crossSeriesReducer: 'REDUCE_MEAN',
  42. alignmentPeriod: 'auto',
  43. perSeriesAligner: 'ALIGN_MEAN',
  44. groupBys: [],
  45. },
  46. filters: [],
  47. showAggregationOptions: false,
  48. aliasBy: '',
  49. };
  50. groupBySegments: any[];
  51. removeSegment: any;
  52. showHelp: boolean;
  53. showLastQuery: boolean;
  54. lastQueryMeta: QueryMeta;
  55. lastQueryError?: string;
  56. metricLabels: { [key: string]: string[] };
  57. resourceLabels: { [key: string]: string[] };
  58. filterSegments: any;
  59. /** @ngInject */
  60. constructor($scope, $injector, private uiSegmentSrv, private timeSrv, private templateSrv) {
  61. super($scope, $injector);
  62. _.defaultsDeep(this.target, this.defaults);
  63. this.panelCtrl.events.on('data-received', this.onDataReceived.bind(this), $scope);
  64. this.panelCtrl.events.on('data-error', this.onDataError.bind(this), $scope);
  65. this.stackdriverConstants = options;
  66. this.getCurrentProject()
  67. .then(this.getMetricTypes.bind(this))
  68. .then(this.getLabels.bind(this));
  69. this.initSegments();
  70. }
  71. initSegments() {
  72. this.groupBySegments = this.target.aggregation.groupBys.map(groupBy => {
  73. return this.uiSegmentSrv.getSegmentForValue(groupBy);
  74. });
  75. this.removeSegment = this.uiSegmentSrv.newSegment({ fake: true, value: '-- remove group by --' });
  76. this.ensurePlusButton(this.groupBySegments);
  77. this.filterSegments = new FilterSegments(
  78. this.uiSegmentSrv,
  79. this.target,
  80. this.getGroupBys.bind(this, null, null, DefaultRemoveFilterValue, false),
  81. this.getFilterValues.bind(this)
  82. );
  83. this.filterSegments.buildSegmentModel();
  84. }
  85. async getCurrentProject() {
  86. try {
  87. this.target.project = await this.datasource.getDefaultProject();
  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/your-project-name/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].id));
  112. }
  113. return metricTypes.map(mt => ({ value: mt.id, text: mt.id }));
  114. } else {
  115. return [];
  116. }
  117. }
  118. async getLabels() {
  119. this.loadLabelsPromise = new Promise(async resolve => {
  120. try {
  121. const data = await this.datasource.getTimeSeries({
  122. targets: [
  123. {
  124. refId: this.target.refId,
  125. datasourceId: this.datasource.id,
  126. metricType: this.templateSrv.replace(this.target.metricType),
  127. aggregation: {
  128. crossSeriesReducer: 'REDUCE_NONE',
  129. },
  130. view: 'HEADERS',
  131. },
  132. ],
  133. range: this.timeSrv.timeRange(),
  134. });
  135. this.metricLabels = data.results[this.target.refId].meta.metricLabels;
  136. this.resourceLabels = data.results[this.target.refId].meta.resourceLabels;
  137. resolve();
  138. } catch (error) {
  139. resolve();
  140. }
  141. });
  142. }
  143. async onMetricTypeChange() {
  144. this.refresh();
  145. this.getLabels();
  146. }
  147. async getGroupBys(segment, index, removeText?: string, removeUsed = true) {
  148. await this.loadLabelsPromise;
  149. const metricLabels = Object.keys(this.metricLabels)
  150. .filter(ml => {
  151. if (!removeUsed) {
  152. return true;
  153. }
  154. return this.target.aggregation.groupBys.indexOf('metric.label.' + ml) === -1;
  155. })
  156. .map(l => {
  157. return this.uiSegmentSrv.newSegment({
  158. value: `metric.label.${l}`,
  159. expandable: false,
  160. });
  161. });
  162. const resourceLabels = Object.keys(this.resourceLabels)
  163. .filter(ml => {
  164. if (!removeUsed) {
  165. return true;
  166. }
  167. return this.target.aggregation.groupBys.indexOf('resource.label.' + ml) === -1;
  168. })
  169. .map(l => {
  170. return this.uiSegmentSrv.newSegment({
  171. value: `resource.label.${l}`,
  172. expandable: false,
  173. });
  174. });
  175. const noValueOrPlusButton = !segment || segment.type === 'plus-button';
  176. if (noValueOrPlusButton && metricLabels.length === 0 && resourceLabels.length === 0) {
  177. return Promise.resolve([]);
  178. }
  179. this.removeSegment.value = removeText || this.defaultRemoveGroupByValue;
  180. return Promise.resolve([...metricLabels, ...resourceLabels, this.removeSegment]);
  181. }
  182. groupByChanged(segment, index) {
  183. if (segment.value === this.removeSegment.value) {
  184. this.groupBySegments.splice(index, 1);
  185. } else {
  186. segment.type = 'value';
  187. }
  188. const reducer = (memo, seg) => {
  189. if (!seg.fake) {
  190. memo.push(seg.value);
  191. }
  192. return memo;
  193. };
  194. this.target.aggregation.groupBys = this.groupBySegments.reduce(reducer, []);
  195. this.ensurePlusButton(this.groupBySegments);
  196. this.refresh();
  197. }
  198. async getFilters(segment, index) {
  199. const hasNoFilterKeys = this.metricLabels && Object.keys(this.metricLabels).length === 0;
  200. return this.filterSegments.getFilters(segment, index, hasNoFilterKeys);
  201. }
  202. getFilterValues(index) {
  203. const filterKey = this.templateSrv.replace(this.filterSegments.filterSegments[index - 2].value);
  204. if (!filterKey || !this.metricLabels || Object.keys(this.metricLabels).length === 0) {
  205. return [];
  206. }
  207. const shortKey = filterKey.substring(filterKey.indexOf('.label.') + 7);
  208. if (filterKey.startsWith('metric.label.') && this.metricLabels.hasOwnProperty(shortKey)) {
  209. return this.metricLabels[shortKey];
  210. }
  211. if (filterKey.startsWith('resource.label.') && this.resourceLabels.hasOwnProperty(shortKey)) {
  212. return this.resourceLabels[shortKey];
  213. }
  214. return [];
  215. }
  216. filterSegmentUpdated(segment, index) {
  217. this.target.filters = this.filterSegments.filterSegmentUpdated(segment, index);
  218. this.refresh();
  219. }
  220. ensurePlusButton(segments) {
  221. const count = segments.length;
  222. const lastSegment = segments[Math.max(count - 1, 0)];
  223. if (!lastSegment || lastSegment.type !== 'plus-button') {
  224. segments.push(this.uiSegmentSrv.newPlusButton());
  225. }
  226. }
  227. onDataReceived(dataList) {
  228. this.lastQueryError = null;
  229. this.lastQueryMeta = null;
  230. const anySeriesFromQuery: any = _.find(dataList, { refId: this.target.refId });
  231. if (anySeriesFromQuery) {
  232. this.lastQueryMeta = anySeriesFromQuery.meta;
  233. this.lastQueryMeta.rawQueryString = decodeURIComponent(this.lastQueryMeta.rawQuery);
  234. } else {
  235. }
  236. }
  237. onDataError(err) {
  238. if (err.data && err.data.results) {
  239. const queryRes = err.data.results[this.target.refId];
  240. if (queryRes && queryRes.error) {
  241. this.lastQueryMeta = queryRes.meta;
  242. this.lastQueryMeta.rawQueryString = decodeURIComponent(this.lastQueryMeta.rawQuery);
  243. let jsonBody;
  244. try {
  245. jsonBody = JSON.parse(queryRes.error);
  246. } catch {
  247. this.lastQueryError = queryRes.error;
  248. }
  249. this.lastQueryError = jsonBody.error.message;
  250. }
  251. }
  252. console.error(err);
  253. }
  254. }