query_ctrl.ts 8.8 KB

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