query_ctrl.ts 11 KB

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