query_ctrl.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. import './add_graphite_func';
  2. import './func_editor';
  3. import _ from 'lodash';
  4. import gfunc from './gfunc';
  5. import {Parser} from './parser';
  6. import {QueryCtrl} from 'app/plugins/sdk';
  7. import appEvents from 'app/core/app_events';
  8. const GRAPHITE_TAG_OPERATORS = ['=', '!=', '=~', '!=~'];
  9. export class GraphiteQueryCtrl extends QueryCtrl {
  10. static templateUrl = 'partials/query.editor.html';
  11. functions: any[];
  12. segments: any[];
  13. addTagSegments: any[];
  14. tags: any[];
  15. seriesByTagUsed: boolean;
  16. removeTagValue: string;
  17. /** @ngInject **/
  18. constructor($scope, $injector, private uiSegmentSrv, private templateSrv) {
  19. super($scope, $injector);
  20. if (this.target) {
  21. this.target.target = this.target.target || '';
  22. this.parseTarget();
  23. }
  24. this.removeTagValue = '-- remove tag --';
  25. }
  26. toggleEditorMode() {
  27. this.target.textEditor = !this.target.textEditor;
  28. this.parseTarget();
  29. }
  30. parseTarget() {
  31. this.functions = [];
  32. this.segments = [];
  33. this.error = null;
  34. if (this.target.textEditor) {
  35. return;
  36. }
  37. var parser = new Parser(this.target.target);
  38. var astNode = parser.getAst();
  39. if (astNode === null) {
  40. this.checkOtherSegments(0);
  41. return;
  42. }
  43. if (astNode.type === 'error') {
  44. this.error = astNode.message + " at position: " + astNode.pos;
  45. this.target.textEditor = true;
  46. return;
  47. }
  48. try {
  49. this.parseTargetRecursive(astNode, null, 0);
  50. } catch (err) {
  51. console.log('error parsing target:', err.message);
  52. this.error = err.message;
  53. this.target.textEditor = true;
  54. }
  55. this.checkOtherSegments(this.segments.length - 1);
  56. this.checkForSeriesByTag();
  57. }
  58. addFunctionParameter(func, value, index, shiftBack) {
  59. if (shiftBack) {
  60. index = Math.max(index - 1, 0);
  61. }
  62. func.params[index] = value;
  63. }
  64. parseTargetRecursive(astNode, func, index) {
  65. if (astNode === null) {
  66. return null;
  67. }
  68. switch (astNode.type) {
  69. case 'function':
  70. var innerFunc = gfunc.createFuncInstance(astNode.name, { withDefaultParams: false });
  71. _.each(astNode.params, (param, index) => {
  72. this.parseTargetRecursive(param, innerFunc, index);
  73. });
  74. innerFunc.updateText();
  75. this.functions.push(innerFunc);
  76. break;
  77. case 'series-ref':
  78. this.addFunctionParameter(func, astNode.value, index, this.segments.length > 0);
  79. break;
  80. case 'bool':
  81. case 'string':
  82. case 'number':
  83. if ((index-1) >= func.def.params.length) {
  84. throw { message: 'invalid number of parameters to method ' + func.def.name };
  85. }
  86. var shiftBack = this.isShiftParamsBack(func);
  87. this.addFunctionParameter(func, astNode.value, index, shiftBack);
  88. break;
  89. case 'metric':
  90. if (this.segments.length > 0) {
  91. if (astNode.segments.length !== 1) {
  92. throw { message: 'Multiple metric params not supported, use text editor.' };
  93. }
  94. this.addFunctionParameter(func, astNode.segments[0].value, index, true);
  95. break;
  96. }
  97. this.segments = _.map(astNode.segments, segment => {
  98. return this.uiSegmentSrv.newSegment(segment);
  99. });
  100. }
  101. }
  102. isShiftParamsBack(func) {
  103. return func.def.name !== 'seriesByTag';
  104. }
  105. getSegmentPathUpTo(index) {
  106. var arr = this.segments.slice(0, index);
  107. return _.reduce(arr, function(result, segment) {
  108. return result ? (result + "." + segment.value) : segment.value;
  109. }, "");
  110. }
  111. checkOtherSegments(fromIndex) {
  112. if (fromIndex === 0) {
  113. this.segments.push(this.uiSegmentSrv.newSelectMetric());
  114. return;
  115. }
  116. var path = this.getSegmentPathUpTo(fromIndex + 1);
  117. if (path === "") {
  118. return Promise.resolve();
  119. }
  120. return this.datasource.metricFindQuery(path).then(segments => {
  121. if (segments.length === 0) {
  122. if (path !== '') {
  123. this.segments = this.segments.splice(0, fromIndex);
  124. this.segments.push(this.uiSegmentSrv.newSelectMetric());
  125. }
  126. } else if (segments[0].expandable) {
  127. if (this.segments.length === fromIndex) {
  128. this.segments.push(this.uiSegmentSrv.newSelectMetric());
  129. } else {
  130. return this.checkOtherSegments(fromIndex + 1);
  131. }
  132. }
  133. }).catch(err => {
  134. appEvents.emit('alert-error', ['Error', err]);
  135. });
  136. }
  137. setSegmentFocus(segmentIndex) {
  138. _.each(this.segments, (segment, index) => {
  139. segment.focus = segmentIndex === index;
  140. });
  141. }
  142. wrapFunction(target, func) {
  143. return func.render(target);
  144. }
  145. getAltSegments(index) {
  146. var query = index === 0 ? '*' : this.getSegmentPathUpTo(index) + '.*';
  147. var options = {range: this.panelCtrl.range, requestId: "get-alt-segments"};
  148. return this.datasource.metricFindQuery(query, options).then(segments => {
  149. var altSegments = _.map(segments, segment => {
  150. return this.uiSegmentSrv.newSegment({value: segment.text, expandable: segment.expandable});
  151. });
  152. if (altSegments.length === 0) { return altSegments; }
  153. // add template variables
  154. _.each(this.templateSrv.variables, variable => {
  155. altSegments.unshift(this.uiSegmentSrv.newSegment({
  156. type: 'template',
  157. value: '$' + variable.name,
  158. expandable: true,
  159. }));
  160. });
  161. // add wildcard option
  162. altSegments.unshift(this.uiSegmentSrv.newSegment('*'));
  163. return altSegments;
  164. }).catch(err => {
  165. return [];
  166. });
  167. }
  168. segmentValueChanged(segment, segmentIndex) {
  169. this.error = null;
  170. if (this.functions.length > 0 && this.functions[0].def.fake) {
  171. this.functions = [];
  172. }
  173. if (segment.expandable) {
  174. return this.checkOtherSegments(segmentIndex + 1).then(() => {
  175. this.setSegmentFocus(segmentIndex + 1);
  176. this.targetChanged();
  177. });
  178. } else {
  179. this.segments = this.segments.splice(0, segmentIndex + 1);
  180. }
  181. this.setSegmentFocus(segmentIndex + 1);
  182. this.targetChanged();
  183. }
  184. targetTextChanged() {
  185. this.updateModelTarget();
  186. this.refresh();
  187. }
  188. updateModelTarget() {
  189. // render query
  190. if (!this.target.textEditor) {
  191. var metricPath = this.getSegmentPathUpTo(this.segments.length);
  192. this.target.target = _.reduce(this.functions, this.wrapFunction, metricPath);
  193. }
  194. this.updateRenderedTarget(this.target);
  195. // loop through other queries and update targetFull as needed
  196. for (const target of this.panelCtrl.panel.targets || []) {
  197. if (target.refId !== this.target.refId) {
  198. this.updateRenderedTarget(target);
  199. }
  200. }
  201. }
  202. updateRenderedTarget(target) {
  203. // render nested query
  204. var targetsByRefId = _.keyBy(this.panelCtrl.panel.targets, 'refId');
  205. // no references to self
  206. delete targetsByRefId[target.refId];
  207. var nestedSeriesRefRegex = /\#([A-Z])/g;
  208. var targetWithNestedQueries = target.target;
  209. // Keep interpolating until there are no query references
  210. // The reason for the loop is that the referenced query might contain another reference to another query
  211. while (targetWithNestedQueries.match(nestedSeriesRefRegex)) {
  212. var updated = targetWithNestedQueries.replace(nestedSeriesRefRegex, (match, g1) => {
  213. var t = targetsByRefId[g1];
  214. if (!t) {
  215. return match;
  216. }
  217. // no circular references
  218. delete targetsByRefId[g1];
  219. return t.target;
  220. });
  221. if (updated === targetWithNestedQueries) {
  222. break;
  223. }
  224. targetWithNestedQueries = updated;
  225. }
  226. delete target.targetFull;
  227. if (target.target !== targetWithNestedQueries) {
  228. target.targetFull = targetWithNestedQueries;
  229. }
  230. }
  231. targetChanged() {
  232. if (this.error) {
  233. return;
  234. }
  235. var oldTarget = this.target.target;
  236. this.updateModelTarget();
  237. if (this.target.target !== oldTarget) {
  238. var lastSegment = this.segments.length > 0 ? this.segments[this.segments.length - 1] : {};
  239. if (lastSegment.value !== 'select metric') {
  240. this.panelCtrl.refresh();
  241. }
  242. }
  243. }
  244. removeFunction(func) {
  245. this.functions = _.without(this.functions, func);
  246. this.targetChanged();
  247. }
  248. addFunction(funcDef) {
  249. var newFunc = gfunc.createFuncInstance(funcDef, { withDefaultParams: true });
  250. newFunc.added = true;
  251. this.functions.push(newFunc);
  252. this.moveAliasFuncLast();
  253. this.smartlyHandleNewAliasByNode(newFunc);
  254. if (this.segments.length === 1 && this.segments[0].fake) {
  255. this.segments = [];
  256. }
  257. if (!newFunc.params.length && newFunc.added) {
  258. this.targetChanged();
  259. }
  260. if (newFunc.def.name === 'seriesByTag') {
  261. this.parseTarget();
  262. }
  263. }
  264. moveAliasFuncLast() {
  265. var aliasFunc = _.find(this.functions, function(func) {
  266. return func.def.name === 'alias' ||
  267. func.def.name === 'aliasByNode' ||
  268. func.def.name === 'aliasByMetric';
  269. });
  270. if (aliasFunc) {
  271. this.functions = _.without(this.functions, aliasFunc);
  272. this.functions.push(aliasFunc);
  273. }
  274. }
  275. smartlyHandleNewAliasByNode(func) {
  276. if (func.def.name !== 'aliasByNode') {
  277. return;
  278. }
  279. for (var i = 0; i < this.segments.length; i++) {
  280. if (this.segments[i].value.indexOf('*') >= 0) {
  281. func.params[0] = i;
  282. func.added = false;
  283. this.targetChanged();
  284. return;
  285. }
  286. }
  287. }
  288. //////////////////////////////////
  289. // Graphite seriesByTag support //
  290. //////////////////////////////////
  291. checkForSeriesByTag() {
  292. let seriesByTagFunc = _.find(this.functions, (func) => func.def.name === 'seriesByTag');
  293. if (seriesByTagFunc) {
  294. this.seriesByTagUsed = true;
  295. let tags = this.splitSeriesByTagParams(seriesByTagFunc);
  296. this.tags = tags;
  297. this.fixTagSegments();
  298. }
  299. }
  300. splitSeriesByTagParams(func) {
  301. const tagPattern = /([^\!=~]+)([\!=~]+)([^\!=~]+)/;
  302. return _.flatten(_.map(func.params, (param: string) => {
  303. let matches = tagPattern.exec(param);
  304. if (matches) {
  305. let tag = matches.slice(1);
  306. if (tag.length === 3) {
  307. return {
  308. key: tag[0],
  309. operator: tag[1],
  310. value: tag[2]
  311. }
  312. }
  313. }
  314. return [];
  315. }));
  316. }
  317. getTags() {
  318. return this.datasource.getTags().then((values) => {
  319. let altTags = _.map(values, 'text');
  320. altTags.splice(0, 0, this.removeTagValue);
  321. return mapToDropdownOptions(altTags);
  322. });
  323. }
  324. getTagsAsSegments() {
  325. return this.datasource.getTags().then((values) => {
  326. return _.map(values, (val) => {
  327. return this.uiSegmentSrv.newSegment(val.text);
  328. });
  329. });
  330. }
  331. getTagOperators() {
  332. return mapToDropdownOptions(GRAPHITE_TAG_OPERATORS);
  333. }
  334. getTagValues(tag) {
  335. let tagKey = tag.key;
  336. return this.datasource.getTagValues(tagKey).then((values) => {
  337. let altValues = _.map(values, 'text');
  338. return mapToDropdownOptions(altValues);
  339. });
  340. }
  341. tagChanged(tag, tagIndex) {
  342. this.error = null;
  343. if (tag.key === this.removeTagValue) {
  344. this.removeTag(tagIndex);
  345. return;
  346. }
  347. let newTagParam = renderTagString(tag);
  348. this.getSeriesByTagFunc().params[tagIndex] = newTagParam;
  349. this.tags[tagIndex] = tag;
  350. this.targetChanged();
  351. }
  352. getSeriesByTagFuncIndex() {
  353. return _.findIndex(this.functions, (func) => func.def.name === 'seriesByTag');
  354. }
  355. getSeriesByTagFunc() {
  356. let seriesByTagFuncIndex = this.getSeriesByTagFuncIndex();
  357. if (seriesByTagFuncIndex >= 0) {
  358. return this.functions[seriesByTagFuncIndex];
  359. } else {
  360. return undefined;
  361. }
  362. }
  363. addNewTag(segment) {
  364. let newTagKey = segment.value;
  365. let newTag = {key: newTagKey, operator: '=', value: 'select tag value'};
  366. let newTagParam = renderTagString(newTag);
  367. this.getSeriesByTagFunc().params.push(newTagParam);
  368. this.tags.push(newTag);
  369. this.targetChanged();
  370. this.fixTagSegments();
  371. }
  372. removeTag(index) {
  373. this.getSeriesByTagFunc().params.splice(index, 1);
  374. this.tags.splice(index, 1);
  375. this.targetChanged();
  376. }
  377. fixTagSegments() {
  378. // Adding tag with the same name as just removed works incorrectly if single segment is used (instead of array)
  379. this.addTagSegments = [this.uiSegmentSrv.newPlusButton()];
  380. }
  381. showDelimiter(index) {
  382. return index !== this.tags.length - 1;
  383. }
  384. }
  385. function renderTagString(tag) {
  386. return tag.key + tag.operator + tag.value;
  387. }
  388. function mapToDropdownOptions(results) {
  389. return _.map(results, (value) => {
  390. return {text: value, value: value};
  391. });
  392. }