template_srv.ts 8.3 KB

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