query_ctrl.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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. /** @ngInject **/
  13. constructor($scope, $injector, private uiSegmentSrv, private templateSrv) {
  14. super($scope, $injector);
  15. if (this.target) {
  16. this.target.target = this.target.target || '';
  17. this.parseTarget();
  18. }
  19. }
  20. toggleEditorMode() {
  21. this.target.textEditor = !this.target.textEditor;
  22. this.parseTarget();
  23. }
  24. parseTarget() {
  25. this.functions = [];
  26. this.segments = [];
  27. this.error = null;
  28. if (this.target.textEditor) {
  29. return;
  30. }
  31. var parser = new Parser(this.target.target);
  32. var astNode = parser.getAst();
  33. if (astNode === null) {
  34. this.checkOtherSegments(0);
  35. return;
  36. }
  37. if (astNode.type === 'error') {
  38. this.error = astNode.message + " at position: " + astNode.pos;
  39. this.target.textEditor = true;
  40. return;
  41. }
  42. try {
  43. this.parseTargetRecursive(astNode, null, 0);
  44. } catch (err) {
  45. console.log('error parsing target:', err.message);
  46. this.error = err.message;
  47. this.target.textEditor = true;
  48. }
  49. this.checkOtherSegments(this.segments.length - 1);
  50. }
  51. addFunctionParameter(func, value, index, shiftBack) {
  52. if (shiftBack) {
  53. index = Math.max(index - 1, 0);
  54. }
  55. func.params[index] = value;
  56. }
  57. parseTargetRecursive(astNode, func, index) {
  58. if (astNode === null) {
  59. return null;
  60. }
  61. switch (astNode.type) {
  62. case 'function':
  63. var innerFunc = gfunc.createFuncInstance(astNode.name, { withDefaultParams: false });
  64. _.each(astNode.params, (param, index) => {
  65. this.parseTargetRecursive(param, innerFunc, index);
  66. });
  67. innerFunc.updateText();
  68. this.functions.push(innerFunc);
  69. break;
  70. case 'series-ref':
  71. this.addFunctionParameter(func, astNode.value, index, this.segments.length > 0);
  72. break;
  73. case 'bool':
  74. case 'string':
  75. case 'number':
  76. if ((index-1) >= func.def.params.length) {
  77. throw { message: 'invalid number of parameters to method ' + func.def.name };
  78. }
  79. var shiftBack = this.isShiftParamsBack(func);
  80. this.addFunctionParameter(func, astNode.value, index, shiftBack);
  81. break;
  82. case 'metric':
  83. if (this.segments.length > 0) {
  84. if (astNode.segments.length !== 1) {
  85. throw { message: 'Multiple metric params not supported, use text editor.' };
  86. }
  87. this.addFunctionParameter(func, astNode.segments[0].value, index, true);
  88. break;
  89. }
  90. this.segments = _.map(astNode.segments, segment => {
  91. return this.uiSegmentSrv.newSegment(segment);
  92. });
  93. }
  94. }
  95. isShiftParamsBack(func) {
  96. return func.def.name !== 'seriesByTag';
  97. }
  98. getSegmentPathUpTo(index) {
  99. var arr = this.segments.slice(0, index);
  100. return _.reduce(arr, function(result, segment) {
  101. return result ? (result + "." + segment.value) : segment.value;
  102. }, "");
  103. }
  104. checkOtherSegments(fromIndex) {
  105. if (fromIndex === 0) {
  106. this.segments.push(this.uiSegmentSrv.newSelectMetric());
  107. return;
  108. }
  109. var path = this.getSegmentPathUpTo(fromIndex + 1);
  110. if (path === "") {
  111. return Promise.resolve();
  112. }
  113. return this.datasource.metricFindQuery(path).then(segments => {
  114. if (segments.length === 0) {
  115. if (path !== '') {
  116. this.segments = this.segments.splice(0, fromIndex);
  117. this.segments.push(this.uiSegmentSrv.newSelectMetric());
  118. }
  119. } else if (segments[0].expandable) {
  120. if (this.segments.length === fromIndex) {
  121. this.segments.push(this.uiSegmentSrv.newSelectMetric());
  122. } else {
  123. return this.checkOtherSegments(fromIndex + 1);
  124. }
  125. }
  126. }).catch(err => {
  127. appEvents.emit('alert-error', ['Error', err]);
  128. });
  129. }
  130. setSegmentFocus(segmentIndex) {
  131. _.each(this.segments, (segment, index) => {
  132. segment.focus = segmentIndex === index;
  133. });
  134. }
  135. wrapFunction(target, func) {
  136. return func.render(target);
  137. }
  138. getAltSegments(index) {
  139. var query = index === 0 ? '*' : this.getSegmentPathUpTo(index) + '.*';
  140. var options = {range: this.panelCtrl.range, requestId: "get-alt-segments"};
  141. return this.datasource.metricFindQuery(query, options).then(segments => {
  142. var altSegments = _.map(segments, segment => {
  143. return this.uiSegmentSrv.newSegment({value: segment.text, expandable: segment.expandable});
  144. });
  145. if (altSegments.length === 0) { return altSegments; }
  146. // add template variables
  147. _.each(this.templateSrv.variables, variable => {
  148. altSegments.unshift(this.uiSegmentSrv.newSegment({
  149. type: 'template',
  150. value: '$' + variable.name,
  151. expandable: true,
  152. }));
  153. });
  154. // add wildcard option
  155. altSegments.unshift(this.uiSegmentSrv.newSegment('*'));
  156. return altSegments;
  157. }).catch(err => {
  158. return [];
  159. });
  160. }
  161. segmentValueChanged(segment, segmentIndex) {
  162. this.error = null;
  163. if (this.functions.length > 0 && this.functions[0].def.fake) {
  164. this.functions = [];
  165. }
  166. if (segment.expandable) {
  167. return this.checkOtherSegments(segmentIndex + 1).then(() => {
  168. this.setSegmentFocus(segmentIndex + 1);
  169. this.targetChanged();
  170. });
  171. } else {
  172. this.segments = this.segments.splice(0, segmentIndex + 1);
  173. }
  174. this.setSegmentFocus(segmentIndex + 1);
  175. this.targetChanged();
  176. }
  177. targetTextChanged() {
  178. this.updateModelTarget();
  179. this.refresh();
  180. }
  181. updateModelTarget() {
  182. // render query
  183. if (!this.target.textEditor) {
  184. var metricPath = this.getSegmentPathUpTo(this.segments.length);
  185. this.target.target = _.reduce(this.functions, this.wrapFunction, metricPath);
  186. }
  187. this.updateRenderedTarget(this.target);
  188. // loop through other queries and update targetFull as needed
  189. for (const target of this.panelCtrl.panel.targets || []) {
  190. if (target.refId !== this.target.refId) {
  191. this.updateRenderedTarget(target);
  192. }
  193. }
  194. }
  195. updateRenderedTarget(target) {
  196. // render nested query
  197. var targetsByRefId = _.keyBy(this.panelCtrl.panel.targets, 'refId');
  198. // no references to self
  199. delete targetsByRefId[target.refId];
  200. var nestedSeriesRefRegex = /\#([A-Z])/g;
  201. var targetWithNestedQueries = target.target;
  202. // Keep interpolating until there are no query references
  203. // The reason for the loop is that the referenced query might contain another reference to another query
  204. while (targetWithNestedQueries.match(nestedSeriesRefRegex)) {
  205. var updated = targetWithNestedQueries.replace(nestedSeriesRefRegex, (match, g1) => {
  206. var t = targetsByRefId[g1];
  207. if (!t) {
  208. return match;
  209. }
  210. // no circular references
  211. delete targetsByRefId[g1];
  212. return t.target;
  213. });
  214. if (updated === targetWithNestedQueries) {
  215. break;
  216. }
  217. targetWithNestedQueries = updated;
  218. }
  219. delete target.targetFull;
  220. if (target.target !== targetWithNestedQueries) {
  221. target.targetFull = targetWithNestedQueries;
  222. }
  223. }
  224. targetChanged() {
  225. if (this.error) {
  226. return;
  227. }
  228. var oldTarget = this.target.target;
  229. this.updateModelTarget();
  230. if (this.target.target !== oldTarget) {
  231. var lastSegment = this.segments.length > 0 ? this.segments[this.segments.length - 1] : {};
  232. if (lastSegment.value !== 'select metric') {
  233. this.panelCtrl.refresh();
  234. }
  235. }
  236. }
  237. removeFunction(func) {
  238. this.functions = _.without(this.functions, func);
  239. this.targetChanged();
  240. }
  241. addFunction(funcDef) {
  242. var newFunc = gfunc.createFuncInstance(funcDef, { withDefaultParams: true });
  243. newFunc.added = true;
  244. this.functions.push(newFunc);
  245. this.moveAliasFuncLast();
  246. this.smartlyHandleNewAliasByNode(newFunc);
  247. if (this.segments.length === 1 && this.segments[0].fake) {
  248. this.segments = [];
  249. }
  250. if (!newFunc.params.length && newFunc.added) {
  251. this.targetChanged();
  252. }
  253. }
  254. moveAliasFuncLast() {
  255. var aliasFunc = _.find(this.functions, function(func) {
  256. return func.def.name === 'alias' ||
  257. func.def.name === 'aliasByNode' ||
  258. func.def.name === 'aliasByMetric';
  259. });
  260. if (aliasFunc) {
  261. this.functions = _.without(this.functions, aliasFunc);
  262. this.functions.push(aliasFunc);
  263. }
  264. }
  265. smartlyHandleNewAliasByNode(func) {
  266. if (func.def.name !== 'aliasByNode') {
  267. return;
  268. }
  269. for (var i = 0; i < this.segments.length; i++) {
  270. if (this.segments[i].value.indexOf('*') >= 0) {
  271. func.params[0] = i;
  272. func.added = false;
  273. this.targetChanged();
  274. return;
  275. }
  276. }
  277. }
  278. }