query_ctrl.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. import angular, { auto, IQService } from 'angular';
  2. import _ from 'lodash';
  3. import { InfluxQueryBuilder } from './query_builder';
  4. import InfluxQueryModel from './influx_query_model';
  5. import queryPart from './query_part';
  6. import { QueryCtrl } from 'app/plugins/sdk';
  7. import { TemplateSrv } from 'app/features/templating/template_srv';
  8. export class InfluxQueryCtrl extends QueryCtrl {
  9. static templateUrl = 'partials/query.editor.html';
  10. queryModel: InfluxQueryModel;
  11. queryBuilder: any;
  12. groupBySegment: any;
  13. resultFormats: any[];
  14. orderByTime: any[];
  15. policySegment: any;
  16. tagSegments: any[];
  17. selectMenu: any;
  18. measurementSegment: any;
  19. removeTagFilterSegment: any;
  20. /** @ngInject */
  21. constructor(
  22. $scope: any,
  23. $injector: auto.IInjectorService,
  24. private templateSrv: TemplateSrv,
  25. private $q: IQService,
  26. private uiSegmentSrv: any
  27. ) {
  28. super($scope, $injector);
  29. this.target = this.target;
  30. this.queryModel = new InfluxQueryModel(this.target, templateSrv, this.panel.scopedVars);
  31. this.queryBuilder = new InfluxQueryBuilder(this.target, this.datasource.database);
  32. this.groupBySegment = this.uiSegmentSrv.newPlusButton();
  33. this.resultFormats = [{ text: 'Time series', value: 'time_series' }, { text: 'Table', value: 'table' }];
  34. this.policySegment = uiSegmentSrv.newSegment(this.target.policy);
  35. if (!this.target.measurement) {
  36. this.measurementSegment = uiSegmentSrv.newSelectMeasurement();
  37. } else {
  38. this.measurementSegment = uiSegmentSrv.newSegment(this.target.measurement);
  39. }
  40. this.tagSegments = [];
  41. for (const tag of this.target.tags) {
  42. if (!tag.operator) {
  43. if (/^\/.*\/$/.test(tag.value)) {
  44. tag.operator = '=~';
  45. } else {
  46. tag.operator = '=';
  47. }
  48. }
  49. if (tag.condition) {
  50. this.tagSegments.push(uiSegmentSrv.newCondition(tag.condition));
  51. }
  52. this.tagSegments.push(uiSegmentSrv.newKey(tag.key));
  53. this.tagSegments.push(uiSegmentSrv.newOperator(tag.operator));
  54. this.tagSegments.push(uiSegmentSrv.newKeyValue(tag.value));
  55. }
  56. this.fixTagSegments();
  57. this.buildSelectMenu();
  58. this.removeTagFilterSegment = uiSegmentSrv.newSegment({
  59. fake: true,
  60. value: '-- remove tag filter --',
  61. });
  62. }
  63. removeOrderByTime() {
  64. this.target.orderByTime = 'ASC';
  65. }
  66. buildSelectMenu() {
  67. const categories = queryPart.getCategories();
  68. this.selectMenu = _.reduce(
  69. categories,
  70. (memo, cat, key) => {
  71. const menu = {
  72. text: key,
  73. submenu: cat.map((item: any) => {
  74. return { text: item.type, value: item.type };
  75. }),
  76. };
  77. memo.push(menu);
  78. return memo;
  79. },
  80. []
  81. );
  82. }
  83. getGroupByOptions() {
  84. const query = this.queryBuilder.buildExploreQuery('TAG_KEYS');
  85. return this.datasource
  86. .metricFindQuery(query)
  87. .then((tags: any) => {
  88. const options = [];
  89. if (!this.queryModel.hasFill()) {
  90. options.push(this.uiSegmentSrv.newSegment({ value: 'fill(null)' }));
  91. }
  92. if (!this.target.limit) {
  93. options.push(this.uiSegmentSrv.newSegment({ value: 'LIMIT' }));
  94. }
  95. if (!this.target.slimit) {
  96. options.push(this.uiSegmentSrv.newSegment({ value: 'SLIMIT' }));
  97. }
  98. if (!this.target.tz) {
  99. options.push(this.uiSegmentSrv.newSegment({ value: 'tz' }));
  100. }
  101. if (this.target.orderByTime === 'ASC') {
  102. options.push(this.uiSegmentSrv.newSegment({ value: 'ORDER BY time DESC' }));
  103. }
  104. if (!this.queryModel.hasGroupByTime()) {
  105. options.push(this.uiSegmentSrv.newSegment({ value: 'time($interval)' }));
  106. }
  107. for (const tag of tags) {
  108. options.push(this.uiSegmentSrv.newSegment({ value: 'tag(' + tag.text + ')' }));
  109. }
  110. return options;
  111. })
  112. .catch(this.handleQueryError.bind(this));
  113. }
  114. groupByAction() {
  115. switch (this.groupBySegment.value) {
  116. case 'LIMIT': {
  117. this.target.limit = 10;
  118. break;
  119. }
  120. case 'SLIMIT': {
  121. this.target.slimit = 10;
  122. break;
  123. }
  124. case 'tz': {
  125. this.target.tz = 'UTC';
  126. break;
  127. }
  128. case 'ORDER BY time DESC': {
  129. this.target.orderByTime = 'DESC';
  130. break;
  131. }
  132. default: {
  133. this.queryModel.addGroupBy(this.groupBySegment.value);
  134. }
  135. }
  136. const plusButton = this.uiSegmentSrv.newPlusButton();
  137. this.groupBySegment.value = plusButton.value;
  138. this.groupBySegment.html = plusButton.html;
  139. this.panelCtrl.refresh();
  140. }
  141. addSelectPart(selectParts: any, cat: any, subitem: { value: any }) {
  142. this.queryModel.addSelectPart(selectParts, subitem.value);
  143. this.panelCtrl.refresh();
  144. }
  145. handleSelectPartEvent(selectParts: any, part: any, evt: { name: any }) {
  146. switch (evt.name) {
  147. case 'get-param-options': {
  148. const fieldsQuery = this.queryBuilder.buildExploreQuery('FIELDS');
  149. return this.datasource
  150. .metricFindQuery(fieldsQuery)
  151. .then(this.transformToSegments(true))
  152. .catch(this.handleQueryError.bind(this));
  153. }
  154. case 'part-param-changed': {
  155. this.panelCtrl.refresh();
  156. break;
  157. }
  158. case 'action': {
  159. this.queryModel.removeSelectPart(selectParts, part);
  160. this.panelCtrl.refresh();
  161. break;
  162. }
  163. case 'get-part-actions': {
  164. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  165. }
  166. }
  167. }
  168. handleGroupByPartEvent(part: any, index: any, evt: { name: any }) {
  169. switch (evt.name) {
  170. case 'get-param-options': {
  171. const tagsQuery = this.queryBuilder.buildExploreQuery('TAG_KEYS');
  172. return this.datasource
  173. .metricFindQuery(tagsQuery)
  174. .then(this.transformToSegments(true))
  175. .catch(this.handleQueryError.bind(this));
  176. }
  177. case 'part-param-changed': {
  178. this.panelCtrl.refresh();
  179. break;
  180. }
  181. case 'action': {
  182. this.queryModel.removeGroupByPart(part, index);
  183. this.panelCtrl.refresh();
  184. break;
  185. }
  186. case 'get-part-actions': {
  187. return this.$q.when([{ text: 'Remove', value: 'remove-part' }]);
  188. }
  189. }
  190. }
  191. fixTagSegments() {
  192. const count = this.tagSegments.length;
  193. const lastSegment = this.tagSegments[Math.max(count - 1, 0)];
  194. if (!lastSegment || lastSegment.type !== 'plus-button') {
  195. this.tagSegments.push(this.uiSegmentSrv.newPlusButton());
  196. }
  197. }
  198. measurementChanged() {
  199. this.target.measurement = this.measurementSegment.value;
  200. this.panelCtrl.refresh();
  201. }
  202. getPolicySegments() {
  203. const policiesQuery = this.queryBuilder.buildExploreQuery('RETENTION POLICIES');
  204. return this.datasource
  205. .metricFindQuery(policiesQuery)
  206. .then(this.transformToSegments(false))
  207. .catch(this.handleQueryError.bind(this));
  208. }
  209. policyChanged() {
  210. this.target.policy = this.policySegment.value;
  211. this.panelCtrl.refresh();
  212. }
  213. toggleEditorMode() {
  214. try {
  215. this.target.query = this.queryModel.render(false);
  216. } catch (err) {
  217. console.log('query render error');
  218. }
  219. this.target.rawQuery = !this.target.rawQuery;
  220. }
  221. getMeasurements(measurementFilter: any) {
  222. const query = this.queryBuilder.buildExploreQuery('MEASUREMENTS', undefined, measurementFilter);
  223. return this.datasource
  224. .metricFindQuery(query)
  225. .then(this.transformToSegments(true))
  226. .catch(this.handleQueryError.bind(this));
  227. }
  228. handleQueryError(err: any): any[] {
  229. this.error = err.message || 'Failed to issue metric query';
  230. return [];
  231. }
  232. transformToSegments(addTemplateVars: any) {
  233. return (results: any) => {
  234. const segments = _.map(results, segment => {
  235. return this.uiSegmentSrv.newSegment({
  236. value: segment.text,
  237. expandable: segment.expandable,
  238. });
  239. });
  240. if (addTemplateVars) {
  241. for (const variable of this.templateSrv.variables) {
  242. segments.unshift(
  243. this.uiSegmentSrv.newSegment({
  244. type: 'value',
  245. value: '/^$' + variable.name + '$/',
  246. expandable: true,
  247. })
  248. );
  249. }
  250. }
  251. return segments;
  252. };
  253. }
  254. getTagsOrValues(segment: { type: string }, index: number) {
  255. if (segment.type === 'condition') {
  256. return this.$q.when([this.uiSegmentSrv.newSegment('AND'), this.uiSegmentSrv.newSegment('OR')]);
  257. }
  258. if (segment.type === 'operator') {
  259. const nextValue = this.tagSegments[index + 1].value;
  260. if (/^\/.*\/$/.test(nextValue)) {
  261. return this.$q.when(this.uiSegmentSrv.newOperators(['=~', '!~']));
  262. } else {
  263. return this.$q.when(this.uiSegmentSrv.newOperators(['=', '!=', '<>', '<', '>']));
  264. }
  265. }
  266. let query, addTemplateVars;
  267. if (segment.type === 'key' || segment.type === 'plus-button') {
  268. query = this.queryBuilder.buildExploreQuery('TAG_KEYS');
  269. addTemplateVars = false;
  270. } else if (segment.type === 'value') {
  271. query = this.queryBuilder.buildExploreQuery('TAG_VALUES', this.tagSegments[index - 2].value);
  272. addTemplateVars = true;
  273. }
  274. return this.datasource
  275. .metricFindQuery(query)
  276. .then(this.transformToSegments(addTemplateVars))
  277. .then((results: any) => {
  278. if (segment.type === 'key') {
  279. results.splice(0, 0, angular.copy(this.removeTagFilterSegment));
  280. }
  281. return results;
  282. })
  283. .catch(this.handleQueryError.bind(this));
  284. }
  285. getFieldSegments() {
  286. const fieldsQuery = this.queryBuilder.buildExploreQuery('FIELDS');
  287. return this.datasource
  288. .metricFindQuery(fieldsQuery)
  289. .then(this.transformToSegments(false))
  290. .catch(this.handleQueryError);
  291. }
  292. tagSegmentUpdated(segment: { value: any; type: string; cssClass: string }, index: number) {
  293. this.tagSegments[index] = segment;
  294. // handle remove tag condition
  295. if (segment.value === this.removeTagFilterSegment.value) {
  296. this.tagSegments.splice(index, 3);
  297. if (this.tagSegments.length === 0) {
  298. this.tagSegments.push(this.uiSegmentSrv.newPlusButton());
  299. } else if (this.tagSegments.length > 2) {
  300. this.tagSegments.splice(Math.max(index - 1, 0), 1);
  301. if (this.tagSegments[this.tagSegments.length - 1].type !== 'plus-button') {
  302. this.tagSegments.push(this.uiSegmentSrv.newPlusButton());
  303. }
  304. }
  305. } else {
  306. if (segment.type === 'plus-button') {
  307. if (index > 2) {
  308. this.tagSegments.splice(index, 0, this.uiSegmentSrv.newCondition('AND'));
  309. }
  310. this.tagSegments.push(this.uiSegmentSrv.newOperator('='));
  311. this.tagSegments.push(this.uiSegmentSrv.newFake('select tag value', 'value', 'query-segment-value'));
  312. segment.type = 'key';
  313. segment.cssClass = 'query-segment-key';
  314. }
  315. if (index + 1 === this.tagSegments.length) {
  316. this.tagSegments.push(this.uiSegmentSrv.newPlusButton());
  317. }
  318. }
  319. this.rebuildTargetTagConditions();
  320. }
  321. rebuildTargetTagConditions() {
  322. const tags: any[] = [];
  323. let tagIndex = 0;
  324. let tagOperator = '';
  325. _.each(this.tagSegments, (segment2, index) => {
  326. if (segment2.type === 'key') {
  327. if (tags.length === 0) {
  328. tags.push({});
  329. }
  330. tags[tagIndex].key = segment2.value;
  331. } else if (segment2.type === 'value') {
  332. tagOperator = this.getTagValueOperator(segment2.value, tags[tagIndex].operator);
  333. if (tagOperator) {
  334. this.tagSegments[index - 1] = this.uiSegmentSrv.newOperator(tagOperator);
  335. tags[tagIndex].operator = tagOperator;
  336. }
  337. tags[tagIndex].value = segment2.value;
  338. } else if (segment2.type === 'condition') {
  339. tags.push({ condition: segment2.value });
  340. tagIndex += 1;
  341. } else if (segment2.type === 'operator') {
  342. tags[tagIndex].operator = segment2.value;
  343. }
  344. });
  345. this.target.tags = tags;
  346. this.panelCtrl.refresh();
  347. }
  348. getTagValueOperator(tagValue: string, tagOperator: string): string {
  349. if (tagOperator !== '=~' && tagOperator !== '!~' && /^\/.*\/$/.test(tagValue)) {
  350. return '=~';
  351. } else if ((tagOperator === '=~' || tagOperator === '!~') && /^(?!\/.*\/$)/.test(tagValue)) {
  352. return '=';
  353. }
  354. return null;
  355. }
  356. getCollapsedText() {
  357. return this.queryModel.render(false);
  358. }
  359. }