template_srv.ts 8.2 KB

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