graphite_query.ts 8.0 KB

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