graphite_query.ts 7.8 KB

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