template_srv.ts 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. import kbn from 'app/core/utils/kbn';
  2. import _ from 'lodash';
  3. function luceneEscape(value) {
  4. return value.replace(/([\!\*\+\-\=<>\s\&\|\(\)\[\]\{\}\^\~\?\:\\/"])/g, '\\$1');
  5. }
  6. export class TemplateSrv {
  7. variables: any[];
  8. /*
  9. * This regex matches 3 types of variable reference with an optional format specifier
  10. * \$(\w+) $var1
  11. * \[\[([\s\S]+?)(?::(\w+))?\]\] [[var2]] or [[var2:fmt2]]
  12. * \${(\w+)(?::(\w+))?} ${var3} or ${var3:fmt3}
  13. */
  14. private regex = /\$(\w+)|\[\[([\s\S]+?)(?::(\w+))?\]\]|\${(\w+)(?::(\w+))?}/g;
  15. private index = {};
  16. private grafanaVariables = {};
  17. private builtIns = {};
  18. constructor() {
  19. this.builtIns['__interval'] = { text: '1s', value: '1s' };
  20. this.builtIns['__interval_ms'] = { text: '100', value: '100' };
  21. }
  22. init(variables) {
  23. this.variables = variables;
  24. this.updateTemplateData();
  25. }
  26. updateTemplateData() {
  27. this.index = {};
  28. for (let i = 0; i < this.variables.length; i++) {
  29. const variable = this.variables[i];
  30. if (!variable.current || (!variable.current.isNone && !variable.current.value)) {
  31. continue;
  32. }
  33. this.index[variable.name] = variable;
  34. }
  35. }
  36. variableInitialized(variable) {
  37. this.index[variable.name] = variable;
  38. }
  39. getAdhocFilters(datasourceName) {
  40. let filters = [];
  41. for (let i = 0; i < this.variables.length; i++) {
  42. const variable = this.variables[i];
  43. if (variable.type !== 'adhoc') {
  44. continue;
  45. }
  46. if (variable.datasource === datasourceName) {
  47. filters = filters.concat(variable.filters);
  48. }
  49. if (variable.datasource.indexOf('$') === 0) {
  50. if (this.replace(variable.datasource) === datasourceName) {
  51. filters = filters.concat(variable.filters);
  52. }
  53. }
  54. }
  55. return filters;
  56. }
  57. luceneFormat(value) {
  58. if (typeof value === 'string') {
  59. return luceneEscape(value);
  60. }
  61. if (value instanceof Array && value.length === 0) {
  62. return '__empty__';
  63. }
  64. const quotedValues = _.map(value, function(val) {
  65. return '"' + luceneEscape(val) + '"';
  66. });
  67. return '(' + quotedValues.join(' OR ') + ')';
  68. }
  69. // like encodeURIComponent() but for all characters except alpha-numerics
  70. encodeURIQueryValue(str) {
  71. return str.replace(/[^a-z0-9]/gi, function(c) {
  72. return '%' + c.charCodeAt(0).toString(16);
  73. });
  74. }
  75. formatValue(value, format, variable) {
  76. // for some scopedVars there is no variable
  77. variable = variable || {};
  78. if (typeof format === 'function') {
  79. return format(value, variable, this.formatValue);
  80. }
  81. switch (format) {
  82. case 'regex': {
  83. if (typeof value === 'string') {
  84. return kbn.regexEscape(value);
  85. }
  86. const escapedValues = _.map(value, kbn.regexEscape);
  87. if (escapedValues.length === 1) {
  88. return escapedValues[0];
  89. }
  90. return '(' + escapedValues.join('|') + ')';
  91. }
  92. case 'lucene': {
  93. return this.luceneFormat(value);
  94. }
  95. case 'pipe': {
  96. if (typeof value === 'string') {
  97. return value;
  98. }
  99. return value.join('|');
  100. }
  101. case 'distributed': {
  102. if (typeof value === 'string') {
  103. return value;
  104. }
  105. return this.distributeVariable(value, variable.name);
  106. }
  107. case 'csv': {
  108. if (_.isArray(value)) {
  109. return value.join(',');
  110. }
  111. return value;
  112. }
  113. case 'percentencode': {
  114. // like glob, but url escaped
  115. if (_.isArray(value)) {
  116. return this.encodeURIQueryValue('{' + value.join(',') + '}');
  117. }
  118. return this.encodeURIQueryValue(value);
  119. }
  120. default: {
  121. if (_.isArray(value)) {
  122. return '{' + value.join(',') + '}';
  123. }
  124. return value;
  125. }
  126. }
  127. }
  128. setGrafanaVariable(name, value) {
  129. this.grafanaVariables[name] = value;
  130. }
  131. getVariableName(expression) {
  132. this.regex.lastIndex = 0;
  133. const match = this.regex.exec(expression);
  134. if (!match) {
  135. return null;
  136. }
  137. return match[1] || match[2];
  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, function(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, function(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();