query_ctrl.ts 11 KB

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