graphite_query.ts 7.1 KB

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