template_srv.ts 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. import kbn from 'app/core/utils/kbn';
  2. import _ from 'lodash';
  3. import { variableRegex } from 'app/features/templating/variable';
  4. import { TimeRange } 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 'percentencode': {
  139. // like glob, but url escaped
  140. if (_.isArray(value)) {
  141. return this.encodeURIComponentStrict('{' + value.join(',') + '}');
  142. }
  143. return this.encodeURIComponentStrict(value);
  144. }
  145. default: {
  146. if (_.isArray(value)) {
  147. return '{' + value.join(',') + '}';
  148. }
  149. return value;
  150. }
  151. }
  152. }
  153. setGrafanaVariable(name, value) {
  154. this.grafanaVariables[name] = value;
  155. }
  156. getVariableName(expression) {
  157. this.regex.lastIndex = 0;
  158. const match = this.regex.exec(expression);
  159. if (!match) {
  160. return null;
  161. }
  162. const variableName = match.slice(1).find(match => match !== undefined);
  163. return variableName;
  164. }
  165. variableExists(expression) {
  166. const name = this.getVariableName(expression);
  167. return name && this.index[name] !== void 0;
  168. }
  169. highlightVariablesAsHtml(str) {
  170. if (!str || !_.isString(str)) {
  171. return str;
  172. }
  173. str = _.escape(str);
  174. this.regex.lastIndex = 0;
  175. return str.replace(this.regex, (match, var1, var2, fmt2, var3) => {
  176. if (this.index[var1 || var2 || var3] || this.builtIns[var1 || var2 || var3]) {
  177. return '<span class="template-variable">' + match + '</span>';
  178. }
  179. return match;
  180. });
  181. }
  182. getAllValue(variable) {
  183. if (variable.allValue) {
  184. return variable.allValue;
  185. }
  186. const values = [];
  187. for (let i = 1; i < variable.options.length; i++) {
  188. values.push(variable.options[i].value);
  189. }
  190. return values;
  191. }
  192. replace(target, scopedVars?, format?) {
  193. if (!target) {
  194. return target;
  195. }
  196. let variable, systemValue, value, fmt;
  197. this.regex.lastIndex = 0;
  198. return target.replace(this.regex, (match, var1, var2, fmt2, var3, fmt3) => {
  199. variable = this.index[var1 || var2 || var3];
  200. fmt = fmt2 || fmt3 || format;
  201. if (scopedVars) {
  202. value = scopedVars[var1 || var2 || var3];
  203. if (value) {
  204. return this.formatValue(value.value, fmt, variable);
  205. }
  206. }
  207. if (!variable) {
  208. return match;
  209. }
  210. systemValue = this.grafanaVariables[variable.current.value];
  211. if (systemValue) {
  212. return this.formatValue(systemValue, fmt, variable);
  213. }
  214. value = variable.current.value;
  215. if (this.isAllValue(value)) {
  216. value = this.getAllValue(variable);
  217. // skip formatting of custom all values
  218. if (variable.allValue) {
  219. return this.replace(value);
  220. }
  221. }
  222. const res = this.formatValue(value, fmt, variable);
  223. return res;
  224. });
  225. }
  226. isAllValue(value) {
  227. return value === '$__all' || (Array.isArray(value) && value[0] === '$__all');
  228. }
  229. replaceWithText(target, scopedVars) {
  230. if (!target) {
  231. return target;
  232. }
  233. let variable;
  234. this.regex.lastIndex = 0;
  235. return target.replace(this.regex, (match, var1, var2, fmt2, var3) => {
  236. if (scopedVars) {
  237. const option = scopedVars[var1 || var2 || var3];
  238. if (option) {
  239. return option.text;
  240. }
  241. }
  242. variable = this.index[var1 || var2 || var3];
  243. if (!variable) {
  244. return match;
  245. }
  246. const value = this.grafanaVariables[variable.current.value];
  247. return typeof value === 'string' ? value : variable.current.text;
  248. });
  249. }
  250. fillVariableValuesForUrl(params, scopedVars?) {
  251. _.each(this.variables, variable => {
  252. if (scopedVars && scopedVars[variable.name] !== void 0) {
  253. if (scopedVars[variable.name].skipUrlSync) {
  254. return;
  255. }
  256. params['var-' + variable.name] = scopedVars[variable.name].value;
  257. } else {
  258. if (variable.skipUrlSync) {
  259. return;
  260. }
  261. params['var-' + variable.name] = variable.getValueForUrl();
  262. }
  263. });
  264. }
  265. distributeVariable(value, variable) {
  266. value = _.map(value, (val, index) => {
  267. if (index !== 0) {
  268. return variable + '=' + val;
  269. } else {
  270. return val;
  271. }
  272. });
  273. return value.join(',');
  274. }
  275. }
  276. export default new TemplateSrv();