graphite_query.ts 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. import _ from 'lodash';
  2. import { Parser } from './parser';
  3. import { TemplateSrv } from 'app/features/templating/template_srv';
  4. import { ScopedVars } from '@grafana/ui';
  5. export default class GraphiteQuery {
  6. datasource: any;
  7. target: any;
  8. functions: any[];
  9. segments: any[];
  10. tags: any[];
  11. error: any;
  12. seriesByTagUsed: boolean;
  13. checkOtherSegmentsIndex: number;
  14. removeTagValue: string;
  15. templateSrv: any;
  16. scopedVars: any;
  17. /** @ngInject */
  18. constructor(datasource: any, target: any, templateSrv?: TemplateSrv, scopedVars?: ScopedVars) {
  19. this.datasource = datasource;
  20. this.target = target;
  21. this.templateSrv = templateSrv;
  22. this.scopedVars = scopedVars;
  23. this.parseTarget();
  24. this.removeTagValue = '-- remove tag --';
  25. }
  26. parseTarget() {
  27. this.functions = [];
  28. this.segments = [];
  29. this.tags = [];
  30. this.seriesByTagUsed = false;
  31. this.error = null;
  32. if (this.target.textEditor) {
  33. return;
  34. }
  35. const parser = new Parser(this.target.target);
  36. const astNode = parser.getAst();
  37. if (astNode === null) {
  38. this.checkOtherSegmentsIndex = 0;
  39. return;
  40. }
  41. if (astNode.type === 'error') {
  42. this.error = astNode.message + ' at position: ' + astNode.pos;
  43. this.target.textEditor = true;
  44. return;
  45. }
  46. try {
  47. this.parseTargetRecursive(astNode, null);
  48. } catch (err) {
  49. console.log('error parsing target:', err.message);
  50. this.error = err.message;
  51. this.target.textEditor = true;
  52. }
  53. this.checkOtherSegmentsIndex = this.segments.length - 1;
  54. }
  55. getSegmentPathUpTo(index: number) {
  56. const arr = this.segments.slice(0, index);
  57. return _.reduce(
  58. arr,
  59. (result, segment) => {
  60. return result ? result + '.' + segment.value : segment.value;
  61. },
  62. ''
  63. );
  64. }
  65. parseTargetRecursive(astNode: any, func: any): any {
  66. if (astNode === null) {
  67. return null;
  68. }
  69. switch (astNode.type) {
  70. case 'function':
  71. const innerFunc = this.datasource.createFuncInstance(astNode.name, {
  72. withDefaultParams: false,
  73. });
  74. _.each(astNode.params, param => {
  75. this.parseTargetRecursive(param, innerFunc);
  76. });
  77. innerFunc.updateText();
  78. this.functions.push(innerFunc);
  79. // extract tags from seriesByTag function and hide function
  80. if (innerFunc.def.name === 'seriesByTag' && !this.seriesByTagUsed) {
  81. this.seriesByTagUsed = true;
  82. innerFunc.hidden = true;
  83. this.tags = this.splitSeriesByTagParams(innerFunc);
  84. }
  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 || this.tags.length) {
  100. this.addFunctionParameter(func, _.join(_.map(astNode.segments, 'value'), '.'));
  101. } else {
  102. this.segments = astNode.segments;
  103. }
  104. break;
  105. }
  106. }
  107. updateSegmentValue(segment: any, index: number) {
  108. this.segments[index].value = segment.value;
  109. }
  110. addSelectMetricSegment() {
  111. this.segments.push({ value: 'select metric' });
  112. }
  113. addFunction(newFunc: any) {
  114. this.functions.push(newFunc);
  115. }
  116. addFunctionParameter(func: any, value: string) {
  117. if (func.params.length >= func.def.params.length && !_.get(_.last(func.def.params), 'multiple', false)) {
  118. throw { message: 'too many parameters for function ' + func.def.name };
  119. }
  120. func.params.push(value);
  121. }
  122. removeFunction(func: any) {
  123. this.functions = _.without(this.functions, func);
  124. }
  125. moveFunction(func: any, offset: number) {
  126. const index = this.functions.indexOf(func);
  127. // @ts-ignore
  128. _.move(this.functions, index, index + offset);
  129. }
  130. updateModelTarget(targets: any) {
  131. const wrapFunction = (target: string, func: any) => {
  132. return func.render(target, (value: string) => {
  133. return this.templateSrv.replace(value, this.scopedVars);
  134. });
  135. };
  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: { refId: string | number; target: any; targetFull: any }, targets: any) {
  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: any, refId: string) {
  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: string, g1: string) => {
  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: { params: any }) {
  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: { key: any; operator: string; value: string }) {
  226. const newTagParam = renderTagString(tag);
  227. this.getSeriesByTagFunc().params.push(newTagParam);
  228. this.tags.push(tag);
  229. }
  230. removeTag(index: number) {
  231. this.getSeriesByTagFunc().params.splice(index, 1);
  232. this.tags.splice(index, 1);
  233. }
  234. updateTag(tag: { key: string }, tagIndex: number) {
  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 renderTagString(tag: { key: any; operator?: any; value?: any }) {
  256. return tag.key + tag.operator + tag.value;
  257. }