graphite_query.ts 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. import _ from 'lodash';
  2. import gfunc from './gfunc';
  3. import { Parser } from './parser';
  4. export default class GraphiteQuery {
  5. target: any;
  6. functions: any[];
  7. segments: any[];
  8. tags: any[];
  9. error: any;
  10. seriesByTagUsed: boolean;
  11. checkOtherSegmentsIndex: number;
  12. removeTagValue: string;
  13. templateSrv: any;
  14. scopedVars: any;
  15. /** @ngInject */
  16. constructor(target, templateSrv?, scopedVars?) {
  17. this.target = target;
  18. this.parseTarget();
  19. this.removeTagValue = '-- remove tag --';
  20. }
  21. parseTarget() {
  22. this.functions = [];
  23. this.segments = [];
  24. this.tags = [];
  25. this.error = null;
  26. if (this.target.textEditor) {
  27. return;
  28. }
  29. var parser = new Parser(this.target.target);
  30. var astNode = parser.getAst();
  31. if (astNode === null) {
  32. this.checkOtherSegmentsIndex = 0;
  33. return;
  34. }
  35. if (astNode.type === 'error') {
  36. this.error = astNode.message + ' at position: ' + astNode.pos;
  37. this.target.textEditor = true;
  38. return;
  39. }
  40. try {
  41. this.parseTargetRecursive(astNode, null);
  42. } catch (err) {
  43. console.log('error parsing target:', err.message);
  44. this.error = err.message;
  45. this.target.textEditor = true;
  46. }
  47. this.checkOtherSegmentsIndex = this.segments.length - 1;
  48. this.checkForSeriesByTag();
  49. }
  50. checkForSeriesByTag() {
  51. let seriesByTagFunc = _.find(this.functions, func => func.def.name === 'seriesByTag');
  52. if (seriesByTagFunc) {
  53. this.seriesByTagUsed = true;
  54. seriesByTagFunc.hidden = true;
  55. let tags = this.splitSeriesByTagParams(seriesByTagFunc);
  56. this.tags = tags;
  57. }
  58. }
  59. getSegmentPathUpTo(index) {
  60. var arr = this.segments.slice(0, index);
  61. return _.reduce(
  62. arr,
  63. function(result, segment) {
  64. return result ? result + '.' + segment.value : segment.value;
  65. },
  66. ''
  67. );
  68. }
  69. parseTargetRecursive(astNode, func) {
  70. if (astNode === null) {
  71. return null;
  72. }
  73. switch (astNode.type) {
  74. case 'function':
  75. var innerFunc = gfunc.createFuncInstance(astNode.name, {
  76. withDefaultParams: false,
  77. });
  78. _.each(astNode.params, param => {
  79. this.parseTargetRecursive(param, innerFunc);
  80. });
  81. innerFunc.updateText();
  82. this.functions.push(innerFunc);
  83. break;
  84. case 'series-ref':
  85. if (this.segments.length > 0) {
  86. this.addFunctionParameter(func, astNode.value);
  87. } else {
  88. this.segments.push(astNode);
  89. }
  90. break;
  91. case 'bool':
  92. case 'string':
  93. case 'number':
  94. this.addFunctionParameter(func, astNode.value);
  95. break;
  96. case 'metric':
  97. if (this.segments.length > 0) {
  98. this.addFunctionParameter(func, _.join(_.map(astNode.segments, 'value'), '.'));
  99. } else {
  100. this.segments = astNode.segments;
  101. }
  102. break;
  103. }
  104. }
  105. updateSegmentValue(segment, index) {
  106. this.segments[index].value = segment.value;
  107. }
  108. addSelectMetricSegment() {
  109. this.segments.push({ value: 'select metric' });
  110. }
  111. addFunction(newFunc) {
  112. this.functions.push(newFunc);
  113. this.moveAliasFuncLast();
  114. }
  115. moveAliasFuncLast() {
  116. var aliasFunc = _.find(this.functions, function(func) {
  117. return func.def.name === 'alias' || func.def.name === 'aliasByNode' || func.def.name === 'aliasByMetric';
  118. });
  119. if (aliasFunc) {
  120. this.functions = _.without(this.functions, aliasFunc);
  121. this.functions.push(aliasFunc);
  122. }
  123. }
  124. addFunctionParameter(func, value) {
  125. if (func.params.length >= func.def.params.length) {
  126. throw { message: 'too many parameters for function ' + func.def.name };
  127. }
  128. func.params.push(value);
  129. }
  130. removeFunction(func) {
  131. this.functions = _.without(this.functions, func);
  132. }
  133. updateModelTarget(targets) {
  134. // render query
  135. if (!this.target.textEditor) {
  136. var metricPath = this.getSegmentPathUpTo(this.segments.length).replace(/\.select metric$/, '');
  137. this.target.target = _.reduce(this.functions, wrapFunction, metricPath);
  138. }
  139. this.updateRenderedTarget(this.target, targets);
  140. // loop through other queries and update targetFull as needed
  141. for (const target of targets || []) {
  142. if (target.refId !== this.target.refId) {
  143. this.updateRenderedTarget(target, targets);
  144. }
  145. }
  146. }
  147. updateRenderedTarget(target, targets) {
  148. // render nested query
  149. var targetsByRefId = _.keyBy(targets, 'refId');
  150. // no references to self
  151. delete targetsByRefId[target.refId];
  152. var nestedSeriesRefRegex = /\#([A-Z])/g;
  153. var targetWithNestedQueries = target.target;
  154. // Keep interpolating until there are no query references
  155. // The reason for the loop is that the referenced query might contain another reference to another query
  156. while (targetWithNestedQueries.match(nestedSeriesRefRegex)) {
  157. var updated = targetWithNestedQueries.replace(nestedSeriesRefRegex, (match, g1) => {
  158. var t = targetsByRefId[g1];
  159. if (!t) {
  160. return match;
  161. }
  162. // no circular references
  163. delete targetsByRefId[g1];
  164. return t.target;
  165. });
  166. if (updated === targetWithNestedQueries) {
  167. break;
  168. }
  169. targetWithNestedQueries = updated;
  170. }
  171. delete target.targetFull;
  172. if (target.target !== targetWithNestedQueries) {
  173. target.targetFull = targetWithNestedQueries;
  174. }
  175. }
  176. splitSeriesByTagParams(func) {
  177. const tagPattern = /([^\!=~]+)([\!=~]+)([^\!=~]+)/;
  178. return _.flatten(
  179. _.map(func.params, (param: string) => {
  180. let matches = tagPattern.exec(param);
  181. if (matches) {
  182. let tag = matches.slice(1);
  183. if (tag.length === 3) {
  184. return {
  185. key: tag[0],
  186. operator: tag[1],
  187. value: tag[2],
  188. };
  189. }
  190. }
  191. return [];
  192. })
  193. );
  194. }
  195. getSeriesByTagFuncIndex() {
  196. return _.findIndex(this.functions, func => func.def.name === 'seriesByTag');
  197. }
  198. getSeriesByTagFunc() {
  199. let seriesByTagFuncIndex = this.getSeriesByTagFuncIndex();
  200. if (seriesByTagFuncIndex >= 0) {
  201. return this.functions[seriesByTagFuncIndex];
  202. } else {
  203. return undefined;
  204. }
  205. }
  206. addTag(tag) {
  207. let newTagParam = renderTagString(tag);
  208. this.getSeriesByTagFunc().params.push(newTagParam);
  209. this.tags.push(tag);
  210. }
  211. removeTag(index) {
  212. this.getSeriesByTagFunc().params.splice(index, 1);
  213. this.tags.splice(index, 1);
  214. }
  215. updateTag(tag, tagIndex) {
  216. this.error = null;
  217. if (tag.key === this.removeTagValue) {
  218. this.removeTag(tagIndex);
  219. return;
  220. }
  221. let newTagParam = renderTagString(tag);
  222. this.getSeriesByTagFunc().params[tagIndex] = newTagParam;
  223. this.tags[tagIndex] = tag;
  224. }
  225. renderTagExpressions(excludeIndex = -1) {
  226. return _.compact(
  227. _.map(this.tags, (tagExpr, index) => {
  228. // Don't render tag that we want to lookup
  229. if (index !== excludeIndex) {
  230. return tagExpr.key + tagExpr.operator + tagExpr.value;
  231. }
  232. })
  233. );
  234. }
  235. }
  236. function wrapFunction(target, func) {
  237. return func.render(target);
  238. }
  239. function renderTagString(tag) {
  240. return tag.key + tag.operator + tag.value;
  241. }