graphite_query.ts 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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(arr, function(result, segment) {
  62. return result ? (result + "." + segment.value) : segment.value;
  63. }, "");
  64. }
  65. parseTargetRecursive(astNode, func) {
  66. if (astNode === null) {
  67. return null;
  68. }
  69. switch (astNode.type) {
  70. case 'function':
  71. var innerFunc = gfunc.createFuncInstance(astNode.name, { withDefaultParams: false });
  72. _.each(astNode.params, param => {
  73. this.parseTargetRecursive(param, innerFunc);
  74. });
  75. innerFunc.updateText();
  76. this.functions.push(innerFunc);
  77. break;
  78. case 'series-ref':
  79. if (this.segments.length > 0) {
  80. this.addFunctionParameter(func, astNode.value);
  81. } else {
  82. this.segments.push(astNode);
  83. }
  84. break;
  85. case 'bool':
  86. case 'string':
  87. case 'number':
  88. this.addFunctionParameter(func, astNode.value);
  89. break;
  90. case 'metric':
  91. if (this.segments.length > 0) {
  92. this.addFunctionParameter(func, _.join(_.map(astNode.segments, 'value'), '.'));
  93. } else {
  94. this.segments = astNode.segments;
  95. }
  96. break;
  97. }
  98. }
  99. updateSegmentValue(segment, index) {
  100. this.segments[index].value = segment.value;
  101. }
  102. addSelectMetricSegment() {
  103. this.segments.push({value: "select metric"});
  104. }
  105. hasSelectMetric() {
  106. return this.segments[this.segments.length - 1].value === 'select metric';
  107. }
  108. addFunction(newFunc) {
  109. this.functions.push(newFunc);
  110. this.moveAliasFuncLast();
  111. }
  112. moveAliasFuncLast() {
  113. var aliasFunc = _.find(this.functions, function(func) {
  114. return func.def.name === 'alias' ||
  115. func.def.name === 'aliasByNode' ||
  116. func.def.name === 'aliasByMetric';
  117. });
  118. if (aliasFunc) {
  119. this.functions = _.without(this.functions, aliasFunc);
  120. this.functions.push(aliasFunc);
  121. }
  122. }
  123. addFunctionParameter(func, value) {
  124. if (func.params.length >= func.def.params.length) {
  125. throw { message: 'too many parameters for function ' + func.def.name };
  126. }
  127. func.params.push(value);
  128. }
  129. removeFunction(func) {
  130. this.functions = _.without(this.functions, func);
  131. }
  132. updateModelTarget(targets) {
  133. // render query
  134. if (!this.target.textEditor) {
  135. var metricPath = this.getSegmentPathUpTo(this.segments.length).replace(/\.select metric$/, '');
  136. this.target.target = _.reduce(this.functions, wrapFunction, metricPath);
  137. }
  138. this.updateRenderedTarget(this.target, targets);
  139. // loop through other queries and update targetFull as needed
  140. for (const target of targets || []) {
  141. if (target.refId !== this.target.refId) {
  142. this.updateRenderedTarget(target, targets);
  143. }
  144. }
  145. }
  146. updateRenderedTarget(target, targets) {
  147. // render nested query
  148. var targetsByRefId = _.keyBy(targets, 'refId');
  149. // no references to self
  150. delete targetsByRefId[target.refId];
  151. var nestedSeriesRefRegex = /\#([A-Z])/g;
  152. var targetWithNestedQueries = target.target;
  153. // Keep interpolating until there are no query references
  154. // The reason for the loop is that the referenced query might contain another reference to another query
  155. while (targetWithNestedQueries.match(nestedSeriesRefRegex)) {
  156. var updated = targetWithNestedQueries.replace(nestedSeriesRefRegex, (match, g1) => {
  157. var t = targetsByRefId[g1];
  158. if (!t) {
  159. return match;
  160. }
  161. // no circular references
  162. delete targetsByRefId[g1];
  163. return t.target;
  164. });
  165. if (updated === targetWithNestedQueries) {
  166. break;
  167. }
  168. targetWithNestedQueries = updated;
  169. }
  170. delete target.targetFull;
  171. if (target.target !== targetWithNestedQueries) {
  172. target.targetFull = targetWithNestedQueries;
  173. }
  174. }
  175. splitSeriesByTagParams(func) {
  176. const tagPattern = /([^\!=~]+)([\!=~]+)([^\!=~]+)/;
  177. return _.flatten(_.map(func.params, (param: string) => {
  178. let matches = tagPattern.exec(param);
  179. if (matches) {
  180. let tag = matches.slice(1);
  181. if (tag.length === 3) {
  182. return {
  183. key: tag[0],
  184. operator: tag[1],
  185. value: tag[2]
  186. };
  187. }
  188. }
  189. return [];
  190. }));
  191. }
  192. getSeriesByTagFuncIndex() {
  193. return _.findIndex(this.functions, (func) => func.def.name === 'seriesByTag');
  194. }
  195. getSeriesByTagFunc() {
  196. let seriesByTagFuncIndex = this.getSeriesByTagFuncIndex();
  197. if (seriesByTagFuncIndex >= 0) {
  198. return this.functions[seriesByTagFuncIndex];
  199. } else {
  200. return undefined;
  201. }
  202. }
  203. addTag(tag) {
  204. let newTagParam = renderTagString(tag);
  205. this.getSeriesByTagFunc().params.push(newTagParam);
  206. this.tags.push(tag);
  207. }
  208. removeTag(index) {
  209. this.getSeriesByTagFunc().params.splice(index, 1);
  210. this.tags.splice(index, 1);
  211. }
  212. updateTag(tag, tagIndex) {
  213. this.error = null;
  214. if (tag.key === this.removeTagValue) {
  215. this.removeTag(tagIndex);
  216. return;
  217. }
  218. let newTagParam = renderTagString(tag);
  219. this.getSeriesByTagFunc().params[tagIndex] = newTagParam;
  220. this.tags[tagIndex] = tag;
  221. }
  222. renderTagExpressions(excludeIndex = -1) {
  223. return _.compact(_.map(this.tags, (tagExpr, index) => {
  224. // Don't render tag that we want to lookup
  225. if (index !== excludeIndex) {
  226. return tagExpr.key + tagExpr.operator + tagExpr.value;
  227. }
  228. }));
  229. }
  230. }
  231. function wrapFunction(target, func) {
  232. return func.render(target);
  233. }
  234. function renderTagString(tag) {
  235. return tag.key + tag.operator + tag.value;
  236. }