query_ctrl.ts 9.0 KB

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