template_srv.ts 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. import kbn from 'app/core/utils/kbn';
  2. import _ from 'lodash';
  3. import { variableRegex } from 'app/features/templating/variable';
  4. import { TimeRange, ScopedVars } from '@grafana/data';
  5. function luceneEscape(value: string) {
  6. return value.replace(/([\!\*\+\-\=<>\s\&\|\(\)\[\]\{\}\^\~\?\:\\/"])/g, '\\$1');
  7. }
  8. interface FieldAccessorCache {
  9. [key: string]: (obj: any) => any;
  10. }
  11. export class TemplateSrv {
  12. variables: any[];
  13. private regex = variableRegex;
  14. private index: any = {};
  15. private grafanaVariables: any = {};
  16. private builtIns: any = {};
  17. private timeRange: TimeRange = null;
  18. private fieldAccessorCache: FieldAccessorCache = {};
  19. constructor() {
  20. this.builtIns['__interval'] = { text: '1s', value: '1s' };
  21. this.builtIns['__interval_ms'] = { text: '100', value: '100' };
  22. this.variables = [];
  23. }
  24. init(variables: any, timeRange?: TimeRange) {
  25. this.variables = variables;
  26. this.timeRange = timeRange;
  27. this.updateIndex();
  28. }
  29. getBuiltInIntervalValue() {
  30. return this.builtIns.__interval.value;
  31. }
  32. updateIndex() {
  33. const existsOrEmpty = (value: any) => value || value === '';
  34. this.index = this.variables.reduce((acc, currentValue) => {
  35. if (currentValue.current && (currentValue.current.isNone || existsOrEmpty(currentValue.current.value))) {
  36. acc[currentValue.name] = currentValue;
  37. }
  38. return acc;
  39. }, {});
  40. if (this.timeRange) {
  41. const from = this.timeRange.from.valueOf().toString();
  42. const to = this.timeRange.to.valueOf().toString();
  43. this.index = {
  44. ...this.index,
  45. ['__from']: {
  46. current: { value: from, text: from },
  47. },
  48. ['__to']: {
  49. current: { value: to, text: to },
  50. },
  51. };
  52. }
  53. }
  54. updateTimeRange(timeRange: TimeRange) {
  55. this.timeRange = timeRange;
  56. this.updateIndex();
  57. }
  58. variableInitialized(variable: any) {
  59. this.index[variable.name] = variable;
  60. }
  61. getAdhocFilters(datasourceName: string) {
  62. let filters: any = [];
  63. if (this.variables) {
  64. for (let i = 0; i < this.variables.length; i++) {
  65. const variable = this.variables[i];
  66. if (variable.type !== 'adhoc') {
  67. continue;
  68. }
  69. // null is the "default" datasource
  70. if (variable.datasource === null || variable.datasource === datasourceName) {
  71. filters = filters.concat(variable.filters);
  72. } else if (variable.datasource.indexOf('$') === 0) {
  73. if (this.replace(variable.datasource) === datasourceName) {
  74. filters = filters.concat(variable.filters);
  75. }
  76. }
  77. }
  78. }
  79. return filters;
  80. }
  81. luceneFormat(value: any) {
  82. if (typeof value === 'string') {
  83. return luceneEscape(value);
  84. }
  85. if (value instanceof Array && value.length === 0) {
  86. return '__empty__';
  87. }
  88. const quotedValues = _.map(value, val => {
  89. return '"' + luceneEscape(val) + '"';
  90. });
  91. return '(' + quotedValues.join(' OR ') + ')';
  92. }
  93. // encode string according to RFC 3986; in contrast to encodeURIComponent()
  94. // also the sub-delims "!", "'", "(", ")" and "*" are encoded;
  95. // unicode handling uses UTF-8 as in ECMA-262.
  96. encodeURIComponentStrict(str: string) {
  97. return encodeURIComponent(str).replace(/[!'()*]/g, c => {
  98. return (
  99. '%' +
  100. c
  101. .charCodeAt(0)
  102. .toString(16)
  103. .toUpperCase()
  104. );
  105. });
  106. }
  107. formatValue(value: any, format: any, variable: any) {
  108. // for some scopedVars there is no variable
  109. variable = variable || {};
  110. if (typeof format === 'function') {
  111. return format(value, variable, this.formatValue);
  112. }
  113. switch (format) {
  114. case 'regex': {
  115. if (typeof value === 'string') {
  116. return kbn.regexEscape(value);
  117. }
  118. const escapedValues = _.map(value, kbn.regexEscape);
  119. if (escapedValues.length === 1) {
  120. return escapedValues[0];
  121. }
  122. return '(' + escapedValues.join('|') + ')';
  123. }
  124. case 'lucene': {
  125. return this.luceneFormat(value);
  126. }
  127. case 'pipe': {
  128. if (typeof value === 'string') {
  129. return value;
  130. }
  131. return value.join('|');
  132. }
  133. case 'distributed': {
  134. if (typeof value === 'string') {
  135. return value;
  136. }
  137. return this.distributeVariable(value, variable.name);
  138. }
  139. case 'csv': {
  140. if (_.isArray(value)) {
  141. return value.join(',');
  142. }
  143. return value;
  144. }
  145. case 'json': {
  146. return JSON.stringify(value);
  147. }
  148. case 'percentencode': {
  149. // like glob, but url escaped
  150. if (_.isArray(value)) {
  151. return this.encodeURIComponentStrict('{' + value.join(',') + '}');
  152. }
  153. return this.encodeURIComponentStrict(value);
  154. }
  155. default: {
  156. if (_.isArray(value) && value.length > 1) {
  157. return '{' + value.join(',') + '}';
  158. }
  159. return value;
  160. }
  161. }
  162. }
  163. setGrafanaVariable(name: string, value: any) {
  164. this.grafanaVariables[name] = value;
  165. }
  166. getVariableName(expression: string) {
  167. this.regex.lastIndex = 0;
  168. const match = this.regex.exec(expression);
  169. if (!match) {
  170. return null;
  171. }
  172. const variableName = match.slice(1).find(match => match !== undefined);
  173. return variableName;
  174. }
  175. variableExists(expression: string) {
  176. const name = this.getVariableName(expression);
  177. return name && this.index[name] !== void 0;
  178. }
  179. highlightVariablesAsHtml(str: string) {
  180. if (!str || !_.isString(str)) {
  181. return str;
  182. }
  183. str = _.escape(str);
  184. this.regex.lastIndex = 0;
  185. return str.replace(this.regex, (match, var1, var2, fmt2, var3) => {
  186. if (this.index[var1 || var2 || var3] || this.builtIns[var1 || var2 || var3]) {
  187. return '<span class="template-variable">' + match + '</span>';
  188. }
  189. return match;
  190. });
  191. }
  192. getAllValue(variable: any) {
  193. if (variable.allValue) {
  194. return variable.allValue;
  195. }
  196. const values = [];
  197. for (let i = 1; i < variable.options.length; i++) {
  198. values.push(variable.options[i].value);
  199. }
  200. return values;
  201. }
  202. getFieldAccessor(fieldPath: string) {
  203. const accessor = this.fieldAccessorCache[fieldPath];
  204. if (accessor) {
  205. return accessor;
  206. }
  207. return (this.fieldAccessorCache[fieldPath] = _.property(fieldPath));
  208. }
  209. getVariableValue(variableName: string, fieldPath: string | undefined, scopedVars: ScopedVars) {
  210. const scopedVar = scopedVars[variableName];
  211. if (!scopedVar) {
  212. return null;
  213. }
  214. if (fieldPath) {
  215. return this.getFieldAccessor(fieldPath)(scopedVar.value);
  216. }
  217. return scopedVar.value;
  218. }
  219. replace(target: string, scopedVars?: ScopedVars, format?: string | Function): any {
  220. if (!target) {
  221. return target;
  222. }
  223. this.regex.lastIndex = 0;
  224. return target.replace(this.regex, (match, var1, var2, fmt2, var3, fieldPath, fmt3) => {
  225. const variableName = var1 || var2 || var3;
  226. const variable = this.index[variableName];
  227. const fmt = fmt2 || fmt3 || format;
  228. if (scopedVars) {
  229. const value = this.getVariableValue(variableName, fieldPath, scopedVars);
  230. if (value !== null && value !== undefined) {
  231. return this.formatValue(value, fmt, variable);
  232. }
  233. }
  234. if (!variable) {
  235. return match;
  236. }
  237. const systemValue = this.grafanaVariables[variable.current.value];
  238. if (systemValue) {
  239. return this.formatValue(systemValue, fmt, variable);
  240. }
  241. let value = variable.current.value;
  242. if (this.isAllValue(value)) {
  243. value = this.getAllValue(variable);
  244. // skip formatting of custom all values
  245. if (variable.allValue) {
  246. return this.replace(value);
  247. }
  248. }
  249. const res = this.formatValue(value, fmt, variable);
  250. return res;
  251. });
  252. }
  253. isAllValue(value: any) {
  254. return value === '$__all' || (Array.isArray(value) && value[0] === '$__all');
  255. }
  256. replaceWithText(target: string, scopedVars: ScopedVars) {
  257. if (!target) {
  258. return target;
  259. }
  260. let variable;
  261. this.regex.lastIndex = 0;
  262. return target.replace(this.regex, (match: any, var1: any, var2: any, fmt2: any, var3: any) => {
  263. if (scopedVars) {
  264. const option = scopedVars[var1 || var2 || var3];
  265. if (option) {
  266. return option.text;
  267. }
  268. }
  269. variable = this.index[var1 || var2 || var3];
  270. if (!variable) {
  271. return match;
  272. }
  273. const value = this.grafanaVariables[variable.current.value];
  274. return typeof value === 'string' ? value : variable.current.text;
  275. });
  276. }
  277. fillVariableValuesForUrl(params: any, scopedVars?: ScopedVars) {
  278. _.each(this.variables, variable => {
  279. if (scopedVars && scopedVars[variable.name] !== void 0) {
  280. if (scopedVars[variable.name].skipUrlSync) {
  281. return;
  282. }
  283. params['var-' + variable.name] = scopedVars[variable.name].value;
  284. } else {
  285. if (variable.skipUrlSync) {
  286. return;
  287. }
  288. params['var-' + variable.name] = variable.getValueForUrl();
  289. }
  290. });
  291. }
  292. distributeVariable(value: any, variable: any) {
  293. value = _.map(value, (val: any, index: number) => {
  294. if (index !== 0) {
  295. return variable + '=' + val;
  296. } else {
  297. return val;
  298. }
  299. });
  300. return value.join(',');
  301. }
  302. }
  303. export default new TemplateSrv();