query_ctrl.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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. return [];
  158. });
  159. }
  160. segmentValueChanged(segment, segmentIndex) {
  161. this.error = null;
  162. if (this.functions.length > 0 && this.functions[0].def.fake) {
  163. this.functions = [];
  164. }
  165. if (segment.expandable) {
  166. return this.checkOtherSegments(segmentIndex + 1).then(() => {
  167. this.setSegmentFocus(segmentIndex + 1);
  168. this.targetChanged();
  169. });
  170. } else {
  171. this.segments = this.segments.splice(0, segmentIndex + 1);
  172. }
  173. this.setSegmentFocus(segmentIndex + 1);
  174. this.targetChanged();
  175. }
  176. targetTextChanged() {
  177. this.updateModelTarget();
  178. this.refresh();
  179. }
  180. updateModelTarget() {
  181. // render query
  182. if (!this.target.textEditor) {
  183. var metricPath = this.getSegmentPathUpTo(this.segments.length);
  184. this.target.target = _.reduce(this.functions, this.wrapFunction, metricPath);
  185. }
  186. this.updateRenderedTarget(this.target);
  187. // loop through other queries and update targetFull as needed
  188. for (const target of this.panelCtrl.panel.targets || []) {
  189. if (target.refId !== this.target.refId) {
  190. this.updateRenderedTarget(target);
  191. }
  192. }
  193. }
  194. updateRenderedTarget(target) {
  195. // render nested query
  196. var targetsByRefId = _.keyBy(this.panelCtrl.panel.targets, 'refId');
  197. // no references to self
  198. delete targetsByRefId[target.refId];
  199. var nestedSeriesRefRegex = /\#([A-Z])/g;
  200. var targetWithNestedQueries = target.target;
  201. // Keep interpolating until there are no query references
  202. // The reason for the loop is that the referenced query might contain another reference to another query
  203. while (targetWithNestedQueries.match(nestedSeriesRefRegex)) {
  204. var updated = targetWithNestedQueries.replace(nestedSeriesRefRegex, (match, g1) => {
  205. var t = targetsByRefId[g1];
  206. if (!t) {
  207. return match;
  208. }
  209. // no circular references
  210. delete targetsByRefId[g1];
  211. return t.target;
  212. });
  213. if (updated === targetWithNestedQueries) {
  214. break;
  215. }
  216. targetWithNestedQueries = updated;
  217. }
  218. delete target.targetFull;
  219. if (target.target !== targetWithNestedQueries) {
  220. target.targetFull = targetWithNestedQueries;
  221. }
  222. }
  223. targetChanged() {
  224. if (this.error) {
  225. return;
  226. }
  227. var oldTarget = this.target.target;
  228. this.updateModelTarget();
  229. if (this.target.target !== oldTarget) {
  230. var lastSegment = this.segments.length > 0 ? this.segments[this.segments.length - 1] : {};
  231. if (lastSegment.value !== 'select metric') {
  232. this.panelCtrl.refresh();
  233. }
  234. }
  235. }
  236. removeFunction(func) {
  237. this.functions = _.without(this.functions, func);
  238. this.targetChanged();
  239. }
  240. addFunction(funcDef) {
  241. var newFunc = gfunc.createFuncInstance(funcDef, { withDefaultParams: true });
  242. newFunc.added = true;
  243. this.functions.push(newFunc);
  244. this.moveAliasFuncLast();
  245. this.smartlyHandleNewAliasByNode(newFunc);
  246. if (this.segments.length === 1 && this.segments[0].fake) {
  247. this.segments = [];
  248. }
  249. if (!newFunc.params.length && newFunc.added) {
  250. this.targetChanged();
  251. }
  252. }
  253. moveAliasFuncLast() {
  254. var aliasFunc = _.find(this.functions, function(func) {
  255. return func.def.name === 'alias' ||
  256. func.def.name === 'aliasByNode' ||
  257. func.def.name === 'aliasByMetric';
  258. });
  259. if (aliasFunc) {
  260. this.functions = _.without(this.functions, aliasFunc);
  261. this.functions.push(aliasFunc);
  262. }
  263. }
  264. smartlyHandleNewAliasByNode(func) {
  265. if (func.def.name !== 'aliasByNode') {
  266. return;
  267. }
  268. for (var i = 0; i < this.segments.length; i++) {
  269. if (this.segments[i].value.indexOf('*') >= 0) {
  270. func.params[0] = i;
  271. func.added = false;
  272. this.targetChanged();
  273. return;
  274. }
  275. }
  276. }
  277. }