query_ctrl.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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. alignmentPeriod: string;
  8. rawQuery: string;
  9. rawQueryString: string;
  10. metricLabels: { [key: string]: string[] };
  11. resourceLabels: { [key: string]: string[] };
  12. }
  13. export class StackdriverQueryCtrl extends QueryCtrl {
  14. static templateUrl = 'partials/query.editor.html';
  15. target: {
  16. project: {
  17. id: string;
  18. name: string;
  19. };
  20. metricType: string;
  21. service: string;
  22. refId: string;
  23. aggregation: {
  24. crossSeriesReducer: string;
  25. alignmentPeriod: string;
  26. perSeriesAligner: string;
  27. groupBys: string[];
  28. };
  29. filters: string[];
  30. aliasBy: string;
  31. metricKind: any;
  32. valueType: any;
  33. };
  34. defaultDropdownValue = 'Select Metric';
  35. defaultServiceValue = 'All Services';
  36. defaultRemoveGroupByValue = '-- remove group by --';
  37. loadLabelsPromise: Promise<any>;
  38. stackdriverConstants;
  39. defaults = {
  40. project: {
  41. id: 'default',
  42. name: 'loading project...',
  43. },
  44. metricType: this.defaultDropdownValue,
  45. service: this.defaultServiceValue,
  46. metric: '',
  47. aggregation: {
  48. crossSeriesReducer: 'REDUCE_MEAN',
  49. alignmentPeriod: 'auto',
  50. perSeriesAligner: 'ALIGN_MEAN',
  51. groupBys: [],
  52. },
  53. filters: [],
  54. showAggregationOptions: false,
  55. aliasBy: '',
  56. metricKind: '',
  57. valueType: '',
  58. };
  59. service: string;
  60. metricType: string;
  61. metricDescriptors: any[];
  62. metrics: any[];
  63. services: any[];
  64. groupBySegments: any[];
  65. removeSegment: any;
  66. showHelp: boolean;
  67. showLastQuery: boolean;
  68. lastQueryMeta: QueryMeta;
  69. lastQueryError?: string;
  70. metricLabels: { [key: string]: string[] };
  71. resourceLabels: { [key: string]: string[] };
  72. filterSegments: any;
  73. /** @ngInject */
  74. constructor($scope, $injector, private uiSegmentSrv, private templateSrv) {
  75. super($scope, $injector);
  76. _.defaultsDeep(this.target, this.defaults);
  77. this.metricDescriptors = [];
  78. this.metrics = [];
  79. this.services = [];
  80. this.metricType = this.defaultDropdownValue;
  81. this.service = this.defaultServiceValue;
  82. this.panelCtrl.events.on('data-received', this.onDataReceived.bind(this), $scope);
  83. this.panelCtrl.events.on('data-error', this.onDataError.bind(this), $scope);
  84. this.getCurrentProject()
  85. .then(this.loadMetricDescriptors.bind(this))
  86. .then(this.getLabels.bind(this));
  87. this.initSegments();
  88. }
  89. initSegments() {
  90. this.groupBySegments = this.target.aggregation.groupBys.map(groupBy => {
  91. return this.uiSegmentSrv.getSegmentForValue(groupBy);
  92. });
  93. this.removeSegment = this.uiSegmentSrv.newSegment({ fake: true, value: '-- remove group by --' });
  94. this.ensurePlusButton(this.groupBySegments);
  95. this.filterSegments = new FilterSegments(
  96. this.uiSegmentSrv,
  97. this.target,
  98. this.getGroupBys.bind(this, null, null, DefaultRemoveFilterValue, false),
  99. this.getFilterValues.bind(this)
  100. );
  101. this.filterSegments.buildSegmentModel();
  102. }
  103. async getCurrentProject() {
  104. try {
  105. this.target.project = await this.datasource.getDefaultProject();
  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 loadMetricDescriptors() {
  125. if (this.target.project.id !== 'default') {
  126. this.metricDescriptors = await this.datasource.getMetricTypes(this.target.project.id);
  127. this.services = this.getServicesList();
  128. this.metrics = this.getMetricsList();
  129. return this.metricDescriptors;
  130. } else {
  131. return [];
  132. }
  133. }
  134. getServicesList() {
  135. const defaultValue = { value: this.defaultServiceValue, text: this.defaultServiceValue };
  136. const services = this.metricDescriptors.map(m => {
  137. const [service] = m.type.split('/');
  138. const [serviceShortName] = service.split('.');
  139. return {
  140. value: service,
  141. text: serviceShortName,
  142. };
  143. });
  144. if (services.find(m => m.value === this.target.service)) {
  145. this.service = this.target.service;
  146. }
  147. return services.length > 0 ? [defaultValue, ..._.uniqBy(services, 'value')] : [];
  148. }
  149. getMetricsList() {
  150. const metrics = this.metricDescriptors.map(m => {
  151. const [service] = m.type.split('/');
  152. const [serviceShortName] = service.split('.');
  153. return {
  154. service,
  155. value: m.type,
  156. serviceShortName,
  157. text: m.displayName,
  158. title: m.description,
  159. };
  160. });
  161. let result;
  162. if (this.target.service === this.defaultServiceValue) {
  163. result = metrics.map(m => ({ ...m, text: `${m.service} - ${m.text}` }));
  164. } else {
  165. result = metrics.filter(m => m.service === this.target.service);
  166. }
  167. if (result.find(m => m.value === this.target.metricType)) {
  168. this.metricType = this.target.metricType;
  169. } else if (result.length > 0) {
  170. this.metricType = this.target.metricType = result[0].value;
  171. }
  172. return result;
  173. }
  174. async getLabels() {
  175. this.loadLabelsPromise = new Promise(async resolve => {
  176. try {
  177. const data = await this.datasource.getLabels(this.target.metricType, this.target.refId);
  178. this.metricLabels = data.results[this.target.refId].meta.metricLabels;
  179. this.resourceLabels = data.results[this.target.refId].meta.resourceLabels;
  180. resolve();
  181. } catch (error) {
  182. console.log(error.data.message);
  183. appEvents.emit('alert-error', ['Error', 'Error loading metric labels for ' + this.target.metricType]);
  184. resolve();
  185. }
  186. });
  187. }
  188. onServiceChange() {
  189. this.target.service = this.service;
  190. this.metrics = this.getMetricsList();
  191. this.setMetricType();
  192. if (!this.metrics.find(m => m.value === this.target.metricType)) {
  193. this.target.metricType = this.defaultDropdownValue;
  194. } else {
  195. this.refresh();
  196. }
  197. }
  198. async onMetricTypeChange() {
  199. this.setMetricType();
  200. this.refresh();
  201. this.getLabels();
  202. }
  203. setMetricType() {
  204. this.target.metricType = this.metricType;
  205. const { valueType, metricKind } = this.metricDescriptors.find(m => m.type === this.target.metricType);
  206. this.target.valueType = valueType;
  207. this.target.metricKind = metricKind;
  208. this.$scope.$broadcast('metricTypeChanged');
  209. }
  210. async getGroupBys(segment, index, removeText?: string, removeUsed = true) {
  211. await this.loadLabelsPromise;
  212. const metricLabels = Object.keys(this.metricLabels || {})
  213. .filter(ml => {
  214. if (!removeUsed) {
  215. return true;
  216. }
  217. return this.target.aggregation.groupBys.indexOf('metric.label.' + ml) === -1;
  218. })
  219. .map(l => {
  220. return this.uiSegmentSrv.newSegment({
  221. value: `metric.label.${l}`,
  222. expandable: false,
  223. });
  224. });
  225. const resourceLabels = Object.keys(this.resourceLabels || {})
  226. .filter(ml => {
  227. if (!removeUsed) {
  228. return true;
  229. }
  230. return this.target.aggregation.groupBys.indexOf('resource.label.' + ml) === -1;
  231. })
  232. .map(l => {
  233. return this.uiSegmentSrv.newSegment({
  234. value: `resource.label.${l}`,
  235. expandable: false,
  236. });
  237. });
  238. const noValueOrPlusButton = !segment || segment.type === 'plus-button';
  239. if (noValueOrPlusButton && metricLabels.length === 0 && resourceLabels.length === 0) {
  240. return Promise.resolve([]);
  241. }
  242. this.removeSegment.value = removeText || this.defaultRemoveGroupByValue;
  243. return Promise.resolve([...metricLabels, ...resourceLabels, this.removeSegment]);
  244. }
  245. groupByChanged(segment, index) {
  246. if (segment.value === this.removeSegment.value) {
  247. this.groupBySegments.splice(index, 1);
  248. } else {
  249. segment.type = 'value';
  250. }
  251. const reducer = (memo, seg) => {
  252. if (!seg.fake) {
  253. memo.push(seg.value);
  254. }
  255. return memo;
  256. };
  257. this.target.aggregation.groupBys = this.groupBySegments.reduce(reducer, []);
  258. this.ensurePlusButton(this.groupBySegments);
  259. this.refresh();
  260. }
  261. async getFilters(segment, index) {
  262. const hasNoFilterKeys = this.metricLabels && Object.keys(this.metricLabels).length === 0;
  263. return this.filterSegments.getFilters(segment, index, hasNoFilterKeys);
  264. }
  265. getFilterValues(index) {
  266. const filterKey = this.templateSrv.replace(this.filterSegments.filterSegments[index - 2].value);
  267. if (!filterKey || !this.metricLabels || Object.keys(this.metricLabels).length === 0) {
  268. return [];
  269. }
  270. const shortKey = filterKey.substring(filterKey.indexOf('.label.') + 7);
  271. if (filterKey.startsWith('metric.label.') && this.metricLabels.hasOwnProperty(shortKey)) {
  272. return this.metricLabels[shortKey];
  273. }
  274. if (filterKey.startsWith('resource.label.') && this.resourceLabels.hasOwnProperty(shortKey)) {
  275. return this.resourceLabels[shortKey];
  276. }
  277. return [];
  278. }
  279. filterSegmentUpdated(segment, index) {
  280. this.target.filters = this.filterSegments.filterSegmentUpdated(segment, index);
  281. this.refresh();
  282. }
  283. ensurePlusButton(segments) {
  284. const count = segments.length;
  285. const lastSegment = segments[Math.max(count - 1, 0)];
  286. if (!lastSegment || lastSegment.type !== 'plus-button') {
  287. segments.push(this.uiSegmentSrv.newPlusButton());
  288. }
  289. }
  290. onDataReceived(dataList) {
  291. this.lastQueryError = null;
  292. this.lastQueryMeta = null;
  293. const anySeriesFromQuery: any = _.find(dataList, { refId: this.target.refId });
  294. if (anySeriesFromQuery) {
  295. this.lastQueryMeta = anySeriesFromQuery.meta;
  296. this.lastQueryMeta.rawQueryString = decodeURIComponent(this.lastQueryMeta.rawQuery);
  297. }
  298. }
  299. onDataError(err) {
  300. if (err.data && err.data.results) {
  301. const queryRes = err.data.results[this.target.refId];
  302. if (queryRes && queryRes.error) {
  303. this.lastQueryMeta = queryRes.meta;
  304. this.lastQueryMeta.rawQueryString = decodeURIComponent(this.lastQueryMeta.rawQuery);
  305. let jsonBody;
  306. try {
  307. jsonBody = JSON.parse(queryRes.error);
  308. } catch {
  309. this.lastQueryError = queryRes.error;
  310. }
  311. this.lastQueryError = jsonBody.error.message;
  312. }
  313. }
  314. console.error(err);
  315. }
  316. }