graphite_query.ts 8.1 KB

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