query_ctrl.ts 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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. var shiftBack = this.isShiftParamsBack(func);
  83. this.addFunctionParameter(func, astNode.value, index, shiftBack);
  84. break;
  85. case 'metric':
  86. if (this.segments.length > 0) {
  87. if (astNode.segments.length !== 1) {
  88. throw { message: 'Multiple metric params not supported, use text editor.' };
  89. }
  90. this.addFunctionParameter(func, astNode.segments[0].value, index, true);
  91. break;
  92. }
  93. this.segments = _.map(astNode.segments, segment => {
  94. return this.uiSegmentSrv.newSegment(segment);
  95. });
  96. }
  97. }
  98. isShiftParamsBack(func) {
  99. return func.def.name !== 'seriesByTag';
  100. }
  101. getSegmentPathUpTo(index) {
  102. var arr = this.segments.slice(0, index);
  103. return _.reduce(arr, function(result, segment) {
  104. return result ? (result + "." + segment.value) : segment.value;
  105. }, "");
  106. }
  107. checkOtherSegments(fromIndex) {
  108. if (fromIndex === 0) {
  109. this.segments.push(this.uiSegmentSrv.newSelectMetric());
  110. return;
  111. }
  112. var path = this.getSegmentPathUpTo(fromIndex + 1);
  113. if (path === "") {
  114. return Promise.resolve();
  115. }
  116. return this.datasource.metricFindQuery(path).then(segments => {
  117. if (segments.length === 0) {
  118. if (path !== '') {
  119. this.segments = this.segments.splice(0, fromIndex);
  120. this.segments.push(this.uiSegmentSrv.newSelectMetric());
  121. }
  122. } else if (segments[0].expandable) {
  123. if (this.segments.length === fromIndex) {
  124. this.segments.push(this.uiSegmentSrv.newSelectMetric());
  125. } else {
  126. return this.checkOtherSegments(fromIndex + 1);
  127. }
  128. }
  129. }).catch(err => {
  130. appEvents.emit('alert-error', ['Error', err]);
  131. });
  132. }
  133. setSegmentFocus(segmentIndex) {
  134. _.each(this.segments, (segment, index) => {
  135. segment.focus = segmentIndex === index;
  136. });
  137. }
  138. wrapFunction(target, func) {
  139. return func.render(target);
  140. }
  141. getAltSegments(index) {
  142. var query = index === 0 ? '*' : this.getSegmentPathUpTo(index) + '.*';
  143. var options = {range: this.panelCtrl.range, requestId: "get-alt-segments"};
  144. return this.datasource.metricFindQuery(query, options).then(segments => {
  145. var altSegments = _.map(segments, segment => {
  146. return this.uiSegmentSrv.newSegment({value: segment.text, expandable: segment.expandable});
  147. });
  148. if (altSegments.length === 0) { return altSegments; }
  149. // add template variables
  150. _.each(this.templateSrv.variables, variable => {
  151. altSegments.unshift(this.uiSegmentSrv.newSegment({
  152. type: 'template',
  153. value: '$' + variable.name,
  154. expandable: true,
  155. }));
  156. });
  157. // add wildcard option
  158. altSegments.unshift(this.uiSegmentSrv.newSegment('*'));
  159. return altSegments;
  160. }).catch(err => {
  161. return [];
  162. });
  163. }
  164. segmentValueChanged(segment, segmentIndex) {
  165. this.error = null;
  166. if (this.functions.length > 0 && this.functions[0].def.fake) {
  167. this.functions = [];
  168. }
  169. if (segment.expandable) {
  170. return this.checkOtherSegments(segmentIndex + 1).then(() => {
  171. this.setSegmentFocus(segmentIndex + 1);
  172. this.targetChanged();
  173. });
  174. } else {
  175. this.segments = this.segments.splice(0, segmentIndex + 1);
  176. }
  177. this.setSegmentFocus(segmentIndex + 1);
  178. this.targetChanged();
  179. }
  180. targetTextChanged() {
  181. this.updateModelTarget();
  182. this.refresh();
  183. }
  184. updateModelTarget() {
  185. // render query
  186. if (!this.target.textEditor) {
  187. var metricPath = this.getSegmentPathUpTo(this.segments.length);
  188. this.target.target = _.reduce(this.functions, this.wrapFunction, metricPath);
  189. }
  190. this.updateRenderedTarget(this.target);
  191. // loop through other queries and update targetFull as needed
  192. for (const target of this.panelCtrl.panel.targets || []) {
  193. if (target.refId !== this.target.refId) {
  194. this.updateRenderedTarget(target);
  195. }
  196. }
  197. }
  198. updateRenderedTarget(target) {
  199. // render nested query
  200. var targetsByRefId = _.keyBy(this.panelCtrl.panel.targets, 'refId');
  201. // no references to self
  202. delete targetsByRefId[target.refId];
  203. var nestedSeriesRefRegex = /\#([A-Z])/g;
  204. var targetWithNestedQueries = target.target;
  205. // Keep interpolating until there are no query references
  206. // The reason for the loop is that the referenced query might contain another reference to another query
  207. while (targetWithNestedQueries.match(nestedSeriesRefRegex)) {
  208. var updated = targetWithNestedQueries.replace(nestedSeriesRefRegex, (match, g1) => {
  209. var t = targetsByRefId[g1];
  210. if (!t) {
  211. return match;
  212. }
  213. // no circular references
  214. delete targetsByRefId[g1];
  215. return t.target;
  216. });
  217. if (updated === targetWithNestedQueries) {
  218. break;
  219. }
  220. targetWithNestedQueries = updated;
  221. }
  222. delete target.targetFull;
  223. if (target.target !== targetWithNestedQueries) {
  224. target.targetFull = targetWithNestedQueries;
  225. }
  226. }
  227. targetChanged() {
  228. if (this.error) {
  229. return;
  230. }
  231. var oldTarget = this.target.target;
  232. this.updateModelTarget();
  233. if (this.target.target !== oldTarget) {
  234. var lastSegment = this.segments.length > 0 ? this.segments[this.segments.length - 1] : {};
  235. if (lastSegment.value !== 'select metric') {
  236. this.panelCtrl.refresh();
  237. }
  238. }
  239. }
  240. removeFunction(func) {
  241. this.functions = _.without(this.functions, func);
  242. this.targetChanged();
  243. }
  244. addFunction(funcDef) {
  245. var newFunc = gfunc.createFuncInstance(funcDef, { withDefaultParams: true });
  246. newFunc.added = true;
  247. this.functions.push(newFunc);
  248. this.moveAliasFuncLast();
  249. this.smartlyHandleNewAliasByNode(newFunc);
  250. if (this.segments.length === 1 && this.segments[0].fake) {
  251. this.segments = [];
  252. }
  253. if (!newFunc.params.length && newFunc.added) {
  254. this.targetChanged();
  255. }
  256. }
  257. moveAliasFuncLast() {
  258. var aliasFunc = _.find(this.functions, function(func) {
  259. return func.def.name === 'alias' ||
  260. func.def.name === 'aliasByNode' ||
  261. func.def.name === 'aliasByMetric';
  262. });
  263. if (aliasFunc) {
  264. this.functions = _.without(this.functions, aliasFunc);
  265. this.functions.push(aliasFunc);
  266. }
  267. }
  268. smartlyHandleNewAliasByNode(func) {
  269. if (func.def.name !== 'aliasByNode') {
  270. return;
  271. }
  272. for (var i = 0; i < this.segments.length; i++) {
  273. if (this.segments[i].value.indexOf('*') >= 0) {
  274. func.params[0] = i;
  275. func.added = false;
  276. this.targetChanged();
  277. return;
  278. }
  279. }
  280. }
  281. }