query_ctrl.ts 9.9 KB

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