template_srv.ts 7.4 KB

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