graphite_query.ts 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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. const parser = new Parser(this.target.target);
  31. const 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. const seriesByTagFunc = _.find(this.functions, func => func.def.name === 'seriesByTag');
  53. if (seriesByTagFunc) {
  54. this.seriesByTagUsed = true;
  55. seriesByTagFunc.hidden = true;
  56. const tags = this.splitSeriesByTagParams(seriesByTagFunc);
  57. this.tags = tags;
  58. }
  59. }
  60. getSegmentPathUpTo(index) {
  61. const 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. const 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. const 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. const 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. const targetsByRefId = _.keyBy(targets, 'refId');
  151. // no references to self
  152. delete targetsByRefId[target.refId];
  153. const nestedSeriesRefRegex = /\#([A-Z])/g;
  154. let targetWithNestedQueries = target.target;
  155. // Use ref count to track circular references
  156. function countTargetRefs(targetsByRefId, refId) {
  157. let refCount = 0;
  158. _.each(targetsByRefId, (t, id) => {
  159. if (id !== refId) {
  160. const match = nestedSeriesRefRegex.exec(t.target);
  161. const count = match && match.length ? match.length - 1 : 0;
  162. refCount += count;
  163. }
  164. });
  165. targetsByRefId[refId].refCount = refCount;
  166. }
  167. _.each(targetsByRefId, (t, id) => {
  168. countTargetRefs(targetsByRefId, id);
  169. });
  170. // Keep interpolating until there are no query references
  171. // The reason for the loop is that the referenced query might contain another reference to another query
  172. while (targetWithNestedQueries.match(nestedSeriesRefRegex)) {
  173. const updated = targetWithNestedQueries.replace(nestedSeriesRefRegex, (match, g1) => {
  174. const t = targetsByRefId[g1];
  175. if (!t) {
  176. return match;
  177. }
  178. // no circular references
  179. if (t.refCount === 0) {
  180. delete targetsByRefId[g1];
  181. }
  182. t.refCount--;
  183. return t.target;
  184. });
  185. if (updated === targetWithNestedQueries) {
  186. break;
  187. }
  188. targetWithNestedQueries = updated;
  189. }
  190. delete target.targetFull;
  191. if (target.target !== targetWithNestedQueries) {
  192. target.targetFull = targetWithNestedQueries;
  193. }
  194. }
  195. splitSeriesByTagParams(func) {
  196. const tagPattern = /([^\!=~]+)(\!?=~?)(.*)/;
  197. return _.flatten(
  198. _.map(func.params, (param: string) => {
  199. const matches = tagPattern.exec(param);
  200. if (matches) {
  201. const tag = matches.slice(1);
  202. if (tag.length === 3) {
  203. return {
  204. key: tag[0],
  205. operator: tag[1],
  206. value: tag[2],
  207. };
  208. }
  209. }
  210. return [];
  211. })
  212. );
  213. }
  214. getSeriesByTagFuncIndex() {
  215. return _.findIndex(this.functions, func => func.def.name === 'seriesByTag');
  216. }
  217. getSeriesByTagFunc() {
  218. const seriesByTagFuncIndex = this.getSeriesByTagFuncIndex();
  219. if (seriesByTagFuncIndex >= 0) {
  220. return this.functions[seriesByTagFuncIndex];
  221. } else {
  222. return undefined;
  223. }
  224. }
  225. addTag(tag) {
  226. const newTagParam = renderTagString(tag);
  227. this.getSeriesByTagFunc().params.push(newTagParam);
  228. this.tags.push(tag);
  229. }
  230. removeTag(index) {
  231. this.getSeriesByTagFunc().params.splice(index, 1);
  232. this.tags.splice(index, 1);
  233. }
  234. updateTag(tag, tagIndex) {
  235. this.error = null;
  236. if (tag.key === this.removeTagValue) {
  237. this.removeTag(tagIndex);
  238. return;
  239. }
  240. const newTagParam = renderTagString(tag);
  241. this.getSeriesByTagFunc().params[tagIndex] = newTagParam;
  242. this.tags[tagIndex] = tag;
  243. }
  244. renderTagExpressions(excludeIndex = -1) {
  245. return _.compact(
  246. _.map(this.tags, (tagExpr, index) => {
  247. // Don't render tag that we want to lookup
  248. if (index !== excludeIndex) {
  249. return tagExpr.key + tagExpr.operator + tagExpr.value;
  250. }
  251. })
  252. );
  253. }
  254. }
  255. function wrapFunction(target, func) {
  256. return func.render(target);
  257. }
  258. function renderTagString(tag) {
  259. return tag.key + tag.operator + tag.value;
  260. }