query_ctrl.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. ///<reference path="../../../headers/common.d.ts" />
  2. import './add_graphite_func';
  3. import './func_editor';
  4. import angular from 'angular';
  5. import _ from 'lodash';
  6. import moment from 'moment';
  7. import gfunc from './gfunc';
  8. import {Parser} from './parser';
  9. import {QueryCtrl} from 'app/plugins/sdk';
  10. import appEvents from 'app/core/app_events';
  11. export class GraphiteQueryCtrl extends QueryCtrl {
  12. static templateUrl = 'partials/query.editor.html';
  13. functions: any[];
  14. segments: 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. }
  23. toggleEditorMode() {
  24. this.target.textEditor = !this.target.textEditor;
  25. this.parseTarget();
  26. }
  27. parseTarget() {
  28. this.functions = [];
  29. this.segments = [];
  30. this.error = null;
  31. if (this.target.textEditor) {
  32. return;
  33. }
  34. var parser = new Parser(this.target.target);
  35. var astNode = parser.getAst();
  36. if (astNode === null) {
  37. this.checkOtherSegments(0);
  38. return;
  39. }
  40. if (astNode.type === 'error') {
  41. this.error = astNode.message + " at position: " + astNode.pos;
  42. this.target.textEditor = true;
  43. return;
  44. }
  45. try {
  46. this.parseTargetRecursive(astNode, null, 0);
  47. } catch (err) {
  48. console.log('error parsing target:', err.message);
  49. this.error = err.message;
  50. this.target.textEditor = true;
  51. }
  52. this.checkOtherSegments(this.segments.length - 1);
  53. }
  54. addFunctionParameter(func, value, index, shiftBack) {
  55. if (shiftBack) {
  56. index = Math.max(index - 1, 0);
  57. }
  58. func.params[index] = value;
  59. }
  60. parseTargetRecursive(astNode, func, index) {
  61. if (astNode === null) {
  62. return null;
  63. }
  64. switch (astNode.type) {
  65. case 'function':
  66. var innerFunc = gfunc.createFuncInstance(astNode.name, { withDefaultParams: false });
  67. _.each(astNode.params, (param, index) => {
  68. this.parseTargetRecursive(param, innerFunc, index);
  69. });
  70. innerFunc.updateText();
  71. this.functions.push(innerFunc);
  72. break;
  73. case 'series-ref':
  74. this.addFunctionParameter(func, astNode.value, index, this.segments.length > 0);
  75. break;
  76. case 'bool':
  77. case 'string':
  78. case 'number':
  79. if ((index-1) >= func.def.params.length) {
  80. throw { message: 'invalid number of parameters to method ' + func.def.name };
  81. }
  82. this.addFunctionParameter(func, astNode.value, index, true);
  83. break;
  84. case 'metric':
  85. if (this.segments.length > 0) {
  86. if (astNode.segments.length !== 1) {
  87. throw { message: 'Multiple metric params not supported, use text editor.' };
  88. }
  89. this.addFunctionParameter(func, astNode.segments[0].value, index, true);
  90. break;
  91. }
  92. this.segments = _.map(astNode.segments, segment => {
  93. return this.uiSegmentSrv.newSegment(segment);
  94. });
  95. }
  96. }
  97. getSegmentPathUpTo(index) {
  98. var arr = this.segments.slice(0, index);
  99. return _.reduce(arr, function(result, segment) {
  100. return result ? (result + "." + segment.value) : segment.value;
  101. }, "");
  102. }
  103. checkOtherSegments(fromIndex) {
  104. if (fromIndex === 0) {
  105. this.segments.push(this.uiSegmentSrv.newSelectMetric());
  106. return;
  107. }
  108. var path = this.getSegmentPathUpTo(fromIndex + 1);
  109. if (path === "") {
  110. return Promise.resolve();
  111. }
  112. return this.datasource.metricFindQuery(path).then(segments => {
  113. if (segments.length === 0) {
  114. if (path !== '') {
  115. this.segments = this.segments.splice(0, fromIndex);
  116. this.segments.push(this.uiSegmentSrv.newSelectMetric());
  117. }
  118. } else if (segments[0].expandable) {
  119. if (this.segments.length === fromIndex) {
  120. this.segments.push(this.uiSegmentSrv.newSelectMetric());
  121. } else {
  122. return this.checkOtherSegments(fromIndex + 1);
  123. }
  124. }
  125. }).catch(err => {
  126. appEvents.emit('alert-error', ['Error', err]);
  127. });
  128. }
  129. setSegmentFocus(segmentIndex) {
  130. _.each(this.segments, (segment, index) => {
  131. segment.focus = segmentIndex === index;
  132. });
  133. }
  134. wrapFunction(target, func) {
  135. return func.render(target);
  136. }
  137. getAltSegments(index) {
  138. var query = index === 0 ? '*' : this.getSegmentPathUpTo(index) + '.*';
  139. var options = {range: this.panelCtrl.range, requestId: "get-alt-segments"};
  140. return this.datasource.metricFindQuery(query, options).then(segments => {
  141. var altSegments = _.map(segments, segment => {
  142. return this.uiSegmentSrv.newSegment({value: segment.text, expandable: segment.expandable});
  143. });
  144. if (altSegments.length === 0) { return altSegments; }
  145. // add template variables
  146. _.each(this.templateSrv.variables, variable => {
  147. altSegments.unshift(this.uiSegmentSrv.newSegment({
  148. type: 'template',
  149. value: '$' + variable.name,
  150. expandable: true,
  151. }));
  152. });
  153. // add wildcard option
  154. altSegments.unshift(this.uiSegmentSrv.newSegment('*'));
  155. return altSegments;
  156. }).catch(err => {
  157. appEvents.emit('alert-error', ['Error', 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. }