query_ctrl.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. import './add_graphite_func';
  2. import './func_editor';
  3. import _ from 'lodash';
  4. import gfunc from './gfunc';
  5. import {Parser} from './parser';
  6. import {QueryCtrl} from 'app/plugins/sdk';
  7. import appEvents from 'app/core/app_events';
  8. export class GraphiteQueryCtrl extends QueryCtrl {
  9. static templateUrl = 'partials/query.editor.html';
  10. functions: any[];
  11. segments: any[];
  12. tagSegments: any[];
  13. seriesByTagUsed: boolean;
  14. removeTagSegment: any;
  15. /** @ngInject **/
  16. constructor($scope, $injector, private uiSegmentSrv, private templateSrv) {
  17. super($scope, $injector);
  18. if (this.target) {
  19. this.target.target = this.target.target || '';
  20. this.parseTarget();
  21. }
  22. this.removeTagSegment = uiSegmentSrv.newSegment({fake: true, value: '-- remove tag --'});
  23. }
  24. toggleEditorMode() {
  25. this.target.textEditor = !this.target.textEditor;
  26. this.parseTarget();
  27. }
  28. parseTarget() {
  29. this.functions = [];
  30. this.segments = [];
  31. this.error = null;
  32. if (this.target.textEditor) {
  33. return;
  34. }
  35. var parser = new Parser(this.target.target);
  36. var astNode = parser.getAst();
  37. if (astNode === null) {
  38. this.checkOtherSegments(0);
  39. return;
  40. }
  41. if (astNode.type === 'error') {
  42. this.error = astNode.message + " at position: " + astNode.pos;
  43. this.target.textEditor = true;
  44. return;
  45. }
  46. try {
  47. this.parseTargetRecursive(astNode, null, 0);
  48. } catch (err) {
  49. console.log('error parsing target:', err.message);
  50. this.error = err.message;
  51. this.target.textEditor = true;
  52. }
  53. this.checkOtherSegments(this.segments.length - 1);
  54. this.checkForSeriesByTag();
  55. }
  56. addFunctionParameter(func, value, index, shiftBack) {
  57. if (shiftBack) {
  58. index = Math.max(index - 1, 0);
  59. }
  60. func.params[index] = value;
  61. }
  62. parseTargetRecursive(astNode, func, index) {
  63. if (astNode === null) {
  64. return null;
  65. }
  66. switch (astNode.type) {
  67. case 'function':
  68. var innerFunc = gfunc.createFuncInstance(astNode.name, { withDefaultParams: false });
  69. _.each(astNode.params, (param, index) => {
  70. this.parseTargetRecursive(param, innerFunc, index);
  71. });
  72. innerFunc.updateText();
  73. this.functions.push(innerFunc);
  74. break;
  75. case 'series-ref':
  76. this.addFunctionParameter(func, astNode.value, index, this.segments.length > 0);
  77. break;
  78. case 'bool':
  79. case 'string':
  80. case 'number':
  81. if ((index-1) >= func.def.params.length) {
  82. throw { message: 'invalid number of parameters to method ' + func.def.name };
  83. }
  84. var shiftBack = this.isShiftParamsBack(func);
  85. this.addFunctionParameter(func, astNode.value, index, shiftBack);
  86. break;
  87. case 'metric':
  88. if (this.segments.length > 0) {
  89. if (astNode.segments.length !== 1) {
  90. throw { message: 'Multiple metric params not supported, use text editor.' };
  91. }
  92. this.addFunctionParameter(func, astNode.segments[0].value, index, true);
  93. break;
  94. }
  95. this.segments = _.map(astNode.segments, segment => {
  96. return this.uiSegmentSrv.newSegment(segment);
  97. });
  98. }
  99. }
  100. isShiftParamsBack(func) {
  101. return func.def.name !== 'seriesByTag';
  102. }
  103. checkForSeriesByTag() {
  104. let seriesByTagFunc = _.find(this.functions, (func) => func.def.name === 'seriesByTag');
  105. if (seriesByTagFunc) {
  106. this.seriesByTagUsed = true;
  107. let tags = this.splitSeriesByTagParams(seriesByTagFunc);
  108. this.tagSegments = [];
  109. _.each(tags, (tag) => {
  110. this.tagSegments.push(this.uiSegmentSrv.newKey(tag.key));
  111. this.tagSegments.push(this.uiSegmentSrv.newOperator(tag.operator));
  112. this.tagSegments.push(this.uiSegmentSrv.newKeyValue(tag.value));
  113. });
  114. this.fixTagSegments();
  115. }
  116. }
  117. splitSeriesByTagParams(func) {
  118. const tagPattern = /([^\!=~]+)([\!=~]+)([^\!=~]+)/;
  119. return _.flatten(_.map(func.params, (param: string) => {
  120. let matches = tagPattern.exec(param);
  121. if (matches) {
  122. let tag = matches.slice(1);
  123. if (tag.length === 3) {
  124. return {
  125. key: tag[0],
  126. operator: tag[1],
  127. value: tag[2]
  128. }
  129. }
  130. }
  131. return [];
  132. }));
  133. }
  134. getSegmentPathUpTo(index) {
  135. var arr = this.segments.slice(0, index);
  136. return _.reduce(arr, function(result, segment) {
  137. return result ? (result + "." + segment.value) : segment.value;
  138. }, "");
  139. }
  140. checkOtherSegments(fromIndex) {
  141. if (fromIndex === 0) {
  142. this.segments.push(this.uiSegmentSrv.newSelectMetric());
  143. return;
  144. }
  145. var path = this.getSegmentPathUpTo(fromIndex + 1);
  146. if (path === "") {
  147. return Promise.resolve();
  148. }
  149. return this.datasource.metricFindQuery(path).then(segments => {
  150. if (segments.length === 0) {
  151. if (path !== '') {
  152. this.segments = this.segments.splice(0, fromIndex);
  153. this.segments.push(this.uiSegmentSrv.newSelectMetric());
  154. }
  155. } else if (segments[0].expandable) {
  156. if (this.segments.length === fromIndex) {
  157. this.segments.push(this.uiSegmentSrv.newSelectMetric());
  158. } else {
  159. return this.checkOtherSegments(fromIndex + 1);
  160. }
  161. }
  162. }).catch(err => {
  163. appEvents.emit('alert-error', ['Error', err]);
  164. });
  165. }
  166. setSegmentFocus(segmentIndex) {
  167. _.each(this.segments, (segment, index) => {
  168. segment.focus = segmentIndex === index;
  169. });
  170. }
  171. wrapFunction(target, func) {
  172. return func.render(target);
  173. }
  174. getAltTagSegments(index) {
  175. let paramPartIndex = getParamPartIndex(index);
  176. if (paramPartIndex === 1) {
  177. // Operator
  178. let operators = ['=', '!=', '=~', '!=~'];
  179. let segments = _.map(operators, (operator) => this.uiSegmentSrv.newOperator(operator));
  180. return Promise.resolve(segments);
  181. } else if (paramPartIndex === 0) {
  182. // Tag
  183. return this.datasource.getTags().then(segments => {
  184. let altSegments = _.map(segments, segment => {
  185. return this.uiSegmentSrv.newSegment({value: segment.text, expandable: false});
  186. });
  187. altSegments.splice(0, 0, _.cloneDeep(this.removeTagSegment));
  188. return altSegments;
  189. });
  190. } else {
  191. // Tag value
  192. let relatedTagSegmentIndex = getRelatedTagSegmentIndex(index);
  193. let tag = this.tagSegments[relatedTagSegmentIndex].value;
  194. return this.datasource.getTagValues(tag).then(segments => {
  195. let altSegments = _.map(segments, segment => {
  196. return this.uiSegmentSrv.newSegment({value: segment.text, expandable: false});
  197. });
  198. return altSegments;
  199. });
  200. }
  201. }
  202. getAltSegments(index) {
  203. var query = index === 0 ? '*' : this.getSegmentPathUpTo(index) + '.*';
  204. var options = {range: this.panelCtrl.range, requestId: "get-alt-segments"};
  205. return this.datasource.metricFindQuery(query, options).then(segments => {
  206. var altSegments = _.map(segments, segment => {
  207. return this.uiSegmentSrv.newSegment({value: segment.text, expandable: segment.expandable});
  208. });
  209. if (altSegments.length === 0) { return altSegments; }
  210. // add template variables
  211. _.each(this.templateSrv.variables, variable => {
  212. altSegments.unshift(this.uiSegmentSrv.newSegment({
  213. type: 'template',
  214. value: '$' + variable.name,
  215. expandable: true,
  216. }));
  217. });
  218. // add wildcard option
  219. altSegments.unshift(this.uiSegmentSrv.newSegment('*'));
  220. return altSegments;
  221. }).catch(err => {
  222. return [];
  223. });
  224. }
  225. segmentValueChanged(segment, segmentIndex) {
  226. this.error = null;
  227. if (this.functions.length > 0 && this.functions[0].def.fake) {
  228. this.functions = [];
  229. }
  230. if (segment.expandable) {
  231. return this.checkOtherSegments(segmentIndex + 1).then(() => {
  232. this.setSegmentFocus(segmentIndex + 1);
  233. this.targetChanged();
  234. });
  235. } else {
  236. this.segments = this.segments.splice(0, segmentIndex + 1);
  237. }
  238. this.setSegmentFocus(segmentIndex + 1);
  239. this.targetChanged();
  240. }
  241. tagSegmentChanged(tagSegment, segmentIndex) {
  242. this.error = null;
  243. if (tagSegment.value === this.removeTagSegment.value) {
  244. this.removeTag(segmentIndex);
  245. return;
  246. }
  247. if (tagSegment.type === 'plus-button') {
  248. let newTag = {key: tagSegment.value, operator: '=', value: 'select tag value'};
  249. this.tagSegments.splice(this.tagSegments.length - 1, 1);
  250. this.addNewTag(newTag);
  251. }
  252. let paramIndex = getParamIndex(segmentIndex);
  253. let newTagParam = this.renderTagParam(segmentIndex);
  254. this.functions[this.getSeriesByTagFuncIndex()].params[paramIndex] = newTagParam;
  255. this.targetChanged();
  256. this.parseTarget();
  257. }
  258. getSeriesByTagFuncIndex() {
  259. return _.findIndex(this.functions, (func) => func.def.name === 'seriesByTag');
  260. }
  261. addNewTag(tag) {
  262. this.tagSegments.push(this.uiSegmentSrv.newKey(tag.key));
  263. this.tagSegments.push(this.uiSegmentSrv.newOperator(tag.operator));
  264. this.tagSegments.push(this.uiSegmentSrv.newKeyValue(tag.value));
  265. }
  266. removeTag(index) {
  267. let paramIndex = getParamIndex(index);
  268. this.tagSegments.splice(index, 3);
  269. this.functions[this.getSeriesByTagFuncIndex()].params.splice(paramIndex, 1);
  270. this.targetChanged();
  271. this.parseTarget();
  272. }
  273. renderTagParam(segmentIndex) {
  274. let tagIndex = getRelatedTagSegmentIndex(segmentIndex)
  275. return _.map(this.tagSegments.slice(tagIndex, tagIndex + 3), (segment) => segment.value).join('');
  276. }
  277. targetTextChanged() {
  278. this.updateModelTarget();
  279. this.refresh();
  280. }
  281. updateModelTarget() {
  282. // render query
  283. if (!this.target.textEditor) {
  284. var metricPath = this.getSegmentPathUpTo(this.segments.length);
  285. this.target.target = _.reduce(this.functions, this.wrapFunction, metricPath);
  286. }
  287. this.updateRenderedTarget(this.target);
  288. // loop through other queries and update targetFull as needed
  289. for (const target of this.panelCtrl.panel.targets || []) {
  290. if (target.refId !== this.target.refId) {
  291. this.updateRenderedTarget(target);
  292. }
  293. }
  294. }
  295. updateRenderedTarget(target) {
  296. // render nested query
  297. var targetsByRefId = _.keyBy(this.panelCtrl.panel.targets, 'refId');
  298. // no references to self
  299. delete targetsByRefId[target.refId];
  300. var nestedSeriesRefRegex = /\#([A-Z])/g;
  301. var targetWithNestedQueries = target.target;
  302. // Keep interpolating until there are no query references
  303. // The reason for the loop is that the referenced query might contain another reference to another query
  304. while (targetWithNestedQueries.match(nestedSeriesRefRegex)) {
  305. var updated = targetWithNestedQueries.replace(nestedSeriesRefRegex, (match, g1) => {
  306. var t = targetsByRefId[g1];
  307. if (!t) {
  308. return match;
  309. }
  310. // no circular references
  311. delete targetsByRefId[g1];
  312. return t.target;
  313. });
  314. if (updated === targetWithNestedQueries) {
  315. break;
  316. }
  317. targetWithNestedQueries = updated;
  318. }
  319. delete target.targetFull;
  320. if (target.target !== targetWithNestedQueries) {
  321. target.targetFull = targetWithNestedQueries;
  322. }
  323. }
  324. targetChanged() {
  325. if (this.error) {
  326. return;
  327. }
  328. var oldTarget = this.target.target;
  329. this.updateModelTarget();
  330. if (this.target.target !== oldTarget) {
  331. var lastSegment = this.segments.length > 0 ? this.segments[this.segments.length - 1] : {};
  332. if (lastSegment.value !== 'select metric') {
  333. this.panelCtrl.refresh();
  334. }
  335. }
  336. }
  337. removeFunction(func) {
  338. this.functions = _.without(this.functions, func);
  339. this.targetChanged();
  340. }
  341. addFunction(funcDef) {
  342. var newFunc = gfunc.createFuncInstance(funcDef, { withDefaultParams: true });
  343. newFunc.added = true;
  344. this.functions.push(newFunc);
  345. this.moveAliasFuncLast();
  346. this.smartlyHandleNewAliasByNode(newFunc);
  347. if (this.segments.length === 1 && this.segments[0].fake) {
  348. this.segments = [];
  349. }
  350. if (!newFunc.params.length && newFunc.added) {
  351. this.targetChanged();
  352. }
  353. if (newFunc.def.name === 'seriesByTag') {
  354. this.parseTarget();
  355. }
  356. }
  357. moveAliasFuncLast() {
  358. var aliasFunc = _.find(this.functions, function(func) {
  359. return func.def.name === 'alias' ||
  360. func.def.name === 'aliasByNode' ||
  361. func.def.name === 'aliasByMetric';
  362. });
  363. if (aliasFunc) {
  364. this.functions = _.without(this.functions, aliasFunc);
  365. this.functions.push(aliasFunc);
  366. }
  367. }
  368. smartlyHandleNewAliasByNode(func) {
  369. if (func.def.name !== 'aliasByNode') {
  370. return;
  371. }
  372. for (var i = 0; i < this.segments.length; i++) {
  373. if (this.segments[i].value.indexOf('*') >= 0) {
  374. func.params[0] = i;
  375. func.added = false;
  376. this.targetChanged();
  377. return;
  378. }
  379. }
  380. }
  381. fixTagSegments() {
  382. var count = this.tagSegments.length;
  383. var lastSegment = this.tagSegments[Math.max(count-1, 0)];
  384. if (!lastSegment || lastSegment.type !== 'plus-button') {
  385. this.tagSegments.push(this.uiSegmentSrv.newPlusButton());
  386. }
  387. }
  388. showDelimiter(index) {
  389. return getParamPartIndex(index) === 2 && index !== this.tagSegments.length - 2;
  390. }
  391. }
  392. function getParamIndex(segmentIndex) {
  393. return Math.floor(segmentIndex / 3);
  394. }
  395. function getParamPartIndex(segmentIndex) {
  396. return segmentIndex % 3;
  397. }
  398. function getRelatedTagSegmentIndex(segmentIndex) {
  399. return getParamIndex(segmentIndex) * 3;
  400. }