query_ctrl.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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. // mport BaseComponent, * as extras from './A';
  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. secondaryCrossSeriesReducer: string;
  24. alignmentPeriod: string;
  25. perSeriesAligner: string;
  26. groupBys: string[];
  27. };
  28. filters: 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. secondaryCrossSeriesReducer: 'REDUCE_NONE',
  45. alignmentPeriod: 'auto',
  46. perSeriesAligner: 'ALIGN_MEAN',
  47. groupBys: [],
  48. },
  49. filters: [],
  50. showAggregationOptions: false,
  51. };
  52. groupBySegments: any[];
  53. filterSegments: any[];
  54. removeSegment: any;
  55. showHelp: boolean;
  56. showLastQuery: boolean;
  57. lastQueryMeta: QueryMeta;
  58. lastQueryError?: string;
  59. metricLabels: { [key: string]: string[] };
  60. resourceLabels: { [key: string]: string[] };
  61. /** @ngInject */
  62. constructor($scope, $injector, private uiSegmentSrv, private timeSrv) {
  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 = [];
  80. this.target.filters.forEach((f, index) => {
  81. switch (index % 4) {
  82. case 0:
  83. this.filterSegments.push(this.uiSegmentSrv.newKey(f));
  84. break;
  85. case 1:
  86. this.filterSegments.push(this.uiSegmentSrv.newOperator(f));
  87. break;
  88. case 2:
  89. this.filterSegments.push(this.uiSegmentSrv.newKeyValue(f));
  90. break;
  91. case 3:
  92. this.filterSegments.push(this.uiSegmentSrv.newCondition(f));
  93. break;
  94. }
  95. });
  96. this.ensurePlusButton(this.filterSegments);
  97. }
  98. async getCurrentProject() {
  99. try {
  100. const projects = await this.datasource.getProjects();
  101. if (projects && projects.length > 0) {
  102. this.target.project = projects[0];
  103. } else {
  104. throw new Error('No projects found');
  105. }
  106. } catch (error) {
  107. let message = 'Projects cannot be fetched: ';
  108. message += error.statusText ? error.statusText + ': ' : '';
  109. if (error && error.data && error.data.error && error.data.error.message) {
  110. if (error.data.error.code === 403) {
  111. message += `
  112. A list of projects could not be fetched from the Google Cloud Resource Manager API.
  113. You might need to enable it first:
  114. https://console.developers.google.com/apis/library/cloudresourcemanager.googleapis.com`;
  115. } else {
  116. message += error.data.error.code + '. ' + error.data.error.message;
  117. }
  118. } else {
  119. message += 'Cannot connect to Stackdriver API';
  120. }
  121. appEvents.emit('ds-request-error', message);
  122. }
  123. }
  124. async getMetricTypes() {
  125. //projects/your-project-name/metricDescriptors/agent.googleapis.com/agent/api_request_count
  126. if (this.target.project.id !== 'default') {
  127. const metricTypes = await this.datasource.getMetricTypes(this.target.project.id);
  128. if (this.target.metricType === this.defaultDropdownValue && metricTypes.length > 0) {
  129. this.$scope.$apply(() => (this.target.metricType = metricTypes[0].id));
  130. }
  131. return metricTypes.map(mt => ({ value: mt.id, text: mt.id }));
  132. } else {
  133. return [];
  134. }
  135. }
  136. async getLabels() {
  137. this.loadLabelsPromise = new Promise(async resolve => {
  138. try {
  139. const data = await this.datasource.getTimeSeries({
  140. targets: [
  141. {
  142. refId: this.target.refId,
  143. datasourceId: this.datasource.id,
  144. metricType: this.target.metricType,
  145. aggregation: {
  146. crossSeriesReducer: 'REDUCE_NONE',
  147. },
  148. view: 'HEADERS',
  149. },
  150. ],
  151. range: this.timeSrv.timeRange(),
  152. });
  153. this.metricLabels = data.results[this.target.refId].meta.metricLabels;
  154. this.resourceLabels = data.results[this.target.refId].meta.resourceLabels;
  155. resolve();
  156. } catch (error) {
  157. resolve();
  158. }
  159. });
  160. }
  161. async onMetricTypeChange() {
  162. this.refresh();
  163. this.getLabels();
  164. }
  165. async getGroupBys(segment, index, removeText?: string, removeUsed = true) {
  166. await this.loadLabelsPromise;
  167. const metricLabels = Object.keys(this.metricLabels)
  168. .filter(ml => {
  169. if (!removeUsed) {
  170. return true;
  171. }
  172. return this.target.aggregation.groupBys.indexOf('metric.label.' + ml) === -1;
  173. })
  174. .map(l => {
  175. return this.uiSegmentSrv.newSegment({
  176. value: `metric.label.${l}`,
  177. expandable: false,
  178. });
  179. });
  180. const resourceLabels = Object.keys(this.resourceLabels)
  181. .filter(ml => {
  182. if (!removeUsed) {
  183. return true;
  184. }
  185. return this.target.aggregation.groupBys.indexOf('resource.label.' + ml) === -1;
  186. })
  187. .map(l => {
  188. return this.uiSegmentSrv.newSegment({
  189. value: `resource.label.${l}`,
  190. expandable: false,
  191. });
  192. });
  193. const noValueOrPlusButton = !segment || segment.type === 'plus-button';
  194. if (noValueOrPlusButton && metricLabels.length === 0 && resourceLabels.length === 0) {
  195. return Promise.resolve([]);
  196. }
  197. this.removeSegment.value = removeText || this.defaultRemoveGroupByValue;
  198. return Promise.resolve([...metricLabels, ...resourceLabels, this.removeSegment]);
  199. }
  200. groupByChanged(segment, index) {
  201. if (segment.value === this.removeSegment.value) {
  202. this.groupBySegments.splice(index, 1);
  203. } else {
  204. segment.type = 'value';
  205. }
  206. const reducer = (memo, seg) => {
  207. if (!seg.fake) {
  208. memo.push(seg.value);
  209. }
  210. return memo;
  211. };
  212. this.target.aggregation.groupBys = this.groupBySegments.reduce(reducer, []);
  213. this.ensurePlusButton(this.groupBySegments);
  214. this.refresh();
  215. }
  216. async getFilters(segment, index) {
  217. if (segment.type === 'condition') {
  218. return [this.uiSegmentSrv.newSegment('AND')];
  219. }
  220. if (segment.type === 'operator') {
  221. return this.uiSegmentSrv.newOperators(['=', '!=', '=~', '!=~']);
  222. }
  223. if (segment.type === 'key' || segment.type === 'plus-button') {
  224. if (
  225. this.metricLabels &&
  226. Object.keys(this.metricLabels).length === 0 &&
  227. segment.value &&
  228. segment.value !== this.defaultRemoveFilterValue
  229. ) {
  230. this.removeSegment.value = this.defaultRemoveFilterValue;
  231. return Promise.resolve([this.removeSegment]);
  232. } else {
  233. return this.getGroupBys(null, null, this.defaultRemoveFilterValue, false);
  234. }
  235. }
  236. if (segment.type === 'value') {
  237. const filterKey = this.filterSegments[index - 2].value;
  238. const shortKey = filterKey.substring(filterKey.indexOf('.label.') + 7);
  239. if (filterKey.startsWith('metric.label.') && this.metricLabels.hasOwnProperty(shortKey)) {
  240. return this.getValuesForFilterKey(this.metricLabels[shortKey]);
  241. }
  242. if (filterKey.startsWith('resource.label.') && this.resourceLabels.hasOwnProperty(shortKey)) {
  243. return this.getValuesForFilterKey(this.resourceLabels[shortKey]);
  244. }
  245. }
  246. return [];
  247. }
  248. getValuesForFilterKey(labels: any[]) {
  249. const filterValues = labels.map(l => {
  250. return this.uiSegmentSrv.newSegment({
  251. value: `${l}`,
  252. expandable: false,
  253. });
  254. });
  255. return filterValues;
  256. }
  257. filterSegmentUpdated(segment, index) {
  258. if (segment.type === 'plus-button') {
  259. this.addNewFilterSegments(segment, index);
  260. } else if (segment.type === 'key' && segment.value === this.defaultRemoveFilterValue) {
  261. this.removeFilterSegment(index);
  262. this.ensurePlusButton(this.filterSegments);
  263. } else if (segment.type === 'value' && segment.value !== this.defaultFilterValue) {
  264. this.ensurePlusButton(this.filterSegments);
  265. }
  266. this.target.filters = this.filterSegments.filter(s => s.type !== 'plus-button').map(seg => seg.value);
  267. this.refresh();
  268. }
  269. addNewFilterSegments(segment, index) {
  270. if (index > 2) {
  271. this.filterSegments.splice(index, 0, this.uiSegmentSrv.newCondition('AND'));
  272. }
  273. segment.type = 'key';
  274. this.filterSegments.push(this.uiSegmentSrv.newOperator('='));
  275. this.filterSegments.push(this.uiSegmentSrv.newFake(this.defaultFilterValue, 'value', 'query-segment-value'));
  276. }
  277. removeFilterSegment(index) {
  278. this.filterSegments.splice(index, 3);
  279. // remove trailing condition
  280. if (index > 2 && this.filterSegments[index - 1].type === 'condition') {
  281. this.filterSegments.splice(index - 1, 1);
  282. }
  283. // remove condition if it is first segment
  284. if (index === 0 && this.filterSegments[0].type === 'condition') {
  285. this.filterSegments.splice(0, 1);
  286. }
  287. }
  288. ensurePlusButton(segments) {
  289. const count = segments.length;
  290. const lastSegment = segments[Math.max(count - 1, 0)];
  291. if (!lastSegment || lastSegment.type !== 'plus-button') {
  292. segments.push(this.uiSegmentSrv.newPlusButton());
  293. }
  294. }
  295. onDataReceived(dataList) {
  296. this.lastQueryError = null;
  297. this.lastQueryMeta = null;
  298. const anySeriesFromQuery: any = _.find(dataList, { refId: this.target.refId });
  299. if (anySeriesFromQuery) {
  300. this.lastQueryMeta = anySeriesFromQuery.meta;
  301. this.lastQueryMeta.rawQueryString = decodeURIComponent(this.lastQueryMeta.rawQuery);
  302. } else {
  303. }
  304. }
  305. onDataError(err) {
  306. if (err.data && err.data.results) {
  307. const queryRes = err.data.results[this.target.refId];
  308. if (queryRes && queryRes.error) {
  309. this.lastQueryMeta = queryRes.meta;
  310. this.lastQueryMeta.rawQueryString = decodeURIComponent(this.lastQueryMeta.rawQuery);
  311. let jsonBody;
  312. try {
  313. jsonBody = JSON.parse(queryRes.error);
  314. } catch {
  315. this.lastQueryError = queryRes.error;
  316. }
  317. this.lastQueryError = jsonBody.error.message;
  318. }
  319. }
  320. console.error(err);
  321. }
  322. }