graphite_query.ts 7.3 KB

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