graphite_query.ts 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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. this.moveAliasFuncLast();
  117. }
  118. moveAliasFuncLast() {
  119. const aliasFunc: any = _.find(this.functions, func => {
  120. return func.def.name.startsWith('alias');
  121. });
  122. if (aliasFunc) {
  123. this.functions = _.without(this.functions, aliasFunc);
  124. this.functions.push(aliasFunc);
  125. }
  126. }
  127. addFunctionParameter(func, value) {
  128. if (func.params.length >= func.def.params.length && !_.get(_.last(func.def.params), 'multiple', false)) {
  129. throw { message: 'too many parameters for function ' + func.def.name };
  130. }
  131. func.params.push(value);
  132. }
  133. removeFunction(func) {
  134. this.functions = _.without(this.functions, func);
  135. }
  136. moveFunction(func, offset) {
  137. const index = this.functions.indexOf(func);
  138. // @ts-ignore
  139. _.move(this.functions, index, index + offset);
  140. }
  141. updateModelTarget(targets) {
  142. const wrapFunction = (target: string, func: any) => {
  143. return func.render(target, (value: string) => {
  144. return this.templateSrv.replace(value, this.scopedVars);
  145. });
  146. };
  147. if (!this.target.textEditor) {
  148. const metricPath = this.getSegmentPathUpTo(this.segments.length).replace(/\.select metric$/, '');
  149. this.target.target = _.reduce(this.functions, wrapFunction, metricPath);
  150. }
  151. this.updateRenderedTarget(this.target, targets);
  152. // loop through other queries and update targetFull as needed
  153. for (const target of targets || []) {
  154. if (target.refId !== this.target.refId) {
  155. this.updateRenderedTarget(target, targets);
  156. }
  157. }
  158. }
  159. updateRenderedTarget(target, targets) {
  160. // render nested query
  161. const targetsByRefId = _.keyBy(targets, 'refId');
  162. // no references to self
  163. delete targetsByRefId[target.refId];
  164. const nestedSeriesRefRegex = /\#([A-Z])/g;
  165. let targetWithNestedQueries = target.target;
  166. // Use ref count to track circular references
  167. function countTargetRefs(targetsByRefId, refId) {
  168. let refCount = 0;
  169. _.each(targetsByRefId, (t, id) => {
  170. if (id !== refId) {
  171. const match = nestedSeriesRefRegex.exec(t.target);
  172. const count = match && match.length ? match.length - 1 : 0;
  173. refCount += count;
  174. }
  175. });
  176. targetsByRefId[refId].refCount = refCount;
  177. }
  178. _.each(targetsByRefId, (t, id) => {
  179. countTargetRefs(targetsByRefId, id);
  180. });
  181. // Keep interpolating until there are no query references
  182. // The reason for the loop is that the referenced query might contain another reference to another query
  183. while (targetWithNestedQueries.match(nestedSeriesRefRegex)) {
  184. const updated = targetWithNestedQueries.replace(nestedSeriesRefRegex, (match, g1) => {
  185. const t = targetsByRefId[g1];
  186. if (!t) {
  187. return match;
  188. }
  189. // no circular references
  190. if (t.refCount === 0) {
  191. delete targetsByRefId[g1];
  192. }
  193. t.refCount--;
  194. return t.target;
  195. });
  196. if (updated === targetWithNestedQueries) {
  197. break;
  198. }
  199. targetWithNestedQueries = updated;
  200. }
  201. delete target.targetFull;
  202. if (target.target !== targetWithNestedQueries) {
  203. target.targetFull = targetWithNestedQueries;
  204. }
  205. }
  206. splitSeriesByTagParams(func) {
  207. const tagPattern = /([^\!=~]+)(\!?=~?)(.*)/;
  208. return _.flatten(
  209. _.map(func.params, (param: string) => {
  210. const matches = tagPattern.exec(param);
  211. if (matches) {
  212. const tag = matches.slice(1);
  213. if (tag.length === 3) {
  214. return {
  215. key: tag[0],
  216. operator: tag[1],
  217. value: tag[2],
  218. };
  219. }
  220. }
  221. return [];
  222. })
  223. );
  224. }
  225. getSeriesByTagFuncIndex() {
  226. return _.findIndex(this.functions, func => func.def.name === 'seriesByTag');
  227. }
  228. getSeriesByTagFunc() {
  229. const seriesByTagFuncIndex = this.getSeriesByTagFuncIndex();
  230. if (seriesByTagFuncIndex >= 0) {
  231. return this.functions[seriesByTagFuncIndex];
  232. } else {
  233. return undefined;
  234. }
  235. }
  236. addTag(tag) {
  237. const newTagParam = renderTagString(tag);
  238. this.getSeriesByTagFunc().params.push(newTagParam);
  239. this.tags.push(tag);
  240. }
  241. removeTag(index) {
  242. this.getSeriesByTagFunc().params.splice(index, 1);
  243. this.tags.splice(index, 1);
  244. }
  245. updateTag(tag, tagIndex) {
  246. this.error = null;
  247. if (tag.key === this.removeTagValue) {
  248. this.removeTag(tagIndex);
  249. return;
  250. }
  251. const newTagParam = renderTagString(tag);
  252. this.getSeriesByTagFunc().params[tagIndex] = newTagParam;
  253. this.tags[tagIndex] = tag;
  254. }
  255. renderTagExpressions(excludeIndex = -1) {
  256. return _.compact(
  257. _.map(this.tags, (tagExpr, index) => {
  258. // Don't render tag that we want to lookup
  259. if (index !== excludeIndex) {
  260. return tagExpr.key + tagExpr.operator + tagExpr.value;
  261. }
  262. })
  263. );
  264. }
  265. }
  266. function renderTagString(tag) {
  267. return tag.key + tag.operator + tag.value;
  268. }